diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs index c906f88..2f1608b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs @@ -310,6 +310,8 @@ public partial class BuffManager : IDisposable private const double BusyHealRetryMs = 1500; // Refusals in a row (with backoff, about 3.5 s or more) before StopCompletely: longer than any real gesture. private const int BusyStopAtStreak = 4; + // The player's hand-cast refusal line was logged for this run (cleared by a refusal outside one). + private bool _handRefusalLogged; // "Not enough mana" refusal (see OnChatWindowText): the refused family rests // briefly and buffing pauses; neither is a silent-no-show strike. @@ -4493,7 +4495,7 @@ public partial class BuffManager : IDisposable /// /// Buffing's built-in list (no buff profile chosen): creature mastery, Focus, Willpower and - /// Life Magic Mastery first, the other creature buffs for usable skills, life protections, + /// Life Magic Mastery first, then Mana Conversion Mastery, the other creature buffs for usable skills, life protections, /// weapon auras, armor banes. Pump thread: it reads the character's skills. /// internal List BuildBuiltInBuffList() => BuildBuiltInBuffList(out _); @@ -4507,6 +4509,7 @@ public partial class BuffManager : IDisposable var step2_Focus = new List(); var step3_Willpower = new List(); var step3b_LifeMastery = new List(); + var step3c_ManaConversion = new List(); var step4_OtherCreature = new List(); var step5_LifeAndItem = new List(); var step6_WeaponAuras = new List(); @@ -4529,6 +4532,12 @@ public partial class BuffManager : IDisposable } if (kvp.Value.Contains("Creature Enchantment Mastery")) step1_CreatureMastery.Add(kvp.Value); + // Right after the four that raise casting skill (R-20261119-195743-1993): Mana Conversion + // lowers what every buff after it costs, and it came near the end of the creature buffs. + // Not before Focus and Willpower: it is a creature spell, and cast before they raise the + // skill it would land a level low and be recast in the same run (the upgrade pass). + else if (kvp.Value == "Mana Conversion Mastery") + step3c_ManaConversion.Add(kvp.Value); else if (kvp.Value == "Life Magic Mastery") step3b_LifeMastery.Add(kvp.Value); else if (!BaseCreatureBuffs.Contains(kvp.Value)) @@ -4570,6 +4579,7 @@ public partial class BuffManager : IDisposable final.AddRange(step2_Focus); final.AddRange(step3_Willpower); final.AddRange(step3b_LifeMastery); // the four that raise casting skill and mana come first + final.AddRange(step3c_ManaConversion); // then what cheapens every cast after it final.AddRange(step4_OtherCreature); final.AddRange(step5_LifeAndItem); final.AddRange(step6_WeaponAuras); @@ -4725,6 +4735,23 @@ public partial class BuffManager : IDisposable // construction → 0x00460D1D killed regardless of gate precision. if (lower.Contains("you're too busy") || lower.Contains("you are too busy")) { + // The player casting by hand (2026-11-18, R-20261118-214609-a9a8 / R-20261118-205826-9c70): + // this is the refusal of the player's own click from AC's spell bar, not of anything RynthAi + // sent (RynthAi starts nothing while the player casts, ActionPacer.HandCastHolds). Counting it + // escalated the backoff to 8 s and, at the 4th, sent StopCompletely into the cast that was + // running (the player's, or RynthAi's own), which can drop it. A kit or buff of ours still + // waiting keeps waiting for its own result or give-up time. + if (ActionPacer.HandCasting(_host)) + { + ObserveLastUseDone(); + if (!_handRefusalLogged) + { + _handRefusalLogged = true; + _host.Log("[BuffChat] 'You're too busy!' answers the player's own cast by hand (AC's spell bar or a hotkey), not RynthAi's: no backoff, no stop, pending kept."); + } + return; + } + _handRefusalLogged = false; // A kit in flight with no result yet: this is its refusal (see KitRefused). Our bot // sends nothing else while a kit is pending (CheckVitals returns at KitPending). if (_kitUsedAt != DateTime.MinValue && _kitLandedAt == DateTime.MinValue diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.OutOfReach.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.OutOfReach.cs new file mode 100644 index 0000000..9bf8ac3 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.OutOfReach.cs @@ -0,0 +1,74 @@ +// ============================================================================ +// RynthSuite - Combat/CombatManager.OutOfReach.cs +// A target past the attack's reach (2026-11-19, R-20261119-155301-121a, 2026.11.15.3). +// +// Back from a death, a caster held an Olthoi Hive Warrior 88 m off: every Incantation of Force +// Arc at it came back UseDone 0x550 (ACE's MissileOutOfRange, the client's "Out of Range!") +// about 60 ms after the send, and combat cast again at once: 1,027 casts since the last kill, +// about 12 a second, for well over a minute. The no-damage count never got there, because a cast +// sent inside the last one's 500 ms refusal window restarts that window, and the target was in the +// scan because Monster Range reached past the spell's own range. The server's answer says it +// plainly: from here, this attack can't reach it. +// +// Now one such answer drops the target and leaves it out of the scan while it is no nearer than +// OutOfReachCloserM inside the distance it was refused at, for OutOfReachSkipSec at most. Said +// once in chat per target. The hunt still walks toward it (it doesn't read this), so closing in +// brings it back. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.RynthAi; + +public partial class CombatManager +{ + /// ACE's MissileOutOfRange, as a UseDone error ("Out of Range!"): the attack can't reach the target from here. + internal const uint MissileOutOfRangeErr = 0x550; + /// A target refused as out of range stays out of the scan at most this long. + internal const double OutOfReachSkipSec = 60; + /// ...and only while it is no nearer than this inside the distance it was refused at (meters). + internal const double OutOfReachCloserM = 3; + + private readonly Dictionary _outOfReach = new(); + private int _outOfReachSaidId; + + /// The server answered an attack at MissileOutOfRange. + private void NoteOutOfReach(int target) + { + double dist = _worldFilter.Distance(unchecked((int)_playerId), target); + if (dist >= double.MaxValue) return; // no positions: nothing to measure "nearer" against + DateTime now = RynthClock.Now; + if (_outOfReach.Count >= 64) PruneOutOfReach(now); + _outOfReach[target] = (dist, now.AddSeconds(OutOfReachSkipSec)); + string name = _worldFilter[target]?.Name ?? $"0x{(uint)target:X8}"; + string why = $"out of range at {dist:0} m (the server answered 'Out of Range!', UseDone 0x550): " + + $"left until it is within {Math.Max(0, dist - OutOfReachCloserM):0} m, {OutOfReachSkipSec:0} s at most"; + _host.Log($"[CombatTarget] 0x{(uint)target:X8} '{name}' {why}"); + if (_outOfReachSaidId != target) + { + _outOfReachSaidId = target; + _host.WriteToChat($"[RynthAi] {name} is out of range at {dist:0} yd: fighting others until it comes closer" + + (dist <= _settings.MonsterRange ? $" (Monster Range {_settings.MonsterRange:0} reaches past the attack)." : "."), 1); + } + if (target == activeTargetId) DropTarget(why); + } + + /// The scan leaves out: refused as out of range, and no nearer yet. + private bool IsOutOfReach(int id, double dist) + { + if (_outOfReach.Count == 0 || !_outOfReach.TryGetValue(id, out var e)) return false; + if (RynthClock.Now < e.Until && dist > e.Distance - OutOfReachCloserM) return true; + _outOfReach.Remove(id); + return false; + } + + private readonly List _outOfReachPrune = new(); + private void PruneOutOfReach(DateTime now) + { + _outOfReachPrune.Clear(); + foreach (var kv in _outOfReach) + if (now >= kv.Value.Until) _outOfReachPrune.Add(kv.Key); + foreach (int id in _outOfReachPrune) _outOfReach.Remove(id); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs index cbadd1c..598e3e6 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.PassedOver.cs @@ -55,6 +55,7 @@ public partial class CombatManager internal const string PassedOverNeverAttack = "on the never-attack list"; internal const string PassedOverGhost = "a ghost (the server doesn't have it)"; internal const string PassedOverEnvironment = "left for hitting the environment"; + internal const string PassedOverOutOfReach = "out of range of the attack (the server said so), no nearer yet"; internal const string PassedOverNotAttackable = "not attackable"; /// Tests: the LOS verdict per monster instead of the ray test (true = blocked). diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs index 8b023ff..8ff7cb1 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs @@ -267,6 +267,9 @@ public partial class CombatManager : IDisposable // Grace period: keep activeTargetId alive for this long after it disappears from scan, // so a single bad LOS result or scan gap doesn't hand control to navigation. private DateTime _targetLostScanTime = DateTime.MinValue; + // The last scan that left the fight target out for a wall in the way: the drop line says why + // (R-20261119-114214-b9ed: "scan grace expired" didn't say it was line of sight). + private DateTime _engagedLosBlockedAt = DateTime.MinValue; private const double TARGET_SCAN_GRACE_MS = 1500.0; // The locked target (see HandleCombatTrigger: with Target Lock on it is held until it dies, @@ -1229,6 +1232,13 @@ public partial class CombatManager : IDisposable continue; } + // Refused 'Out of Range!' and no nearer since (CombatManager.OutOfReach.cs). + if (IsOutOfReach(wo.Id, dist)) + { + if (notePassed) NotePassedOver(wo.Id, dist, PassedOverOutOfReach); + continue; + } + // Just killed (KillerNotification) but not yet a corpse — skip so we // don't re-lock and cast at it during its death animation. if (_recentlyKilled.ContainsKey(wo.Id)) continue; @@ -1298,6 +1308,7 @@ public partial class CombatManager : IDisposable if (losBlocked) { _nearbyNoLos++; // in range + attackable but wall-blocked — still stops nav + if (isEngaged) _engagedLosBlockedAt = RynthClock.Now; if (notePassed) NotePassedOver(wo.Id, dist, PassedOverLos); continue; } @@ -1484,6 +1495,7 @@ public partial class CombatManager : IDisposable private void NoteOffensiveAnswer(int target, uint err) { if (target == 0) return; + if (err == MissileOutOfRangeErr) NoteOutOfReach(target); // CombatManager.OutOfReach.cs if (err != TargetNotAcquiredErr) { // A 'too busy' says nothing about the target; any other answer means the server has it. @@ -2000,7 +2012,10 @@ public partial class CombatManager : IDisposable // count toward the blacklist miss streak. Clear pending silently // so JudgePendingOffensiveCast's 500ms no-too-busy window stays // honest, and the next attempt can be issued under the throttle. - if (lo.Contains("you're too busy") || lo.Contains("you are too busy")) + // The player's own click refused while our cast runs (2026-11-18, R-20261118-205826-9c70, + // 15:52:54-58: refusals of 'Casting Incantation of Force Streak' during our Force Arc, which + // hit) is not ours: our cast stays pending and counted. + if ((lo.Contains("you're too busy") || lo.Contains("you are too busy")) && !ActionPacer.HandCasting(_host)) { _pendingOffensiveSpellId = 0; _pendingOffensiveTargetId = 0; @@ -2092,8 +2107,10 @@ public partial class CombatManager : IDisposable // Refused mid-gesture: the debuff never went out, so don't let the result timeout // mark it as landed. Retry it (counted, so a refusal loop can't run forever). - if (text.IndexOf("you're too busy", StringComparison.OrdinalIgnoreCase) >= 0 - || text.IndexOf("you are too busy", StringComparison.OrdinalIgnoreCase) >= 0) + // Not when it is the player's own cast by hand that was refused (2026-11-18): our debuff is running. + if ((text.IndexOf("you're too busy", StringComparison.OrdinalIgnoreCase) >= 0 + || text.IndexOf("you are too busy", StringComparison.OrdinalIgnoreCase) >= 0) + && !ActionPacer.HandCasting(_host)) { NoteDebuffFailed("Refused"); return; @@ -3002,22 +3019,43 @@ public partial class CombatManager : IDisposable float curHp = tid != 0 ? _worldFilter.GetHealthRatio(tid) : -1f; bool curServerAlive = curHp > 0f && !_worldFilter.IsHealthEstimated(tid); bool noticeForNeighbour = otherVictim != 0 && curServerAlive; - if (tid != 0 && curMatches && (noticeForSwappedMob || !curAttacked || noticeForNeighbour)) + // 2026-11-18, R-20261118-012228-179f (DreamWeave, melee, a pack of same-named Olthoi): the + // fight target was dropped as dead twice in 4 s while it was alive and fighting. The weapon + // cleaves: each swing hits the target and a same-named neighbour, and in Melee mode every + // damage line naming the target is the target's (ResolveHitVictim), so the neighbour is + // never "hit by us" and FindRecentlyHitVictim finds no one when the neighbour dies. The + // notice was the target's, the target was dropped, kept off the scan for 4 s, and the bot + // swung at the next one (the "dead" target was back in the scan exactly 4 s later). But + // the server said the target was alive: combat's QueryHealth makes it the server's + // selection, so ACE pushes its health with every hit, the lethal one too (DamageHistory.Add + // sends the 0 before OnDeath sends the notice), and a cleave strikes the aimed target first. + // A server health that came with or after our last hit on it, above 0, means the notice is + // a neighbour's even when we can't say which. The health is asked again: a target that did + // die some other way (a damage-over-time tick sends no health) answers 0 and is dropped as + // "hp=0" on the next tick. + bool aliveByFreshHealth = !noticeForNeighbour && tid != 0 && curMatches && curServerAlive + && _fightTargetId == tid && TryFreshFightHealth(out float freshHp) && freshHp > 0f; + if (tid != 0 && curMatches && (noticeForSwappedMob || !curAttacked || noticeForNeighbour || aliveByFreshHealth)) { _host.Log($"[RynthAi] Kill notice names 0x{tid:X8} '{curName}' but " + (noticeForSwappedMob ? $"belongs to predicted kill 0x{pendingKillId:X8}" : noticeForNeighbour ? $"it is alive ({curHp:0.00}); a neighbour we hit died (0x{otherVictim:X8})" + : aliveByFreshHealth ? $"the server says it is alive ({DescribeFightHealthAge()}); a same-named monster near it died (a cleave, a pet, a ring), not known which; its health is asked again" : "it hasn't been attacked yet") + " — keeping the target"); if (noticeForNeighbour) SuppressGuessedDeath(otherVictim, nowKill); + if (aliveByFreshHealth) + try { if (_host.HasQueryHealth) _host.QueryHealth((uint)tid); } catch { } } else if (tid != 0 && curMatches) { _recentlyKilled[tid] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS); NoteConfirmedKill(tid, nowKill); ForgetScanned(tid); - DropTarget("killed (KillerNotification)"); + // The server health it was dropped on, so a report shows whether the drop was sure + // (R-20261118-012228-179f). + DropTarget($"killed (KillerNotification; {(_fightTargetId == tid ? DescribeFightHealthAge() : "not the fight being tracked")})"); } else if (pendingKillId == 0) { @@ -3376,6 +3414,18 @@ public partial class CombatManager : IDisposable || _fightHealthAt >= _fightLastHitAt.AddMilliseconds(-FightHealthHitSlackMs); } + /// The fight target's last server health and how old it and our last hit on it are, for + /// the kill-notice log lines (R-20261118-012228-179f): "server health 0.61 40 ms ago, last hit + /// 35 ms ago", or "no server health this fight". + private string DescribeFightHealthAge() + { + if (_fightHealthAt == DateTime.MinValue) return "no server health this fight"; + DateTime now = TargetClock(); + string hit = _fightLastHitAt == DateTime.MinValue ? "no hit yet" + : $"last hit {(now - _fightLastHitAt).TotalMilliseconds:0} ms ago"; + return $"server health {_fightHealth:0.00} {(now - _fightHealthAt).TotalMilliseconds:0} ms ago, {hit}"; + } + /// /// The evidence says the cast just fired can't finish the fight target: what is left of it is more /// than KILL_VETO_REACH casts of . Two sources, either one enough: @@ -3819,7 +3869,9 @@ public partial class CombatManager : IDisposable _targetLostScanTime = RynthClock.Now; if ((RynthClock.Now - _targetLostScanTime).TotalMilliseconds > TARGET_SCAN_GRACE_MS) - DropTarget("scan grace expired"); + DropTarget((RynthClock.Now - _engagedLosBlockedAt).TotalMilliseconds <= TARGET_SCAN_GRACE_MS + ? "scan grace expired (out of sight: the line-of-sight check finds a wall in the way)" + : "scan grace expired"); return true; } _targetLostScanTime = DateTime.MinValue; // back in scan — reset grace timer diff --git a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs index 1487f99..a98987b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/CorpseOpenController.cs @@ -1018,6 +1018,22 @@ public sealed partial class RynthAiPlugin } return; } + // AutoCram's or AutoStack's move has no answer yet (2026-11-18, R-20261117-230613-88c5). The + // cram runs on the first tick after a corpse is released, and this open went out 1-3 ms + // after it: the client still held the cram in its one pending item request, refused the use + // ("You can only move or use one item at a time") and sent nothing, and the looter waited + // 5 s for an answer before opening it again. The answer takes 50-300 ms; the claim's clock + // stops meanwhile (as for the salvage panel above). + if (ItemMoveHold() is string moveHold) + { + FreezeCorpseTimeout(now); + if (_openHeldByMoveLoggedFor != _targetCorpseId) + { + _openHeldByMoveLoggedFor = _targetCorpseId; + LootDiag($"[RynthAi] Corpse loot: open of 0x{(uint)_targetCorpseId:X8} waits: {moveHold} (the client takes one item action at a time)."); + } + return; + } // A starved turn's open waits for combat's first attack at a target it has just locked // (2026-11-15, R-20261115-165857-1de7). A monster came into range 0.4 s after the claim, // the starved turn kept Looting (none within 5 yd), and the open went out 0.3 s after the @@ -1108,6 +1124,7 @@ public sealed partial class RynthAiPlugin private long _corpseOpenBusyWaitSince; private bool _openHeldBySalvageLogged; + private int _openHeldByMoveLoggedFor; // the corpse whose open waited for AutoCram's/AutoStack's move (logged once) private int _openHeldForAttackLoggedFor; // the corpse whose open waited for combat's first attack (logged once) /// A starved turn's open waits this long at most for combat's first attack at a fresh lock diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs index 7978c56..ca49c17 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs @@ -497,13 +497,26 @@ internal sealed partial class LegacyDashboardRenderer RefreshAllLists(); - // Load MonsterRules from monsters.json (overrides what was in the profile) - // and migrate existing rules to that file if it doesn't exist yet. + // The Monsters rules belong to the profile (2026-11-18). The MonsterProfiles file is the + // active profile's copy, kept for the Monster Editor and tagged with that profile's name. + // It overrides the profile's rules only when it is this profile's copy (or untagged, from + // before the tag: then it was the one list every profile used). Another profile's copy is + // replaced by this profile's rules. Before, the file always won, so a reload or relog + // brought back the rules last edited under another profile. MigrateMonstersToFile(); - LoadMonstersFromFile(); + string? monstersOwner = ReadMonstersOwner(); + bool fileIsOurs = monstersOwner == null || monstersOwner.Equals(activeProfile, StringComparison.OrdinalIgnoreCase); + if (fileIsOurs) LoadMonstersFromFile(); // Always re-insert the catch-all "Default" rule at index 0; without it the // combat system has no fallback weapon/damage selection for unmatched mobs. _settings.EnsureDefaultRule(); + if (!fileIsOurs) + { + _host.Log($"[RynthAi] Monsters: the Monsters file held profile '{monstersOwner}''s rules; using profile '{activeProfile}''s own."); + SaveMonstersFile(); + } + else if (monstersOwner == null && File.Exists(MonstersFilePath)) + WriteMonstersOwner(); SetupMonsterWatcher(); if (holdUnreadable) @@ -1012,6 +1025,31 @@ internal sealed partial class LegacyDashboardRenderer LoadMonstersFromFile(); } + // Which profile the MonsterProfiles file belongs to: ".profile", one line, the profile name. + // A separate file so the rules file keeps the shape the Monster Editor reads and writes. + private string MonstersOwnerPath => MonstersFilePath.Length == 0 ? string.Empty : MonstersFilePath + ".profile"; + + /// The profile the Monsters file was written for; null when it isn't tagged (or there's no file). + private string? ReadMonstersOwner() + { + try + { + string path = MonstersOwnerPath; + if (path.Length == 0 || !File.Exists(path)) return null; + string name = File.ReadAllText(path).Trim(); + return name.Length > 0 ? name : null; + } + catch { return null; } + } + + private void WriteMonstersOwner() + { + string path = MonstersOwnerPath; + string profile = _settings.SelectedProfile ?? string.Empty; + if (path.Length == 0 || profile.Length == 0) return; + try { File.WriteAllText(path, profile); } catch { } + } + /// Saves the Monsters rules after a change made outside the panel (a chat command). public void SaveMonsterRules() => SaveMonstersFile(); @@ -1037,6 +1075,7 @@ internal sealed partial class LegacyDashboardRenderer Directory.CreateDirectory(_monstersFolder); File.WriteAllText(path, json); }); + WriteMonstersOwner(); if (_monsterWatcher != null) _monsterWatcher.EnableRaisingEvents = wasEnabled; @@ -1832,6 +1871,7 @@ internal sealed partial class LegacyDashboardRenderer EnableManaTapping = _settings.EnableManaTapping, ManaTapMinMana = _settings.ManaTapMinMana, ManaStoneKeepCount = _settings.ManaStoneKeepCount, + ManaTapMacroOff = _settings.ManaTapMacroOff, CurrentTargetName = _currentTargetId != 0 ? (_targetLabel ?? string.Empty) : string.Empty, // The engine's Items face marks these "(missing)"; display only (ApplyItemsJson ignores it). MissingIds = MissingWeaponIds().OrderBy(id => id).ToList(), @@ -1856,6 +1896,7 @@ internal sealed partial class LegacyDashboardRenderer _settings.EnableManaTapping = p.EnableManaTapping; _settings.ManaTapMinMana = p.ManaTapMinMana; _settings.ManaStoneKeepCount = p.ManaStoneKeepCount; + if (p.ManaTapMacroOff is bool tapMacroOff) _settings.ManaTapMacroOff = tapMacroOff; // an engine without the toggle leaves it SaveSettings(); } catch { } @@ -2040,6 +2081,11 @@ internal sealed partial class LegacyDashboardRenderer _lastSavedJson = string.Empty; } + // The Monsters rules just loaded are this profile's: the Monsters file (and the Monster + // Editor) now hold them, tagged with this profile, so a reload or relog keeps them. + _settings.EnsureDefaultRule(); + SaveMonstersFile(); + ApplyUiStateFromSettings(); // Reload nav route for the new profile @@ -2359,6 +2405,7 @@ internal sealed partial class LegacyDashboardRenderer dst.EnableManaTapping = tmp.EnableManaTapping; dst.ManaTapMinMana = tmp.ManaTapMinMana; dst.ManaStoneKeepCount = tmp.ManaStoneKeepCount; + dst.ManaTapMacroOff = tmp.ManaTapMacroOff; dst.AutoVendorEnabled = tmp.AutoVendorEnabled; dst.AutoVendorEnableBuying = tmp.AutoVendorEnableBuying; dst.AutoVendorEnableSelling = tmp.AutoVendorEnableSelling; diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs index 4e57501..ff365e2 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs @@ -839,6 +839,9 @@ public sealed class LegacyUiSettings public bool EnableManaTapping = true; public int ManaTapMinMana = 2500; public int ManaStoneKeepCount = 5; + /// Mana tap with macro off: refills and drains run with the macro stopped too (on by default; + /// absent from an older profile = on). Off: only while the macro runs. + public bool ManaTapMacroOff = true; // ── AutoVendor (UtilityBelt AutoVendor; /ub autovendor, /ub vendor) ──────── /// Run AutoVendor when a vendor opens (and allow /ub autovendor). UB defaults this on; @@ -1244,6 +1247,8 @@ public sealed class ItemsBridgePayload public bool EnableManaTapping { get; set; } = true; // absent from an old profile = the new default public int ManaTapMinMana { get; set; } public int ManaStoneKeepCount { get; set; } + /// Mana tap with macro off. Absent (an engine without the toggle) = unchanged. + public bool? ManaTapMacroOff { get; set; } public string CurrentTargetName { get; set; } = string.Empty; /// Listed weapons the character no longer carries (not in the pack, not wielded), by /// id: the engine's Items face shows them as missing. Display only, never read back. diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs index c0dd293..bc35676 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryManager.cs @@ -71,6 +71,86 @@ public sealed class InventoryManager _cache = cache; } + // ── The last move or merge, until the server answers it (2026-11-18, R-20261117-230613-88c5) ── + // AC lets the client have one item request out at a time: a pack move fills the client's pending + // inventory request slot, and until the server's answer about that item comes back the client + // refuses every use, move and pickup with "You can only move or use one item at a time" and + // sends nothing (RynthCore ClientActionGates). AutoCram runs on the first tick after a corpse is + // released, and the looter claimed and used the next corpse 1-3 ms after the cram's move, four + // times in 100 s in the report: each open was refused, the looter waited 5 s for an answer that + // could never come, then opened the corpse again. So the next item action (a corpse, door or chest + // use, salvage, a mana stone, a pet) waits for this move's answer: the item seen out of the pack it + // was moved from, or out of the stack it was merged from, or the server refusing it + // (InventoryServerSaveFailed naming it). At most MoveAnswerMaxMs, so a lost answer holds nothing + // for long. + private uint _flightId; + private int _flightFrom; + private int _flightStack; + private bool _flightIsMerge; + private int _flightErrSeq; + private DateTime _flightSentAt = DateTime.MinValue; + private string _flightWhat = ""; + + /// Longest a move counts as unanswered: answers come in 50-300 ms; this only bounds a lost one. + internal const double MoveAnswerMaxMs = 3000; + private const uint EventInventoryServerSaveFailed = 0x00A0; + + private void NoteMoveSent(uint id, int fromContainer, int stackCount, bool merge, string what) + { + _flightId = id; + _flightFrom = fromContainer; + _flightStack = stackCount; + _flightIsMerge = merge; + _flightErrSeq = LastWeenieErrorSeq(); + _flightSentAt = RynthClock.Now; + _flightWhat = what; + } + + private int LastWeenieErrorSeq() + { + try { return _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0; } + catch { return 0; } + } + + /// + /// True while AutoCram's or AutoStack's last move has no answer from the server yet: the client + /// refuses any other item action until it has one. says which move. + /// + public bool MoveUnanswered(out string what) + { + what = ""; + if (_flightId == 0) return false; + double age = (RynthClock.Now - _flightSentAt).TotalMilliseconds; + if (age >= MoveAnswerMaxMs || age < 0 || MoveAnswered()) + { + _flightId = 0; + return false; + } + what = $"the {(_flightIsMerge ? "merge" : "move")} of {_flightWhat} sent {age:0} ms ago has no answer yet"; + return true; + } + + private bool MoveAnswered() + { + int id = unchecked((int)_flightId); + try + { + // The server refused it: InventoryServerSaveFailed names the item (it empties the client's slot too). + if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out uint evt, out uint obj) + && seq != _flightErrSeq && evt == EventInventoryServerSaveFailed && obj == _flightId) + return true; + } + catch { } + // Gone from the client (merged away, destroyed) or out of the pack it was moved from. + int container = _cache.GetContainerId(id); + if (container == 0 || container != _flightFrom) return true; + // A merge that left the source in place: its stack shrank. + if (_flightIsMerge && (_cache[id]?.Values(LongValueKey.StackCount, -999) ?? -999) is int n + && n != -999 && n != _flightStack) + return true; + return false; + } + // Kept as a no-op for call-site compatibility. Scans are now driven by // the backoff timer below — we re-scan every 2 seconds when idle, every // 500 ms after an action, so external "dirty" signals aren't needed. @@ -234,6 +314,7 @@ public sealed class InventoryManager // Enqueue accepted — record as PENDING and confirm on a later snapshot (do // NOT blacklist; success and a deferred-but-pending move look identical here). _cramPending[item.Id] = new Pending { EnqueuedAt = RynthClock.Now, FromContainer = playerId }; + NoteMoveSent(unchecked((uint)item.Id), playerId, amount, merge: false, $"'{item.Name}'"); return true; // one action per tick } @@ -375,6 +456,7 @@ public sealed class InventoryManager EnqueuedAt = RynthClock.Now, FromContainer = playerId, TargetCount = target.Count, SourceCount = source.Count, Group = g.Key, Name = source.Item.Name ?? "", Guessed = guessed, }; + NoteMoveSent(unchecked((uint)source.Item.Id), source.Item.Container, source.Count, merge: true, $"'{source.Item.Name}'"); return true; // one action per tick } diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs index d59acee..b647633 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs @@ -199,7 +199,9 @@ internal sealed class ManaStoneManager // on for any refill, so charged stones and bought Mana Charges were never used with it // off (2026-10-08). if (!_settings.EnableManaTapping && !HasChargedRefillStone()) { Reset(); return; } - if (!_settings.IsMacroRunning) { Reset(); return; } + // Mana tap with macro off (on by default, 2026-11-19): stones refill worn gear and drain + // tap loot while you play by hand too. Off: only while the macro runs, as before. + if (!_settings.IsMacroRunning && !_settings.ManaTapMacroOff) { Reset(); return; } long now = NowMs; diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs index 7368948..1328b6d 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs @@ -3749,6 +3749,7 @@ internal sealed partial class ExpressionEngine ["CorpseApproachRangeMax"] = (() => D(s.CorpseApproachRangeMax), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMax = d; }), ["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; }), + ["ManaTapMacroOff"] = (() => B(s.ManaTapMacroOff), v => s.ManaTapMacroOff = ToDouble(v) != 0), // Items > Mana Stone Tapping > With macro off ["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }), ["BlacklistTimeoutSec"] = (() => I(s.BlacklistTimeoutSec), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && d >= 0) s.BlacklistTimeoutSec = (int)Math.Round(d); }), ["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }), diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs index 8aae30a..7fbce4b 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs @@ -222,6 +222,26 @@ internal sealed partial class MetaManager if (_expressions != null) _expressions.CombatTargetCount = count; } + // Combat's ghosts (GhostTracker: monsters the server no longer has for us), left out of the + // monster-distance conditions like the combat scan leaves them out. + private Func? _isGhostMonster; + public void SetGhostCheck(Func? isGhost) => _isGhostMonster = isGhost; + + /// + /// A monster the monster-distance conditions count: alive or not yet known (no health update), + /// attackable, not a ghost. ACE sends a monster's health only once it is selected, appraised or + /// hit, so most monsters nearby have none; skipping those (2026-04-17 to 11-19) made "no monsters + /// within 30" hold the moment the last monster fought died, with others standing 7 m away + /// (R-20261119-123029-4bd1: a meta's clear-the-site state left and turned combat off). The combat + /// scan and Monster Priority Count have always counted them. + /// + private bool CountsAsLiveMonster(WorldObjectCache cache, WorldObject obj) + { + if (cache.GetHealthRatio(obj.Id) == 0f) return false; // dead, pending reclassification + if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(unchecked((uint)obj.Id))) return false; + return _isGhostMonster?.Invoke(obj.Id) != true; + } + // The last chest looted to the end, for ralastchestlooted[]. private Func? _lastChestLooted; public void SetLastChestLooted(Func? lastChest) @@ -761,9 +781,7 @@ internal sealed partial class MetaManager { if (obj.Id == pid) continue; if (obj.ObjectClass != AcObjectClass.Monster) continue; - float hp = _objectCache.GetHealthRatio(obj.Id); - if (hp == 0f || hp < 0f) continue; - if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(unchecked((uint)obj.Id))) continue; + if (!CountsAsLiveMonster(_objectCache, obj)) continue; if (_objectCache.Distance(obj.Id, pid) <= maxDist && rx.IsMatch(obj.Name)) matchCount++; } @@ -783,10 +801,7 @@ internal sealed partial class MetaManager { if (obj.Id == pid) continue; // never count self if (obj.ObjectClass != AcObjectClass.Monster) continue; - float hp = _objectCache.GetHealthRatio(obj.Id); - if (hp == 0f) continue; // dead, pending reclassification - if (hp < 0f) continue; // never received a health update — stale/untracked - if (_host.HasObjectIsAttackable && !_host.ObjectIsAttackable(unchecked((uint)obj.Id))) continue; + if (!CountsAsLiveMonster(_objectCache, obj)) continue; if (_objectCache.Distance(obj.Id, pid) <= maxD) return false; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs index 0a31e56..4a89b6a 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/Raycasting/GeometryLoader.cs @@ -1277,6 +1277,21 @@ namespace RynthCore.Plugin.RynthAi.Raycasting if (setup.PartIds != null && setup.PartIds.Length > 0) { var gfxVol = GetGfxObjBounds(setup.PartIds[0]); + // A big object's first-part sphere is its render bound, not a wall (R-20261119-114214-b9ed, + // landblock 0xB64A): wall panel 0x02001C33 is 24 x 0.4 m but its part sphere 28 m round, + // and 0x02001C39 (29 parts, not one with physics polygons) got a 13 m sphere. They stand + // every 24 m along the landblock edge, so the spheres filled the corner: a line between a + // character and a monster 1.5 m off crossed a sphere's surface and read as blocked, and + // the selected monster was locked and dropped every 2 s without a cast (and a line through + // a panel, both ends inside a sphere, read as clear). Its parts' physics polygons are what + // AC collides with; with none at all nothing stops a spell there. + // Tools/RynthCore.LosProof checks this spot. + if (gfxVol != null && gfxVol.Type == BoundingVolume.VolumeType.Sphere && gfxVol.Dimensions.X > LargePartSphereRadius) + { + var mesh = PartsPhysicsMesh(setup, out bool drawingOnly); + if (mesh != null) { result.Add(mesh); return result; } + if (drawingOnly) return result; + } if (gfxVol != null) result.Add(gfxVol); } @@ -1284,6 +1299,70 @@ namespace RynthCore.Plugin.RynthAi.Raycasting return result; } + /// Past this radius a part's sorting sphere is too coarse to stand for the object (meters). + internal const float LargePartSphereRadius = 4.0f; + + /// + /// The physics polygons of every part of , placed by its part frames, as one + /// triangle mesh (null when there are none or a part couldn't be read). : + /// every part was read and none has physics polygons (the GfxObj's HasPhysics flag, 0x01), so nothing + /// in the object collides. + /// + private BoundingVolume PartsPhysicsMesh(SetupInfo setup, out bool drawingOnly) + { + drawingOnly = false; + int count = setup.PartIds.Length; + bool anyPhysics = false, allRead = true; + for (int i = 0; i < count; i++) + { + byte[] head = _portalDat.GetFileData(setup.PartIds[i]); + if (head == null || head.Length < 8) { allRead = false; continue; } + if ((BitConverter.ToUInt32(head, 4) & 0x01) != 0) anyPhysics = true; + } + if (!anyPhysics) + { + drawingOnly = allRead; + return null; + } + if (setup.PartFrames == null || setup.PartFrames.Length < count) return null; + + var triangles = new List(); + for (int i = 0; i < count && triangles.Count / 3 < MAX_BUILDING_TRIANGLES; i++) + { + if (setup.PartFrames[i] == null) return null; + var mesh = LoadGfxObjMesh(setup.PartIds[i]); + if (mesh == null) continue; // a drawing-only part (or unreadable: the rest still stand) + foreach (var face in mesh.Faces) + { + TriangulateAndTransform(face, mesh.Vertices, setup.PartFrames[i], triangles); + if (triangles.Count / 3 >= MAX_BUILDING_TRIANGLES) break; + } + } + if (triangles.Count < 3) return null; + + float minX = float.MaxValue, minY = float.MaxValue, minZ = float.MaxValue; + float maxX = float.MinValue, maxY = float.MinValue, maxZ = float.MinValue; + foreach (var v in triangles) + { + if (v.X < minX) minX = v.X; if (v.X > maxX) maxX = v.X; + if (v.Y < minY) minY = v.Y; if (v.Y > maxY) maxY = v.Y; + if (v.Z < minZ) minZ = v.Z; if (v.Z > maxZ) maxZ = v.Z; + } + return new BoundingVolume + { + Type = BoundingVolume.VolumeType.TriangleMesh, + Center = new Vector3((minX + maxX) * 0.5f, (minY + maxY) * 0.5f, (minZ + maxZ) * 0.5f), + Dimensions = new Vector3(maxX - minX, maxY - minY, maxZ - minZ), + Min = new Vector3(minX, minY, minZ), + Max = new Vector3(maxX, maxY, maxZ), + MeshTriangles = triangles.ToArray(), + IsDoor = false, + // Physics polygons only, so no box stands in for missing walls (and a thin panel turned + // on the landblock would make a big one). + NoAabbFallback = true + }; + } + // ── Triangle mesh loading ─────────────────────────────────────────── /// @@ -1678,7 +1757,8 @@ namespace RynthCore.Plugin.RynthAi.Raycasting Min = worldMin, Max = worldMax, MeshTriangles = tris, - IsDoor = localVol.IsDoor + IsDoor = localVol.IsDoor, + NoAabbFallback = localVol.NoAabbFallback // a parts mesh (PartsPhysicsMesh): its triangles are all of it }; } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs index 9e52bca..404e4be 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ChestLoot.cs @@ -448,6 +448,10 @@ public sealed partial class RynthAiPlugin } if (now < _chestReopenDueAt || _activity != BotActivity.Looting) return true; + // AutoCram's or AutoStack's move has no answer yet: the client would refuse the use (2026-11-18, + // R-20261117-230613-88c5). It takes 50-300 ms; ChestReopenStaleMs still bounds the wait. + if (ItemMoveHold() != null) + return true; if (IsLootingBlockedByPack(settings)) { diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HandCast.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HandCast.cs new file mode 100644 index 0000000..d703138 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.HandCast.cs @@ -0,0 +1,47 @@ +using System; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthAi; + +// ============================================================================ +// The player casting by hand (2026-11-18, R-20261118-214609-a9a8, R-20261118-205826-9c70). +// +// A cast from AC's own spell bar or a spell hotkey prints "Casting " in the chat (type 26, +// AC's own client status lines: "Using the Corpse of ...", "You're too busy!", "In Portal Space - +// Please Wait..."). RynthAi's casts go through the engine (FreeHandsAndCastSpell / CastSpell with +// no UI) and never print it: in both reports and in the local logs, hundreds of RynthAi casts, no +// such line, while the player's clicks each printed one and drew "You're too busy!" 35-50 ms later. +// Each line goes to ActionPacer.NoteHandCast: the player has the character for a moment (see the +// ActionPacer section "The player casting by hand"). +// ============================================================================ + +public sealed partial class RynthAiPlugin +{ + /// AC's chat type for its own client status lines ("Casting ...", "You're too busy!"). + internal const int AcStatusChatType = 26; + + /// + /// True for AC's own "Casting " line (a cast from the spell bar or a hotkey). + /// Not RynthAi's "[RynthAi] Casting: ..." lines, not another plugin's "Casting X..." notice, not speech. + /// + internal static bool TryParseHandCast(string? text, int chatType, out string spell) + { + spell = ""; + if (chatType != AcStatusChatType || string.IsNullOrEmpty(text)) return false; + const string Prefix = "Casting "; + if (!text.StartsWith(Prefix, StringComparison.Ordinal)) return false; + string rest = text.Substring(Prefix.Length).Trim(); + if (rest.Length == 0 || rest.Length > 80) return false; + if (rest.EndsWith("...", StringComparison.Ordinal) || rest.IndexOf(':') >= 0 || rest.IndexOf('"') >= 0) return false; + if (!char.IsLetter(rest[0])) return false; + spell = rest; + return true; + } + + /// A chat line: AC's "Casting ..." marks the player's own cast by hand (ActionPacer.NoteHandCast). + private void NoteHandCastChat(string text, int chatType) + { + if (TryParseHandCast(text, chatType, out string spell)) + ActionPacer.NoteHandCast(Host, spell); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs index 5437ef9..6caf973 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.NearbyChests.cs @@ -177,6 +177,7 @@ public sealed partial class RynthAiPlugin if (_p._targetCorpseId != 0 || _p._openedContainerId != 0) return "the corpse looter is busy"; if (_p.GroundPickupInFlight) return "a ground pickup is in flight"; if (_p._salvageManager?.PanelPending == true) return "the salvage panel is opening"; + if (_p.ItemMoveHold() is string move) return move; // R-20261117-230613-88c5: the client would refuse the use if (!ActionPacer.MayStart(Host, "Loot", HealNeed.None, out string why)) return why.Length > 0 ? why : "the server owes an answer"; long now = CorpseNowMs; diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs index 2fad092..7868437 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs @@ -21,6 +21,19 @@ public sealed partial class RynthAiPlugin private string? SalvagePanelHold() => _salvageManager?.PanelPending == true ? "the salvage panel is opening; the use waits for the salvage to go out" : null; + /// + /// AutoCram's or AutoStack's last move has no answer from the server yet (2026-11-18, + /// R-20261117-230613-88c5). The client holds that move in its one pending item request, and a + /// corpse, chest or door use sent now is refused with "You can only move or use one item at a + /// time" and never sent, so the looter waited 5 s for an answer that could not come. Null when + /// nothing is in flight. + /// + private string? ItemMoveHold() => + _inventoryManager?.MoveUnanswered(out string what) == true ? what : null; + + /// UseAudit.WorldUseHold: what an automatic door or corpse use waits for, or null. + private string? WorldUseHoldReason() => SalvagePanelHold() ?? ItemMoveHold(); + /// UseAudit.AfterSend: a use or use-on went out - record it as the action the server is answering. private static void RecordUseForPacing(RynthCoreHost host, UseAudit.SentUse use) { @@ -63,6 +76,10 @@ public sealed partial class RynthAiPlugin if (ActionPacer.Enabled && (ActionPacer.Current(Host) != null || ActionPacer.GestureHolds(Host, "Items", HealNeed.None, out _))) busy++; // an unanswered server action, or the character still animating (a pack move of a wielded item, a stone, a summon would start on top) + // AutoCram's or AutoStack's move has no answer yet: the client refuses any other item + // action until it has one (2026-11-18, R-20261117-230613-88c5; ItemMoveHold). + if (_inventoryManager?.MoveUnanswered(out _) == true) + busy++; return busy; } } diff --git a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs index e81057b..cc9a6b3 100644 --- a/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.cs @@ -260,7 +260,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase var hookHost = Host; CombatHook.LastUseDone = () => hookHost.HasUseDoneSeq && hookHost.TryGetLastUseDone(out int s, out uint e) ? (s, e) : null; RynthCore.Plugin.Shared.UseAudit.AfterSend = RecordUseForPacing; - RynthCore.Plugin.Shared.UseAudit.WorldUseHold = SalvagePanelHold; + // The salvage panel opening, or AutoCram's/AutoStack's move not answered yet (2026-11-18, + // R-20261117-230613-88c5): either way the client would refuse the use. + RynthCore.Plugin.Shared.UseAudit.WorldUseHold = WorldUseHoldReason; // "The door is locked!" comes as a transient string (ACE Door.ActOnUse): the door logic picks a // lock only when the server says so (DoorInteractionController). The chat line is the fallback. // The four combat events (hits and evades both ways, by name) feed the Monster Stats @@ -855,6 +857,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase _metaManager.SetKillClock(_killClock); _metaManager.SetCorpseOpenedCheck(id => _completedCorpses.ContainsKey(id)); _metaManager.SetCombatTargetCount(() => _combatManager?.LastScanPossible ?? -1); + _metaManager.SetGhostCheck(id => _combatManager?.Ghosts.IsGhost(id) == true); _metaManager.SetLastChestLooted(() => _lastChestLootedId); _metaManager.SetDunExploreStatus(DunExploreStatus, DunExploreInfoJson); if (_dashboard != null) @@ -2529,6 +2532,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase public override void OnChatWindowText(string? text, int chatType, ref int eat) { if (string.IsNullOrEmpty(text)) return; + try { NoteHandCastChat(text, chatType); } catch { } // the player casting by hand (RynthAiPlugin.HandCast.cs), before the refusal handlers try { NoteServerPolicyChat(text); } catch { } // DreamWeave's Thread lines (ServerPolicy) try { NoteDoorServerText(text); } catch { } // "The door is locked!" (the door logic) try { ItemToolChat(text); } catch { } // the key's answers (chest looter) diff --git a/Plugins/Shared/ActionPacer.cs b/Plugins/Shared/ActionPacer.cs index b894edd..a8a20b9 100644 --- a/Plugins/Shared/ActionPacer.cs +++ b/Plugins/Shared/ActionPacer.cs @@ -209,6 +209,10 @@ internal static class ActionPacer _holdsByWho.Clear(); _playerHoldUntil = _playerHoldSince = _playerHolds = _playerHeldStarts = 0; _playerHoldLogged.Clear(); + _handCastAt = _handCastSince = 0; _handRunCasts = _handRunRefusals = 0; + _handCasts = _handRuns = _handRefusals = _handHeldStarts = 0; + _handSpell = ""; + _handLogged.Clear(); _lastTimeout = ""; ClearBusyLocked(); _stuckBreaks = 0; @@ -432,6 +436,127 @@ internal static class ActionPacer Log(host, $"[Pace] the player's turn is over after {held} ms; RynthAi goes on"); } + // ── The player casting by hand (2026-11-18) ───────────────────────────── + // R-20261118-214609-a9a8 and R-20261118-205826-9c70 (DreamWeave, 2026.11.15.3), "spells are not + // connecting anymore", the player "casting arc VII": a 'too busy' UseDone about every 0.4 s with + // nothing sent by RynthAi (no [CombatCast], no pending buff, the pacer only waiting). The sender + // was the player, casting from AC's own spell bar or hotkeys while the macro ran: AC prints + // "Casting " (chat type 26) for each of those (15:52:54.643 'Casting Incantation of Force + // Arc', then 'Casting Incantation of Force Streak' x3, each answered 'You're too busy!' 35-50 ms + // later), and the heartbeat's input clock read idle=0 exactly while the refusals ran. RynthAi's + // own casts never print that line. ACE refuses every cast while the character's last one is + // still running (VerifyBusy), so each click during a cast came back 0x1D. + // RynthAi took those refusals as its own: the buff step escalated its backoff to 8 s and, at + // the 4th, sent StopCompletely "to clear a stuck gesture" in the middle of a running cast (the + // player's at 16:45:18.6, its own Force Arc at 15:52:58.2), which can drop that cast; and its + // buff pass kept the server busy so the player's clicks were refused. + // Now each such line gives the player the character for HandCastHoldMs from it: RynthAi starts + // no cast, use, stance change or movement (an emergency heal still may), the 'too busy' answers + // in that time are the player's (no breaker evidence, no backoff, no stop), logged at the start + // and the end of the run. + + /// How long after the player's last cast by hand (AC's "Casting ..." line) RynthAi leaves the character to the player. + public const long HandCastHoldMs = 3000; + private static long _handCastAt; // the last "Casting ..." line (0 = none yet) + private static long _handCastSince; // the first one of this run + private static int _handRunCasts, _handRunRefusals; + private static long _handCasts, _handRuns, _handRefusals, _handHeldStarts; + private static string _handSpell = ""; + private static readonly HashSet _handLogged = new(); + + /// The player's casts by hand seen (AC's "Casting ..." lines), runs of them, and the 'too busy' answers to them. + public static long HandCasts => _handCasts; + public static long HandCastRuns => _handRuns; + public static long HandCastRefusals => _handRefusals; + + /// + /// AC printed "Casting ": the player cast from the spell bar or a hotkey (RynthAi's + /// casts never print it). Starts or extends the player's hand-cast run (HandCastHoldMs from now). + /// + public static void NoteHandCast(RynthCoreHost host, string spell) + { + if (!Enabled) return; + long now = NowMs(); + string? end = EndHandRunIfOver(now); + bool began; + lock (Gate) + { + began = _handCastAt == 0; + if (began) + { + _handCastSince = now; + _handRunCasts = 0; + _handRunRefusals = 0; + _handRuns++; + _handLogged.Clear(); + } + _handCastAt = now; + _handRunCasts++; + _handCasts++; + _handSpell = spell; + } + if (end != null) Log(host, end); + if (began) + Log(host, $"[Pace] the player is casting by hand: AC's own 'Casting {spell}' (the spell bar or a hotkey, not RynthAi). " + + $"RynthAi starts nothing new (an emergency heal still may) and takes the server's 'too busy' answers as the player's " + + $"until {HandCastHoldMs} ms after the last one"); + } + + /// True within HandCastHoldMs of the player's last cast by hand. + public static bool HandCasting(RynthCoreHost host) + { + if (!Enabled) return false; + string? end = EndHandRunIfOver(NowMs()); + if (end != null) { Log(host, end); return false; } + lock (Gate) return _handCastAt != 0; + } + + /// The run's end line when HandCastHoldMs has passed since its last cast (the run is closed), else null. + private static string? EndHandRunIfOver(long now) + { + lock (Gate) + { + if (_handCastAt == 0 || now - _handCastAt < HandCastHoldMs) return null; + string line = $"[Pace] the player's casting by hand is over ({_handRunCasts} cast(s) in {_handCastAt - _handCastSince} ms, " + + $"last '{_handSpell}', {_handRunRefusals} 'too busy' answer(s) to them): RynthAi goes on"; + _handCastAt = 0; + _handLogged.Clear(); + return line; + } + } + + /// A 'too busy' answer while the player casts by hand: theirs (counted). False when no run is on. + private static bool TakeHandRefusalLocked(long now) + { + if (_handCastAt == 0 || now - _handCastAt >= HandCastHoldMs) return false; + _handRunRefusals++; + _handRefusals++; + return true; + } + + /// True (with why) while the player casts by hand; an emergency heal is not held. One log line per run and subsystem. + private static bool HandCastHolds(RynthCoreHost host, string who, HealNeed heal, out string why) + { + why = ""; + if (!HandCasting(host)) return false; + // The server's answers are still read while the run holds every start (ServerBusyHolds, which + // reads them, is not reached): its 'too busy' answers are counted as the player's here. + ObserveUseDone(host, NowMs(), out string? seen); + if (seen != null) Log(host, seen); + if (heal == HealNeed.Emergency) return false; + string spell; + bool log; + lock (Gate) + { + _handHeldStarts++; + log = _handLogged.Add(who); + spell = _handSpell; + } + why = $"the player is casting by hand ({spell})"; + if (log) Log(host, $"[Pace] {who} waits: {why}"); + return true; + } + /// True (with why) while another plugin has the player's turn. One log line per hold and subsystem. private static bool PlayerHoldsStart(RynthCoreHost host, string who, out string why) { @@ -478,6 +603,7 @@ internal static class ActionPacer { if (!Enabled) { why = ""; return true; } if (PlayerHoldsStart(host, who, out why)) return false; + if (HandCastHolds(host, who, heal, out why)) return false; // the player casting by hand (2026-11-18) // A buff, heal, kit or potion in the air is refused by ACE: wait for the landing. Combat checks // it itself, at the attack, so a stance change is not held; loot and doors never. if (who == "Buff" && LootJumpAirborne(host, out why)) return false; @@ -604,6 +730,7 @@ internal static class ActionPacer why = ""; if (!Enabled) return false; if (PlayerHoldsStart(host, who, out why)) return true; // the item managers' moves wait too + if (HandCastHolds(host, who, heal, out why)) return true; // and while the player casts by hand bool busy; try { busy = host.HasGetCastBusyState && host.GetCastBusyState() != 0; } catch { busy = false; } long now = NowMs(); @@ -897,7 +1024,10 @@ internal static class ActionPacer if (err == TooBusyErr) { if (_busySince == 0) { _busySince = now; if (_hung == null) _busyLogged.Clear(); } - _busyRefusals++; + // The player's click refused while a cast runs (2026-11-18, R-20261118-214609-a9a8): the + // server is busy all the same (the latch), but it says nothing about a cast of ours, so it is + // no evidence for the stuck-cast breaker. + if (!TakeHandRefusalLocked(now)) _busyRefusals++; return; } if (_busySince != 0 || _hung != null || _stage != BreakStage.None) @@ -1377,6 +1507,7 @@ internal static class ActionPacer lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}"); lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}"); lines.Add($" The player's turn (key presses from other plugins): {_playerHolds}, starts held for them {_playerHeldStarts}"); + lines.Add($" The player casting by hand (AC's 'Casting ...'): {_handCasts} cast(s) in {_handRuns} run(s), {_handRefusals} 'too busy' answer(s) to them, starts held {_handHeldStarts}"); lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}"); lines.Add($" Held while the character was animating {_gestureHolds}, animation time limits {_gestureLimits}"); lines.Add($" Held after a 'too busy' answer {_refusalHolds}, held casts turned to {_heldTurns}, stuck casts broken {_stuckBreaks} ({_forcedBreaks} by the HP failsafe; limit {StuckCastMs} ms)"); @@ -1457,6 +1588,8 @@ internal static class ActionPacer return false; } if (PlayerHoldsStart(host, "mode:" + who, out _)) return false; + // A stance change fails a cast in progress on ACE: never under the player's own cast (2026-11-18). + if (HandCastHolds(host, "mode:" + who, HealNeed.None, out _)) return false; PacedAction? a = Current(host); if (a != null) { diff --git a/Plugins/Shared/MoveAudit.cs b/Plugins/Shared/MoveAudit.cs index 02e2925..4ff3c22 100644 --- a/Plugins/Shared/MoveAudit.cs +++ b/Plugins/Shared/MoveAudit.cs @@ -126,6 +126,8 @@ internal static class MoveAudit private static readonly System.Collections.Generic.HashSet _motionsOn = new(); private static readonly System.Collections.Generic.HashSet _actionHoldLogged = new(); private static long _actionHoldLoggedFor = long.MinValue; + private static readonly System.Collections.Generic.HashSet _handHoldLogged = new(); + private static long _handHoldLoggedRun = -1; /// Callers whose movement is never held: the cast nudge, a macro stop, typed commands. internal static bool IsExemptFromActionHold(string who) => @@ -151,6 +153,23 @@ internal static class MoveAudit lock (Gate) moving = motion != 0 ? _motionsOn.Contains(motion) : (_autoRunOn || _motionsOn.Count > 0); if (moving) return false; // a real stop always goes through, however old the start } + // The player casting by hand (2026-11-18, R-20261118-214609-a9a8): a start or a turn of ours would + // move the character in the player's cast windup. Stops are left to the rules below. + if (!isStop && ActionPacer.HandCasting(host)) + { + bool logHand; + lock (Gate) + { + if (_handHoldLoggedRun != ActionPacer.HandCastRuns) { _handHoldLoggedRun = ActionPacer.HandCastRuns; _handHoldLogged.Clear(); } + logHand = Enabled && _handHoldLogged.Add(who); + } + if (logHand) + { + try { host.Log($"[Move] {PluginName}/{who} {call} held (move/turn): the player is casting by hand"); } + catch { } + } + return true; + } var pending = ActionPacer.Current(host); if (pending == null) return false; if (!ActionPacer.HoldsMovement(host, out string what)) return false; diff --git a/Tools/RynthCore.LosProof/Program.cs b/Tools/RynthCore.LosProof/Program.cs index d36452d..3ce198a 100644 --- a/Tools/RynthCore.LosProof/Program.cs +++ b/Tools/RynthCore.LosProof/Program.cs @@ -83,6 +83,7 @@ internal static class Program MagicArcShortPairs(pairs); MagicArcLongLines(polys); MagicArcOutdoors(); + OutdoorWallPieces(); var ex = pairs.Where(p => p.Kind == 'W' && cells.TryGetValue(p.Cell, out var ca) && ca.Struct != 0) .OrderBy(p => (p.B - p.A).Length()).FirstOrDefault(); @@ -244,6 +245,42 @@ internal static class Program Expect(arcOnly * 100 <= Math.Max(1, tested) * 5, "outdoors an arc is clear wherever the line is (at most 5% clip a tree or roof)"); } + /// + /// R-20261119-114214-b9ed (2026-11-19): in landblock 0xB64A, wall panel 0x02001C33 (24 x 0.4 m) and the + /// drawing-only 0x02001C39 stand every 24 m along the landblock edge. They have no collision spheres or + /// cylinders, so each got its first part's render sphere (28 m and 13 m round), which filled the corner + /// cell: a monster 1.5 m away kept dropping out of sight. Now the parts' physics polygons stand for them + /// (GeometryLoader.PartsPhysicsMesh): the corner is open, and the panels block (with both ends inside + /// the old sphere, a line through a panel crossed no sphere surface and read as clear). + /// + private static void OutdoorWallPieces() + { + const uint lb = 0xB64A; + uint cell = (lb << 16) | 0x0040; + float bx = (lb >> 8) * 192f, by = (lb & 0xFF) * 192f; + Console.WriteLine($"\n=== Outdoor wall pieces, landblock 0x{lb:X4} cell 0x0040 ==="); + var geometry = _geo.GetLandblockGeometry(cell); + int bigSpheres = geometry.Count(v => v.Type == BoundingVolume.VolumeType.Sphere && v.Dimensions.X > 8f + && v.Max.X >= bx + 166 && v.Min.X <= bx + 194 && v.Max.Y >= by + 166 && v.Min.Y <= by + 194); + Vector3 At(float x, float y) => new Vector3(bx + x, by + y, _geo.GetTerrainZWorld(bx + x, by + y)); + var rnd = new Random(1); + int n = 0, blocked = 0; + for (int i = 0; i < 4000; i++) + { + float x = 168 + (float)rnd.NextDouble() * 22, y = 168 + (float)rnd.NextDouble() * 22; + double a = rnd.NextDouble() * Math.PI * 2; + n++; + if (_fsm.IsPathBlocked(cell, At(x, y), At(x + (float)(1.5 * Math.Cos(a)), y + (float)(1.5 * Math.Sin(a))), TargetingFSM.AttackType.Linear, out _)) + blocked++; + } + Console.WriteLine($" spheres over 8 m reaching the corner: {bigSpheres}; 1.5 m lines in the corner blocked: {blocked} of {n}"); + Expect(bigSpheres == 0, "no render sphere stands in for the wall pieces"); + Expect(blocked * 100 <= n * 2, "a monster 1.5 m away in the corner is in sight (at most 2% blocked; it was 4.3%)"); + bool wallsBlock = new[] { ((188f, 180f), (196f, 180f)), ((188f, 160f), (196f, 160f)), ((180f, 188f), (180f, 196f)) } + .All(l => _fsm.IsPathBlocked(cell, At(l.Item1.Item1, l.Item1.Item2), At(l.Item2.Item1, l.Item2.Item2), TargetingFSM.AttackType.Linear, out _)); + Expect(wallsBlock, "a line through a wall panel on the landblock edge is blocked"); + } + private static bool TerrainBetween(Vector3 a, Vector3 b) { for (int i = 1; i < 40; i++) diff --git a/Tools/RynthCore.LosProof/RynthLogStub.cs b/Tools/RynthCore.LosProof/RynthLogStub.cs new file mode 100644 index 0000000..04dd59b --- /dev/null +++ b/Tools/RynthCore.LosProof/RynthLogStub.cs @@ -0,0 +1,10 @@ +// The raycasting sources linked in from RynthAi log through RynthLog, which needs the plugin's install +// paths and host; this tool has neither, so its trace calls go nowhere. +namespace RynthCore.Plugin.RynthAi +{ + internal enum LogCat { Raycast } + internal static class RynthLog + { + public static void Trace(LogCat cat, string message) { } + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Program.cs b/Tools/RynthCore.RynthAiHostTests/Program.cs index 7a7f20d..e91ea80 100644 --- a/Tools/RynthCore.RynthAiHostTests/Program.cs +++ b/Tools/RynthCore.RynthAiHostTests/Program.cs @@ -129,6 +129,7 @@ internal static class Program UseRefusalTests.Register(runner); CorpseKillerTests.Register(runner); VitalsTests.Register(runner); + HandCastTests.Register(runner); MultiTargetTests.Register(runner); CastSafetyTests.Register(runner); HealLatencyTests.Register(runner); @@ -220,6 +221,7 @@ internal static class Program BlankLoadTests.Register(runner); CallStateRepairTests.Register(runner); ProfileButtonTests.Register(runner); + MonsterProfileTests.Register(runner); GiveProfileTests.Register(runner); TinkerTests.Register(runner); LauncherSwapTests.Register(runner); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs index 9489e61..b68c6d3 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/BuffTests.cs @@ -1759,7 +1759,8 @@ internal static class BuffTests var list = rig.B.BuildDynamicBuffList(); Check.Eq(string.Join(", ", list.Take(4)), string.Join(", ", Head), "Creature Enchantment, Focus, Willpower, Life Magic first"); int strength = list.IndexOf("Strength Self"), heavy = list.IndexOf("Heavy Weapon Mastery"), armor = list.IndexOf("Armor Self"); - Check.True(strength == 4, $"everything else follows, Strength next (at {strength})"); + Check.Eq(list.IndexOf("Mana Conversion Mastery"), 4, "Mana Conversion Mastery right after the head (R-20261119-195743-1993)"); + Check.True(strength == 5, $"everything else follows, Strength next (at {strength})"); Check.True(strength < heavy && heavy < armor, "and keeps its old order (attributes, masteries, prots)"); Check.True(list.IndexOf("Blood Drinker Self") > armor, "weapon auras stay after the prots"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs index 500f704..42f1102 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/CombatHookTests.cs @@ -54,6 +54,7 @@ internal static class CombatHookTests r.Add("combat hook: a script heal (a drain) at a fight target whose rule turned to Priority 0 is rejected", HookHealRejectsIgnoredTarget); r.Add("blacklist: casts answered 'too busy' (UseDone 0x1D) are not no-damage casts (answered 0: the target is dropped)", RefusedCastsNotJudged); r.Add("ghost (R-20261115-172110-9e6a): two casts answered 'target not acquired' (UseDone 0x42C) mark the target a ghost and stop the casting", NotAcquiredMarksGhost); + r.Add("out of range (R-20261119-155301-121a): a cast answered 'Out of Range!' (UseDone 0x550) drops the target until it comes 3 m nearer", OutOfRangeDropsTarget); r.Add("blacklist (2026-11-15): melee landing nothing across a building's wall (one inside, one out) keeps the target off 5 min; elsewhere the usual timeout", AcrossWallBlacklistLonger); r.Add("loot jump: Think sends no cast while in the air after a loot jump; it casts on the landing, or at the cap", LootJumpHoldsAttack); r.Add("loot jump: a swing refused in the air (WeenieError 0x4EB) is not a no-damage attack (without it: a miss)", MeleeInAirNotJudged); @@ -1087,6 +1088,46 @@ internal static class CombatHookTests // 2026-11-15, R-20261115-172110-9e6a: every Blade Arc at a target the server didn't have came back // UseDone 0x42C about 70 ms after the send, and combat cast again at once (13 casts in 0.85 s, the // hourglass going round), never dropping it. + // 2026.11.15.3: an Olthoi Hive Warrior 88 m off, every Incantation of Force Arc at it answered UseDone + // 0x550 about 60 ms after the send, and combat cast again at once (1,027 casts since the last kill). + private static void OutOfRangeDropsTarget() => Guard(() => + { + var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; }); + rig.S.EnableRaycasting = false; + rig.Attack(); + Check.Eq(FakeHost.Casts.Count, 1, "the first cast goes out"); + FakeHost.UseDone(CombatManager.MissileOutOfRangeErr); + rig.Attack(); + Check.Eq(FakeHost.Casts.Count, 1, "the server said 'Out of Range!': no second cast at it"); + Check.Eq(rig.C.activeTargetId, 0, "the target is dropped"); + Check.True(FakeHost.Logs.Any(l => l.Contains("out of range at 10 m") && l.Contains("UseDone 0x550")), + "logged with the distance and the answer: " + FakeHost.Logs.LastOrDefault(l => l.Contains("out of range"))); + Check.Eq(FakeHost.Chat.Count(l => l.Contains("is out of range at 10 yd")), 1, "said once in chat"); + + SetField(rig.C, "_lastScanTime", DateTime.MinValue); // the scan's own throttle + rig.C.ScanNearbyTargets(); + Check.False(rig.C.ScannedTargets.Any(t => t.Id == Target), "the scan leaves it out"); + Check.True(rig.C.ScannedTargets.Any(t => t.Id == Other), "the other monster is still a target"); + + FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 8f, 0f); // 2 m nearer: not enough + SetField(rig.C, "_lastScanTime", DateTime.MinValue); + rig.C.ScanNearbyTargets(); + Check.False(rig.C.ScannedTargets.Any(t => t.Id == Target), "2 m nearer: still left out"); + + FakeHost.Positions[(uint)Target] = (0x0101001Bu, 0f, 6f, 0f); // 4 m nearer + SetField(rig.C, "_lastScanTime", DateTime.MinValue); + rig.C.ScanNearbyTargets(); + Check.True(rig.C.ScannedTargets.Any(t => t.Id == Target), "4 m nearer: a target again"); + + // Control: any other answer leaves the target alone. + var ok = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; }); + ok.S.EnableRaycasting = false; + ok.Attack(); + FakeHost.UseDone(0); + ok.Attack(); + Check.Eq(ok.C.activeTargetId, Target, "answered 0: still the target"); + }); + private static void NotAcquiredMarksGhost() => Guard(() => { var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; }); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/HandCastTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/HandCastTests.cs new file mode 100644 index 0000000..60adf0a --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/HandCastTests.cs @@ -0,0 +1,183 @@ +using System; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.PluginSdk; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// The player casting by hand while the macro runs (2026-11-18, R-20261118-214609-a9a8 and +// R-20261118-205826-9c70, DreamWeave, 2026.11.15.3): "spells are not connecting anymore". A 'too busy' +// UseDone about every 0.4 s with nothing sent by RynthAi; the sender was the player's own spell bar +// (AC prints "Casting " for each click, type 26; RynthAi's casts never do). RynthAi took each +// refusal as its own: an 8 s backoff, and at the 4th a StopCompletely into the cast that was running. +// Replayed here: the player's clicks, each refused, never stop the character, never back RynthAi off, +// never count as stuck-cast evidence; RynthAi starts nothing while the player casts (an emergency heal +// still may); and with no hand cast the old streak rules still hold. +internal static class HandCastTests +{ + private const uint Player = 0x50000B01; + private const uint STypeLife = 33; + private const uint TooBusy = 0x1D; + private const string Spell = "Incantation of Force Streak"; + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static; + + public static void Register(Runner r) + { + r.Add("hand cast: AC's own 'Casting ' (type 26) is the player's cast; RynthAi's and other lines are not", ParsesOnlyAcLine); + r.Add("hand cast (R-20261118-214609-a9a8): the player's refused clicks send no StopCompletely, no backoff, no streak", RefusalsAreNotOurs); + r.Add("hand cast: while the player casts RynthAi starts nothing (an emergency heal may), no move starts; it ends 3 s after the last click, logged", PacerYields); + r.Add("hand cast: with no hand cast, RynthAi's own refusal streak still stops the character once", OwnStreakStillStops); + } + + private static long _t; + + private static void PaceOn() + { + _t = 20_000_000; + ActionPacer.Reset(); + ActionPacer.Enabled = true; + ActionPacer.NowMs = () => _t; + MoveAudit.Reset(); + MoveAudit.NowMs = () => _t; + } + + private static void PaceOff() + { + ActionPacer.Enabled = false; + ActionPacer.Reset(); + ActionPacer.NowMs = () => Environment.TickCount64; + MoveAudit.Reset(); + MoveAudit.NowMs = () => Environment.TickCount64; + } + + private static void Paced(Action body) + { + PaceOn(); + try { body(); } + finally { PaceOff(); } + } + + private static (RynthCoreHost host, BuffManager b) Caster() + { + FakeHost.Reset(); + FakeHost.WeaponCalls = true; + FakeHost.StopCalls = true; + FakeHost.ServerGates = true; + FakeHost.CombatModeCalls = true; + FakeHost.LastUseDoneCalls = true; + FakeHost.CombatModeValue = CombatMode.Magic; + foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id); + FakeHost.Skills[(Player, STypeLife)] = (400, 2); + var host = FakeHost.Create(Player); + var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0, + GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false }; + var skills = new CharacterSkills(host); + skills.SetPlayerId(Player); + var sm = new SpellManager(host, s); + sm.InitializeNatively(); + sm.SetCharacterSkills(skills); + var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 }; + var b = new BuffManager(host, s, sm, vitals); + b.SetCharacterSkills(skills); + return (host, b); + } + + private static int Streak(BuffManager b) => (int)typeof(BuffManager).GetField("_busyRefusalStreak", Any)!.GetValue(b)!; + private static DateTime BackoffUntil(BuffManager b) => (DateTime)typeof(BuffManager).GetField("_busyBackoffUntil", Any)!.GetValue(b)!; + + /// One click of the player's, as the client sees it: AC's line, the server's 0x1D, AC's refusal line. + private static void RefusedClick(RynthCoreHost host, BuffManager b) + { + Check.True(RynthAiPlugin.TryParseHandCast("Casting " + Spell, RynthAiPlugin.AcStatusChatType, out string spell), "AC's line parses"); + ActionPacer.NoteHandCast(host, spell); + FakeHost.UseDone(TooBusy); + ActionPacer.MayStart(host, "Buff", HealNeed.None, out _); // RynthAi's tick reads the answer + b.OnChatWindowText("You're too busy!", RynthAiPlugin.AcStatusChatType); + } + + private static void ParsesOnlyAcLine() + { + Check.True(RynthAiPlugin.TryParseHandCast("Casting Incantation of Force Arc", 26, out string s1), "the report's line"); + Check.Eq(s1, "Incantation of Force Arc", "its spell"); + Check.True(RynthAiPlugin.TryParseHandCast("Casting Blade Arc VII", 26, out string s2) && s2 == "Blade Arc VII", "a level VII spell"); + Check.False(RynthAiPlugin.TryParseHandCast("[RynthAi] Casting: Incantation of Focus Self", 5, out _), "RynthAi's own line"); + Check.False(RynthAiPlugin.TryParseHandCast("Casting Incantation of Force Arc", 5, out _), "not AC's status type"); + Check.False(RynthAiPlugin.TryParseHandCast("Casting Incantation of Focus Self...", 26, out _), "another plugin's notice"); + Check.False(RynthAiPlugin.TryParseHandCast("Bob tells you, \"Casting Blade Arc VII\"", 26, out _), "speech"); + Check.False(RynthAiPlugin.TryParseHandCast("Using the Corpse of Olthoi Warrior", 26, out _), "a use line"); + Check.False(RynthAiPlugin.TryParseHandCast("Casting ", 26, out _), "nothing after it"); + } + + // 16:45:16.9-16:45:30.7: 24 refusals of the player's clicks; at the 4th RynthAi sent StopCompletely + // ("the cast gesture looks stuck") into a running cast, and backed its buffs off 8 s. + private static void RefusalsAreNotOurs() => Paced(() => + { + var (host, b) = Caster(); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "RynthAi's tick before the clicks (the answers' baseline)"); + for (int i = 0; i < 8; i++) + { + RefusedClick(host, b); + _t += 400; + } + Check.Eq(FakeHost.Stops, 0, "eight refused clicks of the player's: no StopCompletely into the running cast"); + Check.Eq(Streak(b), 0, "no 'too busy' streak of RynthAi's"); + Check.True(BackoffUntil(b) == DateTime.MinValue, "no backoff for RynthAi's own casts"); + Check.Eq(ActionPacer.HandCastRefusals, 8L, "the eight refusals counted as the player's"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("answers the player's own cast by hand")), 1, "said once for the run"); + Check.False(FakeHost.Logs.Any(l => l.Contains("too-busy streak=")), "no streak lines"); + }); + + private static void PacerYields() => Paced(() => + { + var (host, _) = Caster(); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "free before the player casts"); + ActionPacer.NoteHandCast(host, Spell); + Check.True(FakeHost.Logs.Any(l => l.Contains("the player is casting by hand: AC's own 'Casting " + Spell + "'")), "the run's start logged"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string why), "a buff waits"); + Check.True(why.Contains("casting by hand"), "and says why: " + why); + Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "combat waits"); + Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a plain heal waits"); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal still goes"); + Check.True(ActionPacer.GestureHolds(host, "Items", HealNeed.None, out _), "the item managers' moves wait"); + FakeHost.CombatModeRequests.Clear(); + Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle peace"), "no stance change into the player's cast"); + Check.Eq(FakeHost.CombatModeRequests.Count, 0, "and none sent"); + Check.True(MoveAudit.HeldForAction(host, "Nav", "SetAutoRun(True)", isStop: false), "a nav start is held"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Pace] Buff waits: the player is casting by hand")), 1, "the buff's wait logged once"); + + // A click every 0.4 s keeps the run going; the 0x1D answers are the player's, not breaker evidence. + for (int i = 0; i < 5; i++) + { + _t += 400; + ActionPacer.NoteHandCast(host, Spell); + FakeHost.UseDone(TooBusy); + ActionPacer.MayStart(host, "Buff", HealNeed.None, out _); + } + Check.Eq(ActionPacer.HandCastRuns, 1L, "one run"); + Check.Eq(ActionPacer.HandCasts, 6L, "six casts in it"); + Check.Eq(ActionPacer.HandCastRefusals, 5L, "its five refusals counted as the player's"); + + // 3 s after the last click the player is done; the server's next 'done' clears the latch. + _t += ActionPacer.HandCastHoldMs - 1; + Check.True(ActionPacer.HandCasting(host), "just under 3 s after the last click: still the player's"); + _t += 2; + FakeHost.UseDone(0); + Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out string after), "3 s after the last click RynthAi goes on: " + after); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("the player's casting by hand is over (6 cast(s)")), 1, "the run's end logged once"); + Check.False(MoveAudit.HeldForAction(host, "Nav", "SetAutoRun(True)", isStop: false), "nav may start again"); + }); + + // TooBusyVitals' rule kept: a refusal streak with no hand cast is RynthAi's, and stops once. + private static void OwnStreakStillStops() => Paced(() => + { + var (_, b) = Caster(); + for (int i = 0; i < 4; i++) { FakeHost.UseDone(TooBusy); b.OnChatWindowText("You're too busy!", RynthAiPlugin.AcStatusChatType); } + Check.Eq(FakeHost.Stops, 1, "4 refusals in a row, no hand cast: one StopCompletely"); + Check.Eq(Streak(b), 4, "the streak counts"); + }); +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/KillNoticeTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/KillNoticeTests.cs index fa91cd0..ff9edb9 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/KillNoticeTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/KillNoticeTests.cs @@ -38,6 +38,8 @@ internal static class KillNoticeTests r.Add("kill notice: the fight is over when the last monster dies - looting gets the tick", FightOverLoots); r.Add("targeting: a top-priority monster's tier holds while its death is only a guess", GuessedDeathHoldsTier); r.Add("targeting (melee): after a kill and its echo the same-named top priority is next, not a lesser one", EchoKeepsTopPriorityNext); + r.Add("kill notice (melee, cleave): a same-named neighbour's death keeps the target the server says is alive", CleaveKillKeepsLiveTarget); + r.Add("kill notice (melee): the fight target's own death (the server's 0, or no fresh health) still drops it", MeleeOwnDeathStillDrops); } // ── The rig ────────────────────────────────────────────────────────────── @@ -306,4 +308,95 @@ internal static class KillNoticeTests Check.Eq(rig.C.activeTargetId, Id(twin), "the Priority 5 twin is next (it was 4 s out of the scan before)"); Check.True(rig.Scanned(lesser), "the lesser one was a candidate too"); } + + // ── Melee cleave: the neighbour's notice names the target ──────────────── + // R-20261118-012228-179f (2026-11-18, DreamWeave, melee with a cleaving weapon in a pack of + // same-named Olthoi): "switching targets when it shouldn't be". A swing hits the target and, + // by cleave, a same-named neighbour; in Melee mode both damage lines are the target's, so when + // the neighbour died its notice was matched to the target, which was dropped while alive (the + // server's health for it had just said 0.6), kept off the scan for 4 s, and the bot turned to + // the next one - twice in 4 s in the report. ACE pushes the fight target's health with every + // hit (combat's QueryHealth made it the server's selection), the lethal one too, before the + // notice: a fresh health above 0 says the target didn't die. + + /// The plugin's OnUpdateHealth for a creature: the cache and combat's fight-health clock. + private static void ServerHealth(Rig rig, uint id, float ratio) + { + rig.Cache.OnUpdateHealth(id, ratio); + rig.C.NoteServerHealth(Id(id), ratio); + } + + /// A melee strike on the target with its health from the server (as ACE sends it with the + /// hit) and a cleave hit on a same-named neighbour (a line naming the same name). + private static void StrikeWithCleave(Rig rig, uint target, float healthAfter) + { + ServerHealth(rig, target, healthAfter); + rig.C.OnCombatDamage(40, 1, false, true); + rig.C.HandleChatForDamage("You slash Drumtaken Sentry for 40 points of slashing damage!"); + rig.C.HandleChatForDamage("You slash Drumtaken Sentry for 31 points of slashing damage!"); // the cleave + } + + private static Rig MeleePair(out uint target, out uint twin) + { + var rig = new Rig(CombatMode.Melee); + FakeHost.TargetCalls = true; // QueryHealth counted + target = rig.Mob(Sentry, SentryWcid, 2); + twin = rig.Mob(Sentry, SentryWcid, 3); + rig.Build(target); + rig.Store.SetManualHp(SentryWcid, 200); + return rig; + } + + private static void CleaveKillKeepsLiveTarget() + { + var rig = MeleePair(out uint target, out uint twin); + StrikeWithCleave(rig, target, 0.80f); + rig.Now = rig.Now.AddMilliseconds(1000); + StrikeWithCleave(rig, target, 0.61f); + int queriesBefore = FakeHost.HealthQueries.Count(q => q == target); + + // The next strike's cleave kills the neighbour: no damage line for it, its notice only. + rig.Now = rig.Now.AddMilliseconds(900); + ServerHealth(rig, target, 0.55f); + rig.C.HandleChatForDamage("You slash Drumtaken Sentry for 38 points of slashing damage!"); + rig.C.OnKillNotification("You killed Drumtaken Sentry!"); + + Check.Eq(rig.C.activeTargetId, Id(target), "the target the server says is alive is kept"); + Check.False(rig.Suppressed(target), "and not kept off the scan"); + Check.True(FakeHost.Logs.Any(l => l.Contains("the server says it is alive") && l.Contains("keeping the target")), + "the log says why"); + Check.Eq(FakeHost.HealthQueries.Count(q => q == target), queriesBefore + 1, + "its health is asked again (a target dead some other way answers 0)"); + + rig.Rescan(); + rig.C.HandleCombatTrigger(); + Check.Eq(rig.C.activeTargetId, Id(target), "no switch to another monster"); + Check.False(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock") || l.Contains("[CombatTarget] switch")), + "no new lock"); + } + + private static void MeleeOwnDeathStillDrops() + { + // The lethal hit: the server's 0 comes before the notice. + var rig = MeleePair(out uint target, out uint twin); + StrikeWithCleave(rig, target, 0.30f); + rig.Now = rig.Now.AddMilliseconds(1000); + ServerHealth(rig, target, 0f); + rig.C.OnKillNotification("You killed Drumtaken Sentry!"); + Check.Eq(rig.C.activeTargetId, 0, "health 0: the target died, dropped"); + Check.True(rig.Suppressed(target), "and kept off the scan while its corpse forms"); + Check.True(FakeHost.Logs.Any(l => l.Contains("killed (KillerNotification; server health 0.00")), + "the drop names the server health it went on"); + + // The health stream stopped (the player selected something else): the last health is older + // than the hits since, so it says nothing about the kill and the notice is the target's. + rig = MeleePair(out target, out twin); + StrikeWithCleave(rig, target, 0.30f); + rig.Now = rig.Now.AddMilliseconds(1500); + rig.C.HandleChatForDamage("You slash Drumtaken Sentry for 40 points of slashing damage!"); + rig.Now = rig.Now.AddMilliseconds(1200); + rig.C.OnKillNotification("You killed Drumtaken Sentry!"); + Check.Eq(rig.C.activeTargetId, 0, "stale health: the notice is the target's, dropped"); + Check.False(rig.Suppressed(twin), "the neighbour isn't taken for it"); + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/LootPacingTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/LootPacingTests.cs index fc5871b..4aef3f5 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/LootPacingTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/LootPacingTests.cs @@ -20,6 +20,12 @@ namespace RynthCore.RynthAiHostTests.Tests; // client (the salvage panel open wins), and the corpse loop then waits for an open that never // comes. Corpse opens (and every automatic door/corpse use, via UseAudit.WorldUseHold) wait // while the salvage panel is pending; the corpse claim's timeout is not charged meanwhile. +// I. R-20261117-230613-88c5 (2026-11-18), "after looting a corpse it says you can only move or use +// one item at a time": AutoCram ran on the first tick after a corpse was released, and the +// looter used the next corpse 1-3 ms after the cram's move. The client still held the move in +// its one pending item request, refused the use and sent nothing, and the looter waited 5 s for +// an answer (four times in 100 s). The open now waits for the move's answer (the item out of the +// main pack, or the server refusing it), 3 s at most; so do the other item actions (PacedBusy). internal static class LootPacingTests { private const uint Player = 0x50000E01; @@ -27,6 +33,10 @@ internal static class LootPacingTests private const uint CorpseB = 0x80073023; private const uint Ust = 0x80000E11; private const uint Junk = 0x80000E12; + private const uint Gem = 0x80000E13; + private const uint SidePack = 0x80000E14; + private const uint ItemTypeGem = 0x800; + private const uint ItemsCapacityKey = 6; private const uint UstWcid = 20646; private const uint ItemTypeContainer = 0x200, ItemTypeArmor = 0x2; private const uint LongDescKey = 16; @@ -37,6 +47,8 @@ internal static class LootPacingTests public static void Register(Runner r) { r.Add("salvage/loot: no corpse open (or auto door/corpse use) while the salvage panel is pending; the claim is kept and opened after the execute", CorpseOpenWaitsForSalvagePanel); + r.Add("loot pacing (R-20261117-230613-88c5): no corpse open (or auto door/corpse use, salvage, stone) while AutoCram's move is unanswered; the open goes on the answer", CorpseOpenWaitsForCramMove); + r.Add("loot pacing (R-20261117-230613-88c5): a cram the server refuses frees the open at once; a lost answer holds it 3 s at most", CramMoveHoldBounds); } private static void World() @@ -174,4 +186,132 @@ internal static class LootPacingTests UseAudit.Reset("?", null); } } + + // A gem loose in the main pack and an empty side pack: AutoCram has one move to make. + private static void CramWorld() + { + World(); + FakeHost.WeenieErrorCalls = true; + FakeHost.Names[Gem] = "Black Opal"; + FakeHost.ItemTypes[Gem] = ItemTypeGem; + FakeHost.Containers[Gem] = Player; + FakeHost.Names[SidePack] = "Backpack"; + FakeHost.ItemTypes[SidePack] = ItemTypeContainer; + FakeHost.Ints[(SidePack, ItemsCapacityKey)] = 24; + FakeHost.Containers[SidePack] = Player; + } + + private static InventoryManager CramBot(RynthCoreHost host, Bot bot) + { + _ = bot.Cache[unchecked((int)Gem)]; + _ = bot.Cache[unchecked((int)SidePack)]; + bot.S.EnableAutocram = true; + var inv = new InventoryManager(host, bot.S, bot.Cache); + bot.Set("_inventoryManager", inv); + // As RynthAiPlugin's init wires it. + UseAudit.WorldUseHold = (Func)Delegate.CreateDelegate(typeof(Func), bot.P, + typeof(RynthAiPlugin).GetMethod("WorldUseHoldReason", Any)!); + return inv; + } + + private static int PacedBusy(Bot bot) => (int)typeof(RynthAiPlugin).GetProperty("PacedBusy", Any)!.GetValue(bot.P)!; + + private static void CorpseOpenWaitsForCramMove() + { + CramWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + long now = 60_000_000; + var start = new DateTime(2026, 11, 17, 23, 0, 0); + var savedClock = RynthAiPlugin.CorpseClock; + RynthAiPlugin.CorpseClock = () => now; + RynthClock.TestNow = () => start.AddMilliseconds(now - 60_000_000); + try + { + UseAudit.Reset("RynthAi", () => true); + var inv = CramBot(host, bot); + + // The tick after a corpse is released: no corpse claimed or open, so the cram goes out. + bot.Call("TickCramStack", bot.S); + Check.True(FakeHost.Moves.Any(m => m.Id == Gem && m.Pack == SidePack), "AutoCram moves the gem into the side pack"); + Check.True(inv.MoveUnanswered(out string what), "the move has no answer yet"); + Check.True(what.Contains("Black Opal"), "the hold names the item: " + what); + Check.True(PacedBusy(bot) > 0, "salvage, mana stones, pets and the next cram see it as busy"); + + // The same tick and the next ones: the looter claims the next corpse, but its open waits. + for (int i = 0; i < 5; i++) { bot.Tick(); now += 30; } + Check.Eq(CorpseUses(), 0, "no corpse use while the cram's move is unanswered (the client would refuse it)"); + Check.Eq(bot.Get("_targetCorpseId"), unchecked((int)CorpseA), "the corpse is claimed and kept"); + Check.Eq(FakeHost.Logs.Count(l => l.Contains("waits: the move of 'Black Opal'")), 1, "the wait is logged once"); + Check.False(host.UseFor(CorpseB, "Nav", "test: an automatic world use"), "an automatic door/corpse use is held too"); + Check.Eq(CorpseUses(), 0, "and not sent"); + + // The server answers: the gem is in the side pack. The open goes out on the next tick. + FakeHost.Containers[Gem] = SidePack; + bot.Tick(); + Check.Eq(CorpseUses(), 1, "the corpse is opened once the move is answered"); + Check.True(FakeHost.Uses.Contains(CorpseA), "the claimed corpse"); + Check.False(inv.MoveUnanswered(out _), "nothing in flight"); + Check.Eq(PacedBusy(bot), 0, "and nothing busy"); + } + finally + { + RynthAiPlugin.CorpseClock = savedClock; + RynthClock.TestNow = null; + UseAudit.Reset("?", null); + } + } + + private static void CramMoveHoldBounds() + { + CramWorld(); + var host = FakeHost.Create(Player); + var bot = new Bot(host); + long now = 60_000_000; + var start = new DateTime(2026, 11, 17, 23, 0, 0); + var savedClock = RynthAiPlugin.CorpseClock; + RynthAiPlugin.CorpseClock = () => now; + RynthClock.TestNow = () => start.AddMilliseconds(now - 60_000_000); + try + { + UseAudit.Reset("RynthAi", () => true); + var inv = CramBot(host, bot); + + // Refused: InventoryServerSaveFailed naming the gem (the report's last cram, 18:05:38.869). + bot.Call("TickCramStack", bot.S); + Check.True(inv.MoveUnanswered(out _), "the move is out"); + FakeHost.WeenieError(0, evt: 0x00A0, obj: SidePack); + Check.True(inv.MoveUnanswered(out _), "a refusal naming another object is not this move's answer"); + FakeHost.WeenieError(0, evt: 0x00A0, obj: Gem); + Check.False(inv.MoveUnanswered(out _), "the server refused the move: that is its answer"); + bot.Tick(); + Check.Eq(CorpseUses(), 1, "the open goes out at once"); + + // Lost: no answer at all (a fresh manager, the gem still in the main pack). The hold + // ends after MoveAnswerMaxMs. (The looter lets go of the corpse it opened, so the cram runs.) + bot.Set("_targetCorpseId", 0); + bot.Set("_openedContainerId", 0); + var inv2 = CramBot(host, bot); + bot.Call("TickCramStack", bot.S); + Check.True(inv2.MoveUnanswered(out _), "a second move is out"); + Check.False(host.UseFor(CorpseB, "Nav", "test: an automatic world use"), "an automatic world use is held"); + long sent = now; + bool freed = false; + while (now - sent < 5000) + { + if (host.UseFor(CorpseB, "Nav", "test: an automatic world use")) { freed = true; break; } + now += 100; + } + long held = now - sent; + Check.True(freed, "the use goes out in the end"); + Check.True(held >= (long)InventoryManager.MoveAnswerMaxMs, $"held until the answer limit ({held} ms)"); + Check.True(held <= (long)InventoryManager.MoveAnswerMaxMs + 100, $"and no longer ({held} ms)"); + } + finally + { + RynthAiPlugin.CorpseClock = savedClock; + RynthClock.TestNow = null; + UseAudit.Reset("?", null); + } + } } diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs index b57691f..e5d593a 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/ManaStoneChoiceTests.cs @@ -42,6 +42,39 @@ internal static class ManaStoneChoiceTests r.Add("mana stones: in a fight, worn gear that runs low is still refilled (armor without mana drops its spells)", RefillInFight); r.Add("eternal charge: tapping is ignored while it is in the pack, and applies again when it leaves", EternalIgnoresTapping); r.Add("eternal charge: a use with no answer is tried again in 20 s, not 5 minutes", EternalRetriesSoon); + r.Add("mana tap with macro off (on by default): the macro stopped, stones still refill gear and drain tap loot", TapWithMacroOff); + r.Add("mana tap with macro off, unticked: nothing while the macro is stopped; it starts with the macro", NoTapWithMacroOffUnticked); + } + + // 2026-11-19: mana tapping ran only while the macro ran. "Mana tap with macro off" (on by default) lets it + // work while you play by hand too; mana tapping itself is on by default for a new character. + private static void TapWithMacroOff() + { + var fresh = new LegacyUiSettings(); + Check.True(fresh.ManaTapMacroOff, "Mana tap with macro off is on by default"); + Check.True(fresh.EnableManaTapping, "and so is mana tapping"); + + using var refill = new Rig(tapping: true, new (uint, int?)[] { (StoneA, 3000) }); // the mace reads 0 of 5000 + refill.S.IsMacroRunning = false; + refill.Run(1000); + Check.Eq(refill.OnPlayer.Count, 1, "macro off: the charged stone refills the worn mace"); + + using var drain = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null) }, ringToDrain: true, maceMana: 5000); + drain.S.IsMacroRunning = false; + drain.Run(1000); + Check.Eq(drain.OnRing.Count, 1, "macro off: the ring looted for tapping is drained into the empty stone"); + } + + private static void NoTapWithMacroOffUnticked() + { + using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, 3000) }); + rig.S.ManaTapMacroOff = false; + rig.S.IsMacroRunning = false; + rig.Run(3000); + Check.Eq(rig.OnPlayer.Count, 0, "unticked, macro off: no stone used"); + rig.S.IsMacroRunning = true; + rig.Run(1000); + Check.Eq(rig.OnPlayer.Count, 1, "the macro starts: the stone goes on the player"); } private const uint ChargeA = 0x80400031, ChargeB = 0x80400032, ChargeC = 0x80400033; diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs index bf18530..6a9f335 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MetaTests.cs @@ -675,7 +675,8 @@ internal static class MetaTests } FakeHost.NotAttackable.Add(crier); var host = FakeHost.Create(); - // The lurker never got a health update (untracked); the dead one reads 0. + // The lurker never got a health update (untracked: ACE sends health only once a monster is selected, + // appraised or hit, so most monsters nearby have none); the dead one reads 0. var cache = FakeHost.MakeCache(host, Player, new[] { drudge, farDrudge, crier, dead, lurker }, new Dictionary { [drudge] = 1f, [farDrudge] = 0.5f, [crier] = 1f, [dead] = 0f }); var rig = new Rig(host, Player); @@ -684,23 +685,30 @@ internal static class MetaTests rig.S.MonsterRules.Add(new MonsterRule { Name = "^Drudge" }); Check.True(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,20,1"), "one drudge within 20"); - Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,20,2"), "dead and untracked ones do not count"); - Check.True(rig.Holds(C.MonsterNameCountWithinDistance, "drudge,100,2"), "two within 100 (ignores case, inclusive)"); - Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,99.9,2"), "the far one is at 100"); + Check.True(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,20,2"), "the untracked lurker counts (R-20261119-123029-4bd1)"); + Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,20,3"), "the dead one does not"); + Check.True(rig.Holds(C.MonsterNameCountWithinDistance, "drudge,100,3"), "three within 100 (ignores case, inclusive)"); + Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,99.9,3"), "the far one is at 100"); Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "Crier,20,1"), "not attackable"); Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,x,1"), "bad distance"); Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,20"), "missing count"); Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "(,20,1"), "bad regex"); Check.True(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,20,0"), "at least 0 always holds"); - Check.True(rig.Holds(C.NoMonstersWithinDistance, "9"), "none within 9 (crier, dead, untracked skipped)"); + Check.True(rig.Holds(C.NoMonstersWithinDistance, "4"), "none within 4 (the crier at 1 is not attackable)"); + Check.False(rig.Holds(C.NoMonstersWithinDistance, "5"), "the untracked lurker at 5 is a monster (the dead one there is not)"); Check.False(rig.Holds(C.NoMonstersWithinDistance, "10"), "the drudge at 10"); + // A ghost (combat's GhostTracker: the server no longer has it) is left out, like the combat scan leaves it. + rig.M.SetGhostCheck(id => id == unchecked((int)lurker)); + Check.True(rig.Holds(C.NoMonstersWithinDistance, "9"), "the lurker is a ghost: none within 9"); + Check.False(rig.Holds(C.MonsterNameCountWithinDistance, "Drudge,20,2"), "a ghost is not counted by name either"); + rig.M.SetGhostCheck(null); Check.False(rig.Holds(C.NoMonstersWithinDistance, ""), "empty means 20"); Check.False(rig.Holds(C.NoMonstersWithinDistance, "0"), "0 means 20"); Check.False(rig.Holds(C.NoMonstersWithinDistance, "junk"), "junk means 20"); - // Priority counts use the Monsters list (Default excluded) and, unlike the two above, - // do count a monster that never had a health update. + // Priority counts use the Monsters list (Default excluded) and, like the two above, + // count a monster that never had a health update. Check.True(rig.Holds(C.MonsterPriorityCountWithinDistance, "2,20"), "drudge + untracked lurker"); Check.False(rig.Holds(C.MonsterPriorityCountWithinDistance, "3,20"), "not three within 20"); Check.True(rig.Holds(C.MonsterPriorityCountWithinDistance, "3,100"), "three within 100"); diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/MonsterProfileTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterProfileTests.cs new file mode 100644 index 0000000..f753592 --- /dev/null +++ b/Tools/RynthCore.RynthAiHostTests/Tests/MonsterProfileTests.cs @@ -0,0 +1,165 @@ +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using RynthCore.Plugin.RynthAi; +using RynthCore.Plugin.RynthAi.LegacyUi; +using RynthCore.Plugin.Shared; +using RynthCore.RynthAiHostTests.Fakes; +using RynthCore.RynthAiTests.Harness; + +namespace RynthCore.RynthAiHostTests.Tests; + +// 2026-11-18: the Monsters rules belong to the settings profile. Before, the MonsterProfiles +// file (one per character) overrode every profile at login, so after editing the Monsters list +// under one profile, a reload or relog on another profile brought those rules back: a Void +// profile's Default row (off hand Auto) replaced the main profile's (two hand wraps), and the +// character fought with one weapon while the Monsters tab showed the wrong list. Now the file is +// the active profile's copy, tagged ".profile" with that profile's name. +internal static class MonsterProfileTests +{ + private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + private const int HandWraps = unchecked((int)0x801A1F0D); + private const int OffhandAuto = 1; + + public static void Register(Runner r) + { + r.Add("monsters per profile: switching profiles switches the Monsters list", SwitchSwitchesList); + r.Add("monsters per profile: a relog keeps the profile's own list, not another profile's file", RelogKeepsOwnList); + r.Add("monsters per profile: an untagged Monsters file (from before) still loads, then is tagged", UntaggedFileLoads); + r.Add("monsters per profile: a Monster Editor save still reloads into the profile in use", EditorSaveReloads); + } + + private sealed class Scratch : IDisposable + { + private readonly string? _buffs = BuffProfileStore.FolderOverride; + public readonly string Root, CharDir, MonstersFile; + + public Scratch(string name) + { + Root = Path.Combine(Program.TempRoot, "monster-profiles", name); + if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true); + Directory.CreateDirectory(Root); + LegacyDashboardRenderer.ProfilesBase = Path.Combine(Root, "SettingsProfiles"); + LegacyDashboardRenderer.MonstersBase = Path.Combine(Root, "MonsterProfiles"); + BuffProfileStore.FolderOverride = Path.Combine(Root, "BuffProfiles"); + CharDir = Path.Combine(LegacyDashboardRenderer.ProfilesBase, "TestWorld", "Tester"); + MonstersFile = Path.Combine(LegacyDashboardRenderer.MonstersBase, "TestWorld", "Tester.json"); + } + + public string Tag => File.Exists(MonstersFile + ".profile") ? File.ReadAllText(MonstersFile + ".profile").Trim() : ""; + + public void Dispose() => BuffProfileStore.FolderOverride = _buffs; + } + + /// A fresh dashboard logged in as Tester on TestWorld (a login or a reload). + private static LegacyDashboardRenderer Login(out LegacyUiSettings s) + { + FakeHost.Reset(); + DataWriteGuard.Reset(); + FakeHost.WorldName = "TestWorld"; + var dash = new LegacyDashboardRenderer(FakeHost.Create()); + FakeHost.WorldName = "TestWorld"; + dash.LoadSettings("Tester"); + s = (LegacyUiSettings)typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.GetValue(dash)!; + return dash; + } + + private static MonsterRule DefaultRow(LegacyUiSettings s) => + s.MonsterRules.Single(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase)); + + private static void Select(LegacyDashboardRenderer dash, string profile) => + dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, profile)); + + /// Default: Melee, the second hand wraps in the off hand, plus a Drudge rule. Void (Save As): off hand Auto, Void Magic, no Drudge. + private static LegacyDashboardRenderer TwoProfiles(out LegacyUiSettings s) + { + var dash = Login(out s); + DefaultRow(s).OffhandId = HandWraps; + DefaultRow(s).PreferredDamage = "Melee"; + s.MonsterRules.Add(new MonsterRule { Name = "Drudge", Priority = 3 }); + dash.SaveMonsterRules(); + Check.True(dash.SaveProfileNow(ProfileKind.Settings).Ok, "Default saved"); + + Check.True(dash.SaveProfileAs(ProfileKind.Settings, "Void", replace: false).Ok, "Save As Void"); + Check.Eq(s.SelectedProfile, "Void", "Void in use"); + DefaultRow(s).OffhandId = OffhandAuto; + DefaultRow(s).PreferredDamage = "Void Magic"; + s.MonsterRules.RemoveAll(r => r.Name == "Drudge"); + dash.SaveMonsterRules(); // as the Monsters panel does after an edit + Check.True(dash.SaveProfileNow(ProfileKind.Settings).Ok, "Void saved"); + return dash; + } + + private static void SwitchSwitchesList() + { + using var t = new Scratch("switch"); + var dash = TwoProfiles(out var s); + Check.Eq(t.Tag, "Void", "the Monsters file is Void's while Void is in use"); + + Select(dash, "Default"); + Check.Eq(s.SelectedProfile, "Default", "Default in use"); + Check.Eq(DefaultRow(s).OffhandId, HandWraps, "Default's off hand (the hand wraps), not Void's Auto"); + Check.Eq(DefaultRow(s).PreferredDamage, "Melee", "Default's damage"); + Check.True(s.MonsterRules.Any(r => r.Name == "Drudge"), "Default's own Drudge rule is back"); + Check.Eq(t.Tag, "Default", "the Monsters file is tagged Default"); + Check.True(File.ReadAllText(t.MonstersFile).Contains("Drudge"), "and holds Default's rules (for the Monster Editor)"); + + Select(dash, "Void"); + Check.Eq(DefaultRow(s).OffhandId, OffhandAuto, "Void's own off hand again"); + Check.False(s.MonsterRules.Any(r => r.Name == "Drudge"), "Void has no Drudge rule"); + Check.Eq(t.Tag, "Void", "tagged Void"); + } + + private static void RelogKeepsOwnList() + { + using var t = new Scratch("relog"); + var dash = TwoProfiles(out var s); + Select(dash, "Default"); + + // The report: the file still held Void's rules while Default was the profile in use. + File.WriteAllText(t.MonstersFile, "[{\"Name\":\"Default\",\"Priority\":1,\"PreferredDamage\":\"Void Magic\",\"OffhandId\":1}]"); + File.WriteAllText(t.MonstersFile + ".profile", "Void"); + + Login(out s); + Check.Eq(s.SelectedProfile, "Default", "Default is the active profile"); + Check.Eq(DefaultRow(s).OffhandId, HandWraps, "a reload keeps Default's off hand"); + Check.True(s.MonsterRules.Any(r => r.Name == "Drudge"), "and Default's other rules"); + Check.Eq(t.Tag, "Default", "the file is Default's again"); + Check.True(File.ReadAllText(t.MonstersFile).Contains("Drudge"), "rewritten with Default's rules"); + Check.True(FakeHost.Logs.Any(l => l.Contains("held profile 'Void''s rules")), "logged why"); + } + + private static void UntaggedFileLoads() + { + using var t = new Scratch("untagged"); + var dash = Login(out var s); + Check.True(dash.SaveProfileNow(ProfileKind.Settings).Ok, "Default saved"); + Directory.CreateDirectory(Path.GetDirectoryName(t.MonstersFile)!); + File.Delete(t.MonstersFile + ".profile"); + // A file from before the tag (the one list every profile used): its rules are this profile's. + File.WriteAllText(t.MonstersFile, "[{\"Name\":\"Default\",\"Priority\":1},{\"Name\":\"Banderling\",\"Priority\":4}]"); + + Login(out s); + Check.True(s.MonsterRules.Any(r => r.Name == "Banderling"), "the untagged file's rules load, as before"); + Check.Eq(t.Tag, "Default", "and the file is now tagged with the profile in use"); + } + + private static void EditorSaveReloads() + { + using var t = new Scratch("editor"); + var dash = TwoProfiles(out var s); + Select(dash, "Default"); + + // The Monster Editor writes the rules file only; the tag stays Default's. + File.WriteAllText(t.MonstersFile, "[{\"Name\":\"Default\",\"Priority\":1,\"OffhandId\":" + HandWraps + "},{\"Name\":\"Mosswart\",\"Priority\":2}]"); + typeof(LegacyDashboardRenderer).GetField("_monsterFileChanged", Any)!.SetValue(dash, true); + dash.TickMonsterReload(); + Check.True(s.MonsterRules.Any(r => r.Name == "Mosswart"), "the editor's rules are in use"); + Check.Eq(t.Tag, "Default", "still Default's file"); + + Select(dash, "Void"); + Select(dash, "Default"); + Check.True(s.MonsterRules.Any(r => r.Name == "Mosswart"), "the editor's change was saved into Default (it survives a switch)"); + } +} diff --git a/Tools/RynthCore.RynthAiHostTests/Tests/SpellCatalogTests.cs b/Tools/RynthCore.RynthAiHostTests/Tests/SpellCatalogTests.cs index a116e6c..e5f29ef 100644 --- a/Tools/RynthCore.RynthAiHostTests/Tests/SpellCatalogTests.cs +++ b/Tools/RynthCore.RynthAiHostTests/Tests/SpellCatalogTests.cs @@ -33,6 +33,7 @@ internal static class SpellCatalogTests r.Add("buff profile: save, list and load round-trip", ProfileRoundTrip); r.Add("buff profile: an id-only entry is filled in; a newer schema is refused", ProfileNormalizeAndSchema); r.Add("buff profile: a chosen profile replaces the built-in list (order kept, no disabled or duplicate lines)", ProfileReplacesList); + r.Add("built-in buffs (R-20261119-195743-1993): Mana Conversion Mastery right after the four that raise casting skill, before the rest", ManaConversionEarly); r.Add("buff profile: a profile spell casts the best level known", ProfileResolvesTier); r.Add("buff profile: a name with no tier ladder falls back to its spell family", ProfileFamilyFallback); r.Add("buff profile: Loaded Files lists profiles, picks one by index, and the snapshot reports it", LoadedFilesPicker); @@ -175,6 +176,16 @@ internal static class SpellCatalogTests // ── Buffing with a profile ────────────────────────────────────────────── + private static void ManaConversionEarly() + { + var list = NewBuffs(500).BuildBuiltInBuffList(); + Check.Eq(string.Join(",", list.Take(5)), + "Creature Enchantment Mastery,Focus Self,Willpower Self,Life Magic Mastery,Mana Conversion Mastery", + "the four that raise casting skill, then Mana Conversion Mastery (it cheapens the rest)"); + Check.Eq(list.IndexOf("Strength Self"), 5, "then the other creature buffs"); + Check.Eq(list.Count(b => b == "Mana Conversion Mastery"), 1, "once"); + } + private static void ProfileReplacesList() { var buffs = NewBuffs(500);