Snapshot for release 2026.10.23.1 (internal 7581cff)

This commit is contained in:
Tom Bohar 2026-10-23 16:34:02 -04:00
commit 92f28bd243
73 changed files with 12203 additions and 308 deletions

View file

@ -370,14 +370,14 @@ public partial class BuffManager
/// </summary>
/// <summary>
/// A death or a portal dropped whatever the server had open: a wand use in flight is forgotten,
/// not judged a failed swap (see _directSwapMisses). RynthAiPlugin calls it with the death hold
/// and on entering portal space.
/// not judged a failed swap. RynthAiPlugin calls it with the death hold and on entering portal space.
/// </summary>
internal void ForgetPendingWield(string why)
{
DropWandSwap(why);
if (_pendingWieldId == 0) return;
_pendingWieldId = 0;
_host.Log($"[WieldGate] the wand's use in flight was cut short ({why}): not counted as a failed swap");
_host.Log($"[WieldGate] the wand's wield in flight was cut short ({why}): not counted as a failed swap");
}
internal void CancelPendingRecall(string why)

View file

@ -0,0 +1,202 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The wand swap as it was before 2026-10-22 (RynthSuite e613280), kept for Fast Weapon Swap off: a
/// use of the wand while a weapon is in hand (the client puts the weapon away), the pack route after
/// a miss, and the swap gate's flat 3 s after every pack move. Fast Weapon Swap on goes through
/// HandSwapSequence instead (BuffManager.WandSwapStep). Off is the default until the new swap has run
/// a night on Drakkon; this file goes once it is the only way.
/// </summary>
public partial class BuffManager
{
private int _directSwapMisses; // direct swaps in a row that didn't get the wand into the hand
private bool _packFirstNext; // the next swap goes through the pack (one miss)
private bool _pendingWieldDirect; // the wand's use in flight was a direct swap (a weapon in hand)
internal const int DirectSwapMissesToStick = 2;
private bool PackFirst => _packFirstNext || _directSwapMisses >= DirectSwapMissesToStick;
// The swap gate's claim count when the wand's use went out: a later claim means another swap
// (combat putting the axe back, 12:39 on 10-06) changed the hands, so the result says nothing.
private long _pendingWieldClaim;
private int _bowDequipPendingId;
private DateTime _bowDequipAt = DateTime.MinValue;
private int _bowDequipAttempts;
private const int BowDequipMaxAttempts = 3;
/// <summary>EnsureMagicMode's branch for a wand not yet in hand, before 2026-10-22.</summary>
private bool LegacyWandSwap(int wandId, bool forBuff)
{
// Wield gate: don't spam UseObject. Hold off after the first issue
// until either the wielded check confirms (cleared on the Magic-mode
// branch above) or the resolve timeout elapses, then cool down
// before retrying. Mirrors the no-chat-timeout pattern used for
// spell casts at the top of OnHeartbeat. Checked BEFORE the shared
// swap gate so a denied attempt never claims the cross-subsystem slot.
DateTime now = Now;
if (now < _wieldCooldownUntil)
return false;
if (_pendingWieldId != 0)
{
if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs)
return false;
if (_weaponSwapGate != null && _weaponSwapGate.Claims != _pendingWieldClaim)
{
_pendingWieldId = 0; // another swap since ours: not a failed wield
return false;
}
int stillInHand = _pendingWieldDirect ? FindWieldedNonWandWeapon(wandId) : 0;
if (stillInHand != 0 && IsWieldedLive(stillInHand))
{
_directSwapMisses++;
_packFirstNext = true;
_pendingWieldId = 0;
_host.Log($"[WieldGate] using the wand didn't put 0x{(uint)stillInHand:X8} away in {WieldResolveTimeoutMs:0} ms; " +
(_directSwapMisses >= DirectSwapMissesToStick
? $"{_directSwapMisses} in a row: from now on the weapon goes into a pack first"
: "the next swap puts the weapon into a pack first, then the use is tried again"));
return false;
}
_host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " +
$"{WieldResolveTimeoutMs:0}ms — cooling down {WieldCooldownMs:0}ms");
NoteWandWieldFailed(_pendingWieldId);
_pendingWieldId = 0;
_wieldCooldownUntil = now.AddMilliseconds(WieldCooldownMs);
// FIX: bound the previously-infinite wield loop. If the wand still won't
// wield after a few cooldowns (e.g. no pack to free the bow, or an
// unresolvable collision), degrade so buffing yields and combat runs.
if (++_wieldGateFailCount >= WieldGateFailMax)
return SignalSwapFailure(forBuff, FindWieldedNonWandWeapon(wandId), wandId);
return false;
}
// Shared weapon-swap gate: if CombatManager (or anything else) swapped
// a weapon within the last few seconds, wait — two equips in flight
// collide ("you can only move or use one item at a time" / AV).
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("buff-wand"))
return false;
// Tear down any in-flight physical combat BEFORE the UseObject. The
// transition Melee/Missile → Magic-via-wand must explicitly cancel the
// pending attack, or AC gets a UseObject while m_bAttacking is still
// set and wedges the item-action gate. Done only after we've claimed
// the swap slot above, so we don't cancel an attack then fail to swap.
if (!_combatTeardownDoneForCurrentBuffCycle &&
(CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Buff/WandSwap");
_combatTeardownDoneForCurrentBuffCycle = true;
_host.Log($"[BuffPre] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})");
}
// FIX: stock ACE will NOT auto-dequip the bow for a Held-slot wand
// (CheckWeaponCollision refuses while mainhand != null). Stow the wielded
// non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern,
// AV-safe), then UseObject(wand) once the hand is free. Fully bounded.
int bowId = FindWieldedNonWandWeapon(wandId);
if (bowId != 0 && (PackFirst || !IsWieldedLive(bowId))) // else the use swaps (see _directSwapMisses)
{
if (_bowDequipPendingId == bowId
&& (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs
&& IsWieldedLive(bowId))
return false; // dequip still resolving
if (IsWieldedLive(bowId))
{
int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
if (openPack == 0 || _bowDequipAttempts >= BowDequipMaxAttempts)
{
// No verified-open pack to receive the bow, or repeated dequip
// failures -> the swap provably can't complete now. Degrade.
_host.Log($"[WieldGate] bow 0x{(uint)bowId:X8} dequip blocked (openPack=0x{(uint)openPack:X8}, attempts={_bowDequipAttempts}/{BowDequipMaxAttempts}) — degrading");
if (openPack == 0)
WorldObjectCache.WarnPackFull(_host, "can't put the weapon away to switch to the wand, so buffs and spell heals can't cast");
return SignalSwapFailure(forBuff, bowId, wandId);
}
_bowDequipAttempts++;
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
_bowDequipPendingId = bowId;
_bowDequipAt = now;
_lastCastAttempt = now;
_host.Log($"[WieldGate] dequip bow 0x{(uint)bowId:X8} -> pack 0x{(uint)openPack:X8} (attempt {_bowDequipAttempts}/{BowDequipMaxAttempts}) before wand equip");
return false; // yield until the bow is out of hand
}
_bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand
}
_pendingWieldDirect = bowId != 0 && !PackFirst;
// Hands free: wield the caster into the Held slot (GetAndWieldItem, the paperdoll drag),
// as the off hand does. A use only wields a plain caster: a caster with a spell of its own
// (Electric Baton, Acid Staff) takes the use as "cast it" and the client says it must be
// wielded first (Drakkon, 2026-10-18 14:00). With a weapon still in hand the use stays
// (the client swaps); when that misses, the next swap empties the hands first.
if (!_pendingWieldDirect && _host.HasWieldItem)
{
_host.WieldItem((uint)wandId, HeldSlot);
_host.Log($"[WieldGate] wielding 0x{(uint)wandId:X8} '{_worldObjectCache?[wandId]?.Name}' into the Held slot");
}
else
_host.UseFor((uint)wandId, "Buff", _pendingWieldDirect ? "buffing: switch to the wand" : "buffing: wield the wand");
NoteStanceRequest();
_pendingWieldClaim = _weaponSwapGate?.Claims ?? 0;
_pendingWieldId = wandId;
_pendingWieldAt = now;
_lastCastAttempt = now;
return false; // Yield — let the server equip the wand
}
/// <summary>EnsureMagicMode's first step once the wand reads wielded, before 2026-10-22.</summary>
private void LegacyWandWielded(int wandId)
{
if (_pendingWieldId == wandId)
{
_pendingWieldId = 0;
_wieldCooldownUntil = DateTime.MinValue;
if (_pendingWieldDirect) _directSwapMisses = 0; // the use swapped: back to direct swaps
_packFirstNext = false; // a pack-route swap done: the next one tries the use
}
}
// The currently-wielded non-wand weapon (the bow) that blocks the Held-slot wand; else
// what is in the off hand (a shield, or an off-hand weapon): ACE refuses a Held-slot caster
// beside either. With the global Offhand setting None the off hand is never touched (the
// wand then can't be wielded; logged once).
private int FindWieldedNonWandWeapon(int wandId)
{
if (_worldObjectCache == null) return 0;
int offhand = 0;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: true))
{
if (wo.Id == wandId) continue;
if (IsWandObject(wo)) continue;
if (WorldObjectCache.IsAmmo(wo)) continue; // arrows stay on; only the bow blocks the wand
if (IsInOffhandSlot(wo)) { offhand = wo.Id; continue; }
if ((wo.ObjectClass == AcObjectClass.MeleeWeapon
|| wo.ObjectClass == AcObjectClass.MissileWeapon)
&& WorldObjectCache.IsWieldedByPlayer(_host, wo))
return wo.Id;
}
if (offhand != 0 && OffhandRules.Parse(_settings.OffhandDefault, OffhandMode.Auto) == OffhandMode.None)
{
if (!_offhandNoneNoted)
{
_offhandNoneNoted = true;
_host.Log($"[WieldGate] 0x{(uint)offhand:X8} '{_worldObjectCache[offhand]?.Name}' is in the off hand and Offhand is None — leaving it; the server won't wield the wand beside it");
}
return 0;
}
return offhand;
}
private static bool IsInOffhandSlot(WorldObject wo) =>
(wo.Values(LongValueKey.CurrentWieldedLocation, 0) & OffhandRules.ShieldSlot) != 0;
}

View file

@ -0,0 +1,90 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
using System.Threading;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// /ra swaptest [spell] (2026-10-22): the wand swap and one cast of a self spell, timed, by the
/// same EnsureMagicMode a heal or a buff goes through. With no spell named, the first known of a
/// few spells every caster school has (Lifestone Recall, Portal Recall, the level 1 item auras).
/// A fizzle is as good as a cast here: what it measures is the swap and the stance before it.
/// </summary>
public partial class BuffManager
{
private string? _swapTestRequest; // set on AC's thread by the command, taken on the pump
private int _swapTestSpellId;
private string _swapTestName = "";
private DateTime _swapTestAt = DateTime.MinValue;
private const double SwapTestGiveUpSec = 20;
private static readonly string[] SwapTestDefaults =
{
"Lifestone Recall", "Portal Recall", "Aura of Blood Drinker Self I", "Aura of Swift Killer Self I",
"Aura of Heart Seeker Self I", "Aura of Defender Self I", "Aura of Hermetic Link Self I",
};
/// <summary>The /ra swaptest command (any thread).</summary>
internal void RequestSwapTest(string spell) => Interlocked.Exchange(ref _swapTestRequest, spell ?? "");
/// <summary>Behind the same gates as the vitals step. True while the test holds the tick.</summary>
private bool TickSwapTest()
{
string? req = Interlocked.Exchange(ref _swapTestRequest, null);
if (req != null) StartSwapTest(req.Trim());
if (_swapTestSpellId == 0) return false;
if ((Now - _swapTestAt).TotalSeconds > SwapTestGiveUpSec)
{
_host.WriteToChat($"[RynthAi] Swap test: no Magic stance in {SwapTestGiveUpSec:0} s ({LastWandSwapTrail}).", 2);
_host.Log($"[SwapTest] gave up after {SwapTestGiveUpSec:0} s");
_swapTestSpellId = 0;
return false;
}
if (!EnsureMagicMode()) return true; // a swap step or the stance is on its way
int id = _swapTestSpellId;
_swapTestSpellId = 0;
double ms = (Now - _swapTestAt).TotalMilliseconds;
bool sent = _host.CastSpellFor((uint)_host.GetPlayerId(), id, "Buff", _swapTestName);
_lastCastAttempt = Now;
string swap = LastWandSwapTrail.Length > 0 ? $"; the swap took {LastWandSwapMs:0} ms ({LastWandSwapTrail})" : "; no swap needed";
_host.Log($"[SwapTest] '{_swapTestName}' {(sent ? "cast" : "refused by the client")} {ms:0} ms after the request{swap}");
_host.WriteToChat($"[RynthAi] Swap test: {_swapTestName} {(sent ? "cast" : "refused")} {ms / 1000:0.00} s after the request{swap}.", 1);
LastWandSwapTrail = "";
return true;
}
private void StartSwapTest(string spell)
{
if (spell.StartsWith("burst", StringComparison.OrdinalIgnoreCase))
{
SwapBurst = !spell.EndsWith("off", StringComparison.OrdinalIgnoreCase);
_host.WriteToChat($"[RynthAi] Swap test: the burst is {(SwapBurst ? "on" : "off")} until the next reload (with Fast Weapon Swap it is on by itself).", 1);
_host.Log($"[SwapTest] burst {(SwapBurst ? "on" : "off")}");
return;
}
int id = 0;
string name = "";
foreach (string candidate in spell.Length > 0 ? new[] { spell } : SwapTestDefaults)
{
var e = SpellCatalog.GetByName(candidate);
if (e == null || !_spellManager.IsKnownSpellId(e.Id)) continue;
id = e.Id;
name = e.Name;
break;
}
if (id == 0)
{
_host.WriteToChat(spell.Length > 0
? $"[RynthAi] Swap test: '{spell}' isn't a spell this character knows."
: "[RynthAi] Swap test: none of the default test spells is known; name one: /ra swaptest <spell>.", 2);
return;
}
_swapTestSpellId = id;
_swapTestName = name;
_swapTestAt = Now;
LastWandSwapTrail = "";
_host.Log($"[SwapTest] start: '{name}' (mode {CurrentCombatMode})");
}
}

View file

@ -692,30 +692,34 @@ public partial class BuffManager : IDisposable
// stow the bow into a capacity-verified open pack FIRST (AutoCram pattern), then wield
// the wand. All paths are bounded so a stale/no-op dequip or unwieldable wand can never
// loop forever; on exhaustion the buff family is parked and the bot fights unbuffed.
// Switch like a player (2026-10-06): a use of the wand goes through ClientUISystem::UseObject,
// the client's double-click, which puts the weapon in hand away by itself (ACE's
// DoHandleActionGetAndWieldItem: "the client handles dequipping a lot of conflicting items
// automatically"). Drakkon's axe -> wand took 4.2 s with the pack move first (1.2 s for it,
// then the swap gate's flat 3 s). The pack move stays as the fallback: once a use hasn't
// got the wand into the hand in WieldResolveTimeoutMs, the weapon goes into a pack first.
// Not for the rest of the session on one miss (2026-10-14): a swap the server never finished
// because Drakkon died (13:40) set it, and every later heal from melee took the pack route, the
// move plus the swap gate's flat 3 s, 4+ s with nothing healing; he died twice more. Now one miss
// sends the next swap through the pack and the one after tries the use again; two misses in a
// row keep the pack route. A swap a death or a portal cut short counts for nothing
// (ForgetPendingWield).
private int _directSwapMisses; // direct swaps in a row that didn't get the wand into the hand
private bool _packFirstNext; // the next swap goes through the pack (one miss)
private bool _pendingWieldDirect; // the wand's use in flight was a direct swap (a weapon in hand)
internal const int DirectSwapMissesToStick = 2;
private bool PackFirst => _packFirstNext || _directSwapMisses >= DirectSwapMissesToStick;
// The swap gate's claim count when the wand's use went out: a later claim means another swap
// (combat putting the axe back, 12:39 on 10-06) changed the hands, so the result says nothing.
private long _pendingWieldClaim;
private int _bowDequipPendingId;
private DateTime _bowDequipAt = DateTime.MinValue;
private int _bowDequipAttempts;
private const int BowDequipMaxAttempts = 3;
// The wand swap, as fast as the server allows (2026-10-22, HandSwapSequence): the off hand into
// a pack, then the main hand, then the wand wielded into the Held slot, each the moment the
// server's wielded list says the last step landed. One claim of the swap gate is held for all
// of it. Before, Drakkon's two Hand Wraps -> Sceptre took 7.2 s to the first cast: each pack
// move held the next step the gate's flat 3 s, and the client's own use of the wand (the route
// tried first) takes the main hand first, which costs the off hand a second stance change.
// The why, step by step, is at the top of HandSwapSequence.
private readonly HandSwapSequence _wandSwap = new();
private bool _wandSwapOpen; // started and not yet finished (its log line and the gate's release are owed)
private int _wandSwapWandId;
private bool _wandSwapForBuff;
private int _wandSwapMainAtStart; // the main hand's weapon when it began (put back if the swap fails)
private int _wandSwapLastMoved; // its last pack move or wield: the gate holds the next swap after it
private DateTime _wandSwapTouchedAt = DateTime.MinValue; // EnsureMagicMode last asked for it
// Not asked for this long (the heal or buff no longer needs it): the swap stops, not a failure.
// Longer than the pacer holds the vitals step for our own peace request (ModeMaxMs 2 s).
private const double WandSwapAbandonMs = 3000;
// The wand went on in a combat mode: the server switches to Magic itself (ACE TryShuffleStance),
// after the stance change of the last unwield. Our own ChangeCombatMode(Magic) waits this long for
// it: a second stance change queued behind the server's is how a cast gets held open.
private DateTime _serverMagicDueUntil = DateTime.MinValue;
private const double ServerMagicWaitMs = 2500;
// A swap that went through peace just put the wand in hand: Magic is asked for at once (see the request).
private DateTime _magicAfterPeaceUntil = DateTime.MinValue;
private const double MagicAfterPeaceMs = 2500;
/// <summary>The last wand swap: how long it took and its steps with the server's answer times.</summary>
internal double LastWandSwapMs { get; private set; }
internal string LastWandSwapTrail { get; private set; } = "";
private int _wieldGateFailCount;
private const int WieldGateFailMax = 3;
private bool _wandSwapExhausted; // per-EnsureMagicMode(forBuff) signal: swap can't succeed now
@ -1104,7 +1108,7 @@ public partial class BuffManager : IDisposable
/// </summary>
private string ActiveHealLine(int hp, int stamPct, out int value, out bool inCombat)
{
inCombat = _combatManager?.HasCloseThreat(System.Math.Max(1, _settings.MonsterRange)) == true;
inCombat = InCombatNow();
value = 0;
if (_settings.EmergencyHealAt > 0 && hp <= _settings.EmergencyHealAt) { value = _settings.EmergencyHealAt; return "Emergency Heal At"; }
if (StaminaToHealthAllowed(_settings, hp, stamPct)) { value = _settings.StaminaToHealthAt; return "Stamina To Health At"; }
@ -1287,7 +1291,11 @@ public partial class BuffManager : IDisposable
TickRechargeRequest(); // /ra recharge: one vitals pass, macro on or off (BuffManager.Recharge.cs)
TickOneTouchRequest(); // /ra heal, /ra stam, /ra mana: one-touch recharge, macro on or off (BuffManager.OneTouch.cs)
if (!_settings.IsMacroRunning) return;
if (!_settings.IsMacroRunning) { DropWandSwap("the macro stopped"); return; }
// A wand swap's next step goes as soon as the server has answered the last (before the cast gates).
NoteModeChange();
TickWandSwap();
// Close casts the server reports finished, and say once when one is being held open.
PollCastTracker();
@ -1640,6 +1648,13 @@ public partial class BuffManager : IDisposable
return;
}
// /ra swaptest: the wand swap and one cast, timed (BuffManager.SwapTest.cs). After the vitals.
if (TickSwapTest())
{
Hold("swap test");
return;
}
// Only a recovery retry got past Spell Interval; nothing else goes inside it.
if (intervalHeld)
{
@ -5099,6 +5114,9 @@ public partial class BuffManager : IDisposable
_bowDequipAttempts = 0;
_wieldGateFailCount = 0;
_wandWieldFails.Clear();
_serverMagicDueUntil = DateTime.MinValue;
if (_wandSwap.Active) FinishWandSwap(Now, done: true); // the wand went on and Magic came: the swap is over
_magicAfterPeaceUntil = DateTime.MinValue;
// In Magic, but the stance we asked for may still be settling: yield the tick.
return StanceSettled(urgentHeal);
}
@ -5113,12 +5131,12 @@ public partial class BuffManager : IDisposable
// _lastBuffStanceAttempt), while buffing held the bot.
int noWandShift = Math.Min(_buffStanceConsecutiveFails, 5);
int noWandGateMs = Math.Min(1000 << noWandShift, 30000);
if ((RynthClock.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
if ((Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "no wand: Magic mode bare-handed"))
{
NoteStanceRequest();
_lastBuffStanceAttempt = RynthClock.Now;
_lastCastAttempt = RynthClock.Now;
_lastBuffStanceAttempt = Now;
_lastCastAttempt = Now;
if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++;
if (_buffStanceConsecutiveFails > 1)
_host.Log($"[BuffStance] no wand: ChangeCombatMode(Magic) retry #{_buffStanceConsecutiveFails} (next retry in {noWandGateMs / 1000}s)");
@ -5158,130 +5176,22 @@ public partial class BuffManager : IDisposable
alreadyWielded = true;
}
if (!alreadyWielded)
if (!_settings.FastWeaponSwap)
{
// Wield gate: don't spam UseObject. Hold off after the first issue
// until either the wielded check confirms (cleared on the Magic-mode
// branch above) or the resolve timeout elapses, then cool down
// before retrying. Mirrors the no-chat-timeout pattern used for
// spell casts at the top of OnHeartbeat. Checked BEFORE the shared
// swap gate so a denied attempt never claims the cross-subsystem slot.
DateTime now = RynthClock.Now;
if (now < _wieldCooldownUntil)
// Fast Weapon Swap off: the swap as before 2026-10-22 (BuffManager.LegacySwap.cs).
if (!alreadyWielded) return LegacyWandSwap(wandId, forBuff);
LegacyWandWielded(wandId);
}
else if (_wandSwap.Active || !alreadyWielded)
{
// A cooldown after a swap that didn't finish: no new swap until it ends.
if (!_wandSwap.Active && Now < _wieldCooldownUntil)
return false;
if (_pendingWieldId != 0)
{
if ((now - _pendingWieldAt).TotalMilliseconds < WieldResolveTimeoutMs)
return false;
if (_weaponSwapGate != null && _weaponSwapGate.Claims != _pendingWieldClaim)
{
_pendingWieldId = 0; // another swap since ours: not a failed wield
return false;
}
int stillInHand = _pendingWieldDirect ? FindWieldedNonWandWeapon(wandId) : 0;
if (stillInHand != 0 && IsWieldedLive(stillInHand))
{
_directSwapMisses++;
_packFirstNext = true;
_pendingWieldId = 0;
_host.Log($"[WieldGate] using the wand didn't put 0x{(uint)stillInHand:X8} away in {WieldResolveTimeoutMs:0} ms; " +
(_directSwapMisses >= DirectSwapMissesToStick
? $"{_directSwapMisses} in a row: from now on the weapon goes into a pack first"
: "the next swap puts the weapon into a pack first, then the use is tried again"));
return false;
}
_host.Log($"[WieldGate] UseObject(0x{(uint)_pendingWieldId:X8}) not confirmed in " +
$"{WieldResolveTimeoutMs:0}ms — cooling down {WieldCooldownMs:0}ms");
NoteWandWieldFailed(_pendingWieldId);
_pendingWieldId = 0;
_wieldCooldownUntil = now.AddMilliseconds(WieldCooldownMs);
// FIX: bound the previously-infinite wield loop. If the wand still won't
// wield after a few cooldowns (e.g. no pack to free the bow, or an
// unresolvable collision), degrade so buffing yields and combat runs.
if (++_wieldGateFailCount >= WieldGateFailMax)
return SignalSwapFailure(forBuff, FindWieldedNonWandWeapon(wandId), wandId);
// The wand swap's next step (HandSwapSequence): the off hand, the main hand, then the
// wand, each as soon as the server answers the last. True once the wand is in hand.
_wandSwapTouchedAt = Now;
if (!WandSwapStep(wandId, forBuff, Now))
return false;
}
// Shared weapon-swap gate: if CombatManager (or anything else) swapped
// a weapon within the last few seconds, wait — two equips in flight
// collide ("you can only move or use one item at a time" / AV).
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("buff-wand"))
return false;
// Tear down any in-flight physical combat BEFORE the UseObject. The
// transition Melee/Missile → Magic-via-wand must explicitly cancel the
// pending attack, or AC gets a UseObject while m_bAttacking is still
// set and wedges the item-action gate. Done only after we've claimed
// the swap slot above, so we don't cancel an attack then fail to swap.
if (!_combatTeardownDoneForCurrentBuffCycle &&
(CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Buff/WandSwap");
_combatTeardownDoneForCurrentBuffCycle = true;
_host.Log($"[BuffPre] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})");
}
// FIX: stock ACE will NOT auto-dequip the bow for a Held-slot wand
// (CheckWeaponCollision refuses while mainhand != null). Stow the wielded
// non-wand weapon into a capacity-verified open pack FIRST (AutoCram pattern,
// AV-safe), then UseObject(wand) once the hand is free. Fully bounded.
int bowId = FindWieldedNonWandWeapon(wandId);
if (bowId != 0 && (PackFirst || !IsWieldedLive(bowId))) // else the use swaps (see _directSwapMisses)
{
if (_bowDequipPendingId == bowId
&& (now - _bowDequipAt).TotalMilliseconds < WieldResolveTimeoutMs
&& IsWieldedLive(bowId))
return false; // dequip still resolving
if (IsWieldedLive(bowId))
{
int openPack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
if (openPack == 0 || _bowDequipAttempts >= BowDequipMaxAttempts)
{
// No verified-open pack to receive the bow, or repeated dequip
// failures -> the swap provably can't complete now. Degrade.
_host.Log($"[WieldGate] bow 0x{(uint)bowId:X8} dequip blocked (openPack=0x{(uint)openPack:X8}, attempts={_bowDequipAttempts}/{BowDequipMaxAttempts}) — degrading");
if (openPack == 0)
WorldObjectCache.WarnPackFull(_host, "can't put the weapon away to switch to the wand, so buffs and spell heals can't cast");
return SignalSwapFailure(forBuff, bowId, wandId);
}
_bowDequipAttempts++;
if (_worldObjectCache?[bowId] is WorldObject blocker && IsInOffhandSlot(blocker))
OffhandStowed?.Invoke(bowId); // a shield: combat puts it back after
_host.MoveItemInternal((uint)bowId, (uint)openPack, 0, 1); // amount>=1 (engine rejects 0)
_weaponSwapGate?.NoteMove(bowId, wieldedNow: true);
_bowDequipPendingId = bowId;
_bowDequipAt = now;
_lastCastAttempt = now;
_host.Log($"[WieldGate] dequip bow 0x{(uint)bowId:X8} -> pack 0x{(uint)openPack:X8} (attempt {_bowDequipAttempts}/{BowDequipMaxAttempts}) before wand equip");
return false; // yield until the bow is out of hand
}
_bowDequipPendingId = 0; // bow confirmed unwielded — fall through to wield the wand
}
_pendingWieldDirect = bowId != 0 && !PackFirst;
// Hands free: wield the caster into the Held slot (GetAndWieldItem, the paperdoll drag),
// as the off hand does. A use only wields a plain caster: a caster with a spell of its own
// (Electric Baton, Acid Staff) takes the use as "cast it" and the client says it must be
// wielded first (Drakkon, 2026-10-18 14:00). With a weapon still in hand the use stays
// (the client swaps); when that misses, the next swap empties the hands first.
if (!_pendingWieldDirect && _host.HasWieldItem)
{
_host.WieldItem((uint)wandId, HeldSlot);
_host.Log($"[WieldGate] wielding 0x{(uint)wandId:X8} '{_worldObjectCache?[wandId]?.Name}' into the Held slot");
}
else
_host.UseFor((uint)wandId, "Buff", _pendingWieldDirect ? "buffing: switch to the wand" : "buffing: wield the wand");
NoteStanceRequest();
_pendingWieldClaim = _weaponSwapGate?.Claims ?? 0;
_pendingWieldId = wandId;
_pendingWieldAt = now;
_lastCastAttempt = now;
return false; // Yield — let the server equip the wand
}
// Wand is wielded — clear the gate and switch stance.
@ -5289,8 +5199,15 @@ public partial class BuffManager : IDisposable
{
_pendingWieldId = 0;
_wieldCooldownUntil = DateTime.MinValue;
if (_pendingWieldDirect) _directSwapMisses = 0; // the use swapped: back to direct swaps
_packFirstNext = false; // a pack-route swap done: the next one tries the use
}
// The wand went on in a combat mode: the server switches to Magic by itself once the stance
// change of the last unwield is done (TryShuffleStance). Wait for that rather than queue a
// second stance change behind it.
if (Now < _serverMagicDueUntil)
{
LastBuffSkipReason = "the server is switching to Magic";
return false;
}
// Deadlock episode tracking: wand wielded but mode refuses to flip.
@ -5301,10 +5218,10 @@ public partial class BuffManager : IDisposable
// the clock restarts, so the refusals that follow are not counted as a wedged stance.
if (_buffStanceStuckSince != DateTime.MinValue && ActionPacer.LastEngineRefusalMs > _buffStanceStuckStartMs)
{
_buffStanceStuckSince = RynthClock.Now;
_buffStanceStuckSince = Now;
_buffStanceStuckStartMs = ActionPacer.NowMs();
}
double stuckMs = _buffStanceStuckSince == DateTime.MinValue ? 0 : (RynthClock.Now - _buffStanceStuckSince).TotalMilliseconds;
double stuckMs = _buffStanceStuckSince == DateTime.MinValue ? 0 : (Now - _buffStanceStuckSince).TotalMilliseconds;
// Capped re-equip recovery (mirrors CombatManager): handles the rare
// stale "wielded reads true" by resyncing the wield once or twice.
@ -5312,15 +5229,15 @@ public partial class BuffManager : IDisposable
// and unbounded re-equip jams the item-action queue permanently.
if (_buffStanceReEquips < BuffStanceReEquipMax
&& stuckMs > BuffStanceStuckRecoverMs
&& (RynthClock.Now - _buffStanceLastRecoverAt).TotalMilliseconds > BuffStanceStuckRecoverMs
&& (Now - _buffStanceLastRecoverAt).TotalMilliseconds > BuffStanceStuckRecoverMs
&& (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("buff-stance-recovery")))
{
_buffStanceLastRecoverAt = RynthClock.Now;
_buffStanceLastRecoverAt = Now;
_buffStanceReEquips++;
_host.Log($"[BuffStance] STUCK {stuckMs:0}ms (wielded, mode={CurrentCombatMode}≠Magic) — re-equip attempt {_buffStanceReEquips}/{BuffStanceReEquipMax} 0x{(uint)wandId:X8}");
_host.UseFor((uint)wandId, "Buff", "buffing: stance stuck, wield the wand again");
NoteStanceRequest();
_lastCastAttempt = RynthClock.Now;
_lastCastAttempt = Now;
return false;
}
// Past the cap and clearly wedged: warn ONCE so a multi-hour silent
@ -5340,13 +5257,17 @@ public partial class BuffManager : IDisposable
if (shift > 5) shift = 5;
int gateMs = 1000 << shift; // 1s, 2s, 4s, 8s, 16s, 32s
if (gateMs > 30000) gateMs = 30000; // cap at 30s
if ((RynthClock.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"))
// Right after a swap through peace, Magic goes as soon as the wand is in hand: the server holds a
// Magic change until its peace animation ends by itself (NextUseTime), and on that route no
// other stance change can be queued. Only past our own peace request, never past anything else.
bool magicAfterPeace = Now < _magicAfterPeaceUntil && OnlyOurPeaceRequestPending();
if ((Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode", force: magicAfterPeace))
{
if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = RynthClock.Now; _buffStanceStuckStartMs = ActionPacer.NowMs(); }
if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = Now; _buffStanceStuckStartMs = ActionPacer.NowMs(); }
NoteStanceRequest();
_lastBuffStanceAttempt = RynthClock.Now;
_lastCastAttempt = RynthClock.Now;
_lastBuffStanceAttempt = Now;
_lastCastAttempt = Now;
if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++;
// Visible retry line (throttled by the backoff itself): the
// 2026-06-12 coma produced ZERO log output from this path.
@ -5360,40 +5281,6 @@ public partial class BuffManager : IDisposable
public Action<int>? OffhandStowed { get; set; }
private bool _offhandNoneNoted;
// The currently-wielded non-wand weapon (the bow) that blocks the Held-slot wand; else
// what is in the off hand (a shield, or an off-hand weapon): ACE refuses a Held-slot caster
// beside either. With the global Offhand setting None the off hand is never touched (the
// wand then can't be wielded; logged once).
private int FindWieldedNonWandWeapon(int wandId)
{
if (_worldObjectCache == null) return 0;
int offhand = 0;
foreach (var wo in _worldObjectCache.GetDirectInventory(forceRefresh: true))
{
if (wo.Id == wandId) continue;
if (IsWandObject(wo)) continue;
if (WorldObjectCache.IsAmmo(wo)) continue; // arrows stay on; only the bow blocks the wand
if (IsInOffhandSlot(wo)) { offhand = wo.Id; continue; }
if ((wo.ObjectClass == AcObjectClass.MeleeWeapon
|| wo.ObjectClass == AcObjectClass.MissileWeapon)
&& WorldObjectCache.IsWieldedByPlayer(_host, wo))
return wo.Id;
}
if (offhand != 0 && OffhandRules.Parse(_settings.OffhandDefault, OffhandMode.Auto) == OffhandMode.None)
{
if (!_offhandNoneNoted)
{
_offhandNoneNoted = true;
_host.Log($"[WieldGate] 0x{(uint)offhand:X8} '{_worldObjectCache[offhand]?.Name}' is in the off hand and Offhand is None — leaving it; the server won't wield the wand beside it");
}
return 0;
}
return offhand;
}
private static bool IsInOffhandSlot(WorldObject wo) =>
(wo.Values(LongValueKey.CurrentWieldedLocation, 0) & OffhandRules.ShieldSlot) != 0;
// Live (forceRefresh) wielded check — never trusts a stale cache snapshot.
private bool IsWieldedLive(int id)
{
@ -5445,6 +5332,306 @@ public partial class BuffManager : IDisposable
return false;
}
// ── The wand swap's steps (HandSwapSequence) ────────────────────────────
/// <summary>
/// The wand swap's next step. True once the wand is in hand (the caller then sees to the Magic
/// stance); false while a step is on its way, or when the swap stopped (_magicModeBlocked then
/// lets a vital's kit or potion go, and _wandSwapExhausted parks a buff).
/// </summary>
private bool WandSwapStep(int wandId, bool forBuff, DateTime now)
{
if (_wandSwap.Active && _wandSwapWandId != wandId)
FinishWandSwap(now, done: false, why: "another wand was chosen");
if (!_wandSwap.Active)
{
// Shared weapon-swap gate: one claim for the whole swap, held until it ends, so combat
// can't put a weapon back between its steps (two item actions in flight collide).
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("buff-wand"))
return false;
var start = ReadHands();
int off = HandAt(start, HandSwapSequence.ShieldSlot);
// With the global Offhand setting None the off hand is never touched, and the server won't
// wield a caster beside it: no swap, said once (the kit or potion gets its turn).
if (off != 0 && OffhandRules.Parse(_settings.OffhandDefault, OffhandMode.Auto) == OffhandMode.None)
{
if (!_offhandNoneNoted)
{
_offhandNoneNoted = true;
_host.Log($"[WieldGate] 0x{(uint)off:X8} '{ItemName(off)}' is in the off hand and Offhand is None — leaving it; the server won't wield the wand beside it");
}
return SignalSwapFailure(forBuff, 0, wandId);
}
// Tear down any in-flight physical combat BEFORE the first step: an item action while
// m_bAttacking is still set wedges the client's item-action gate.
if (!_combatTeardownDoneForCurrentBuffCycle &&
(CurrentCombatMode == CombatMode.Melee || CurrentCombatMode == CombatMode.Missile))
{
if (_host.HasCancelAttack) _host.CancelAttack();
if (_host.HasStopCompletely) _host.StopCompletelyBy("Buff/WandSwap");
_combatTeardownDoneForCurrentBuffCycle = true;
_host.Log($"[BuffPre] CancelAttack+StopCompletely before wand equip (mode was {CurrentCombatMode})");
}
// From a combat mode, peace first (HandSwapSequence: one stance leg, then every move is
// answered at once, and no stance change is ever queued behind another).
int mode0 = CurrentCombatMode;
_wandSwap.Start("wand", now, new[] { (wandId, (int)HeldSlot) },
peaceFirst: mode0 == CombatMode.Melee || mode0 == CombatMode.Missile);
_weaponSwapGate?.Hold("buff-wand", (long)_wandSwap.GiveUpMs + 1000);
_wandSwapOpen = true;
_wandSwapWandId = wandId;
_wandSwapForBuff = forBuff;
_wandSwapMainAtStart = MainHandIn(start, wandId);
_wandSwapLastMoved = 0;
_host.Log($"[WieldGate] switching to 0x{(uint)wandId:X8} '{ItemName(wandId)}' ({DescribeHands(start)}, mode {CurrentCombatMode})");
}
var hands = ReadHands();
var step = _wandSwap.Next(hands, CurrentCombatMode, now);
switch (step.Act)
{
case HandSwapSequence.Act.Wait:
return false;
case HandSwapSequence.Act.Stance:
{
// The burst (test toggle /ra swaptest burst on): peace, both hands and the wand in one frame.
int burst = SwapBurst ? TryWandBurst(hands, wandId, now) : 0;
if (burst != 0) return false;
// Refused while the server owes an answer or the character animates (ActionPacer): next tick.
if (_host.ChangeCombatModeFor(step.Slot, "Buff", "wand swap: peace first, then the hands"))
{
_wandSwap.Sent(step, now);
_host.Log($"[WieldGate] peace first {(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch (the moves are then answered at once)");
}
return false;
}
case HandSwapSequence.Act.MoveToPack:
{
int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: 1);
if (pack == 0)
{
WorldObjectCache.WarnPackFull(_host, "can't put the weapon away to switch to the wand, so buffs and spell heals can't cast");
return WandSwapFailed(_wandSwap.Abandon("no pack with room"), forBuff, wandId, now);
}
bool offhand = hands.TryGetValue(step.Id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0;
if (offhand) OffhandStowed?.Invoke(step.Id); // combat puts it back after
_host.MoveItemInternal((uint)step.Id, (uint)pack, 0, 1); // amount>=1 (engine rejects 0)
_wandSwap.Sent(step, now);
_wandSwapLastMoved = step.Id;
_host.Log($"[WieldGate] 0x{(uint)step.Id:X8} '{ItemName(step.Id)}' ({(offhand ? "off hand" : "main hand")}) -> pack 0x{(uint)pack:X8} " +
$"{(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch");
return false;
}
case HandSwapSequence.Act.Wield:
{
// GetAndWieldItem into the Held slot (the paperdoll drag). A use only wields a plain
// caster: one with a spell of its own (Electric Baton, Acid Staff) takes the use as
// "cast it" (Drakkon, 2026-10-18 14:00).
if (_host.HasWieldItem) _host.WieldItem((uint)step.Id, (uint)step.Slot);
else _host.UseFor((uint)step.Id, "Buff", "buffing: wield the wand");
_wandSwap.Sent(step, now);
_wandSwapLastMoved = step.Id;
NoteStanceRequest();
_pendingWieldId = step.Id;
_pendingWieldAt = now;
// No _lastCastAttempt here: the cast interval would hold the Magic request 400 ms (seen on
// Freya, 10-22 22:36); the first cast waits for the stance to settle anyway.
int mode = CurrentCombatMode;
_serverMagicDueUntil = mode == CombatMode.Melee || mode == CombatMode.Missile
? now.AddMilliseconds(ServerMagicWaitMs) : DateTime.MinValue;
_host.Log($"[WieldGate] wielding 0x{(uint)step.Id:X8} '{ItemName(step.Id)}' into the Held slot " +
$"{(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch");
return false;
}
case HandSwapSequence.Act.Done:
FinishWandSwap(now, done: true);
MagicAfterPeace(now);
return true;
default:
return WandSwapFailed(step, forBuff, wandId, now);
}
}
/// <summary>The swap stopped short: bounded retries, then the degrade (kits and potions for vitals, parked buffs).</summary>
private bool WandSwapFailed(HandSwapSequence.Step step, bool forBuff, int wandId, DateTime now)
{
int mainAtStart = _wandSwapMainAtStart;
bool wandUnanswered = _wandSwap.FailedId == wandId;
FinishWandSwap(now, done: false, why: step.Why);
if (step.Why == "no pack with room") return SignalSwapFailure(forBuff, mainAtStart, wandId);
if (wandUnanswered) NoteWandWieldFailed(wandId);
_pendingWieldId = 0;
_serverMagicDueUntil = DateTime.MinValue;
_wieldCooldownUntil = now.AddMilliseconds(WieldCooldownMs);
// A vital's kit or potion gets its turn now, not after the retries.
_magicModeBlocked = true;
if (++_wieldGateFailCount >= WieldGateFailMax)
return SignalSwapFailure(forBuff, mainAtStart, wandId);
return false;
}
/// <summary>The swap is over (<paramref name="done"/>: the wand is in hand): the gate is free again, and the log says how long it took.</summary>
private void FinishWandSwap(DateTime now, bool done, string why = "")
{
if (!_wandSwapOpen) return; // once per swap (a failed sequence has already stopped itself)
_wandSwapOpen = false;
double ms = (now - _wandSwap.StartedAt).TotalMilliseconds;
string trail = _wandSwap.Trail;
_magicAfterPeaceUntil = done && _wandSwap.WentThroughPeace ? now.AddMilliseconds(MagicAfterPeaceMs) : DateTime.MinValue;
_wandSwap.Cancel();
_weaponSwapGate?.Release("buff-wand", _wandSwapLastMoved);
LastWandSwapMs = ms;
LastWandSwapTrail = trail;
_host.Log(done
? $"[WieldGate] wand in hand {ms:0} ms after the switch began ({trail})"
: $"[WieldGate] the switch to the wand stopped after {ms:0} ms: {why} ({trail})");
}
/// <summary>
/// Each heartbeat, before the cast gates: a swap step the server has answered is followed at once
/// (the cast interval, a gesture or a busy count hold casts, not item moves), and a swap nothing
/// asks for any more (the heal or buff went away) stops, without counting as a failure.
/// </summary>
private void TickWandSwap()
{
if (!_wandSwap.Active) return;
DateTime now = Now;
if ((now - _wandSwapTouchedAt).TotalMilliseconds > WandSwapAbandonMs)
{
FinishWandSwap(now, done: false, why: "nothing needs the wand now");
return;
}
WandSwapStep(_wandSwapWandId, _wandSwapForBuff, now);
}
/// <summary>A death, a portal or the macro stopping ended the swap: not a failed swap.</summary>
private void DropWandSwap(string why)
{
if (!_wandSwap.Active) return;
FinishWandSwap(Now, done: false, why: why);
_pendingWieldId = 0;
_serverMagicDueUntil = DateTime.MinValue;
}
/// <summary>What the server says is wielded (item id -> EquipMask), read fresh.</summary>
private Dictionary<int, int> ReadHands() => EquippedState.ReadFresh(_host, _worldObjectCache);
/// <summary>
/// The burst: peace, the moves out of the hands (raw PutItemInContainer, which the client doesn't
/// gate on a pending item request) and the wand's wield, queued in one tick so they go out in one
/// frame, before the client starts the peace animation that holds item actions (0.6 s a step on
/// the step route). In peace the server answers every one at once. Only when the server can't be
/// mid-animation: no combat-mode change for BurstQuietMs (ACE NextUseTime is set by stance changes,
/// uses and kits; the pacer refuses the peace request while a use is unanswered). Anything that
/// hasn't landed in HandSwapSequence.BurstResolveMs goes on one step at a time.
/// 0 = not tried (the step route), 1 = held this tick, 2 = sent.
/// </summary>
private int TryWandBurst(IReadOnlyDictionary<int, int> hands, int wandId, DateTime now)
{
if (!_host.HasPutItemInContainer || !_host.HasWieldItem) return 0;
if ((now - _modeChangedAt).TotalMilliseconds < BurstQuietMs) return 0;
var moves = _wandSwap.Blockers(hands);
if (moves.Count == 0 || moves.Count > 2) return 0;
int pack = WorldObjectCache.FindPackFor(_host, _worldObjectCache, includeMainPack: true, requireFree: moves.Count);
if (pack == 0) return 0;
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "wand swap burst: peace, the hands and the wand at once")) return 1;
foreach (int id in moves)
{
if (hands.TryGetValue(id, out int slot) && (slot & HandSwapSequence.ShieldSlot) != 0) OffhandStowed?.Invoke(id);
_host.PutItemInContainer(unchecked((uint)id), unchecked((uint)pack), 0);
}
_host.WieldItem(unchecked((uint)wandId), HeldSlot);
_wandSwap.SentBurst(moves, now);
_wandSwapLastMoved = wandId;
NoteStanceRequest();
_pendingWieldId = wandId;
_pendingWieldAt = now;
_host.Log($"[WieldGate] burst {(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch: peace, " +
string.Join(", ", moves.ConvertAll(id => $"0x{(uint)id:X8} '{ItemName(id)}'")) +
$" -> pack 0x{(uint)pack:X8}, 0x{(uint)wandId:X8} '{ItemName(wandId)}' -> Held, in one frame");
return 2;
}
/// <summary>
/// The burst goes with Fast Weapon Swap (when the server is quiet; else the step route). /ra swaptest
/// burst on|off overrides it until the next reload, to compare the two routes.
/// </summary>
internal bool SwapBurst { get => _swapBurstOverride ?? _settings.FastWeaponSwap; set => _swapBurstOverride = value; }
private bool? _swapBurstOverride;
private const double BurstQuietMs = 1300;
private int _lastSeenMode = -1;
private DateTime _modeChangedAt = DateTime.MinValue;
/// <summary>When the combat mode last changed, read every heartbeat (combat's tick doesn't run while buffing has it).</summary>
internal DateTime LastModeChangeAt => _modeChangedAt;
/// <summary>Each heartbeat: when the combat mode last changed (the burst waits out a stance change's animation).</summary>
private void NoteModeChange()
{
int m = CurrentCombatMode;
if (m == _lastSeenMode) return;
bool first = _lastSeenMode == -1; // the first read after a load is not a change
_lastSeenMode = m;
if (!first) _modeChangedAt = Now;
}
/// <summary>
/// The wand is in hand after a swap through peace: Magic is asked for now, from the swap itself (it
/// can run before the cast gates, which the pacer holds while our own peace request settles: 0.75 s
/// on Freya, 10-22 22:49). The server holds the change until the peace animation ends by itself.
/// The same bookkeeping as the Magic request in EnsureMagicMode, which won't send it twice.
/// </summary>
private void MagicAfterPeace(DateTime now)
{
if (now >= _magicAfterPeaceUntil || CurrentCombatMode != CombatMode.NonCombat || !OnlyOurPeaceRequestPending()) return;
if (!_host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand in hand after peace: Magic mode", force: true)) return;
if (_buffStanceStuckSince == DateTime.MinValue) { _buffStanceStuckSince = now; _buffStanceStuckStartMs = ActionPacer.NowMs(); }
NoteStanceRequest();
_lastBuffStanceAttempt = now;
_lastCastAttempt = now;
if (_buffStanceConsecutiveFails < 6) _buffStanceConsecutiveFails++;
_host.Log($"[WieldGate] Magic asked for {(now - _wandSwap.StartedAt).TotalMilliseconds:0} ms into the switch (the server starts it when the peace animation ends)");
}
/// <summary>Nothing the pacer waits on but our own request for peace (or nothing at all).</summary>
private bool OnlyOurPeaceRequestPending()
{
var a = ActionPacer.Current(_host);
return a == null || (a.Kind == PacedKind.CombatMode && a.ModeTarget == CombatMode.NonCombat && a.Who == "Buff");
}
private static int HandAt(IReadOnlyDictionary<int, int> hands, int slot)
{
foreach (var kv in hands) if ((kv.Value & slot) != 0) return kv.Key;
return 0;
}
/// <summary>The weapon in the main hand (not the wand being wielded, not the off hand); 0 = none.</summary>
private static int MainHandIn(IReadOnlyDictionary<int, int> hands, int wandId)
{
const int main = HandSwapSequence.MeleeSlot | HandSwapSequence.MissileSlot | HandSwapSequence.TwoHandedSlot | HandSwapSequence.HeldSlot;
foreach (var kv in hands) if (kv.Key != wandId && (kv.Value & main) != 0) return kv.Key;
return 0;
}
private string DescribeHands(IReadOnlyDictionary<int, int> hands)
{
var parts = new List<string>();
foreach (var kv in hands)
{
if ((kv.Value & HandSwapSequence.HandSlots) == 0) continue;
string where = (kv.Value & HandSwapSequence.ShieldSlot) != 0 ? "off hand" : "main hand";
parts.Add($"{where} 0x{(uint)kv.Key:X8} '{ItemName(kv.Key)}'");
}
return parts.Count == 0 ? "hands empty" : string.Join(", ", parts);
}
private string ItemName(int id) => _worldObjectCache?[id]?.Name ?? "?";
/// <summary>
/// Locates a wand to equip: a listed wand, the one already in hand first (so buffing
/// doesn't swap one listed wand for another). The pack is searched only when the Items list

View file

@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Fast Weapon Swap, combat's own equip (2026-10-23): a monster to fight with a caster still in hand
/// (it came while healing). Before, combat used the main weapon (the client's own swap): the wand went
/// into the pack after a forced stance change in Magic mode (about 1.2 s), the main weapon landed at
/// about 1.4 s and the off hand at 1.7 s (Drakkon, 10-22 night, about half his swaps back). Now the same
/// hands swap as weapons back after heals (HandSwapSequence): peace, the wand out, the main weapon and
/// the off hand on (one frame when the server is quiet), then the fight's stance at once.
///
/// A weapons-back swap under way when the target comes goes on, pointed at the fight's weapons when they
/// differ; a fight with the wand ends it. A failed fight swap leaves that weapon to the client's own swap
/// for <see cref="FightSwapFallbackSec"/>. Setting off: none of this runs.
/// </summary>
public partial class CombatManager
{
// The hands swap (_rearmSwap) is for the fight's weapons, not weapons back after heals.
private bool _handsSwapForFight;
private int _handsSwapFightMode;
private string _handsGateBy = "rearm-after-vitals";
// The stance owed after the swap is the fight's (asked for with a target, PeaceModeWhenIdle or not).
private bool _rearmStanceForFight;
// A fight swap that failed: the client's own swap for that weapon for a while.
private int _fightSwapFallbackFor;
private DateTime _fightSwapFallbackUntil = DateTime.MinValue;
private const double FightSwapFallbackSec = 20;
private string HandsSwapLabel => _handsSwapForFight ? "weapons for the fight" : "weapons back";
/// <summary>
/// The fight's main weapon and the off hand to go with it: the planned one, else what is in the off
/// hand already when it may stay (a hands swap takes off everything it doesn't want).
/// </summary>
private List<(int Id, int Slot)> FightWants(WorldObject target, MonsterRule? rule, int mainId)
{
var wants = new List<(int Id, int Slot)> { (mainId, MainSlotFor(mainId)) };
int off = OffhandPlanFor(target, rule, mainId).Id;
if (off != 0 && off != mainId && _worldFilter[off] is WorldObject offWo && (_host.HasWieldItem || IsShieldItem(offWo)))
{
wants.Add((off, HandSwapSequence.ShieldSlot));
return wants;
}
int inOff = OffhandInSlot(fresh: true);
if (inOff != 0 && inOff != mainId && _worldFilter[inOff] is WorldObject inOffWo
&& OffhandRules.OffhandAllowed(MainKindOf(_worldFilter[mainId]), IsShieldItem(inOffWo)))
wants.Add((inOff, HandSwapSequence.ShieldSlot));
return wants;
}
private static bool SameWants(IReadOnlyList<(int Id, int Slot)> a, IReadOnlyList<(int Id, int Slot)> b)
{
if (a.Count != b.Count) return false;
for (int i = 0; i < a.Count; i++)
if (a[i] != b[i]) return false;
return true;
}
/// <summary>
/// A caster in hand and <paramref name="mainId"/> (melee or a launcher) wanted: start the hands swap.
/// True = started, or waiting to (the gate, ammo going into the pack); false = the old route this tick.
/// </summary>
private bool TryStartFightHandsSwap(WorldObject target, MonsterRule? rule, int mainId, int desiredMode)
{
DateTime now = RynthClock.Now;
if (_fightSwapFallbackFor == mainId && now < _fightSwapFallbackUntil) return false;
if (!_host.HasMoveItemInternal) return false;
if (desiredMode == CombatMode.Missile)
{
var prep = PrepareAmmoFor(mainId); // the wrong ammo into the pack first; arms the ammo follow-up
if (prep == AmmoPrep.Busy) return true;
if (prep == AmmoPrep.Blocked) return false;
}
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("combat-hands-swap")) return true;
StartHandsSwapForFight(now, FightWants(target, rule, mainId), desiredMode, target);
RearmSwapAdvance(now);
return true;
}
private void StartHandsSwapForFight(DateTime now, List<(int Id, int Slot)> wants, int desiredMode, WorldObject target)
{
int mode = CurrentCombatMode;
_rearmWants = wants;
_rearmSwap.Start("weapons for the fight", now, wants, peaceFirst: mode != CombatMode.NonCombat);
_handsSwapForFight = true;
_handsSwapFightMode = desiredMode;
_handsGateBy = "combat-hands-swap";
_weaponSwapGate?.Hold(_handsGateBy, (long)_rearmSwap.GiveUpMs + 1000);
_rearmSwapOpen = true;
_rearmLastMoved = 0;
_rearmStanceWanted = 0;
_host.Log($"[EquipDiag] weapons for the fight ('{target.Name}'): " +
string.Join(" + ", wants.Select(w => $"0x{(uint)w.Id:X8} '{WeaponName(w.Id)}'{(w.Slot == HandSwapSequence.ShieldSlot ? " (off hand)" : "")}")) +
$" (mode {mode})");
}
/// <summary>
/// A hands swap is under way and combat has a target: true = wait for it (it goes on, now with the
/// fight's weapons); false = it ended (the fight wants a caster, or another launcher) and combat's
/// own equip goes on this tick.
/// </summary>
private bool FightJoinsHandsSwap(WorldObject target, MonsterRule? rule, int mainId, WorldObject mainObj)
{
DateTime now = RynthClock.Now;
bool wasFight = _handsSwapForFight;
if (IsWandObject(mainObj))
{
FinishRearmSwap(now, done: false, why: $"'{target.Name}' is fought with the wand");
if (!wasFight) _rearmedFor = _rearmVital;
return false;
}
_curOffhandMode = OffhandChoiceFor(target, rule).Mode;
var wants = FightWants(target, rule, mainId);
int mode = WeaponKind(mainId);
if (SameWants(_rearmSwap.Wants, wants))
{
if (!wasFight) _host.Log($"[EquipDiag] weapons back: the same weapons for '{target.Name}', going on");
_handsSwapForFight = true;
_handsSwapFightMode = mode;
return true;
}
if (_rearmSwap.InFlight) return true; // the step on its way lands first, then the new weapons
if (mode == CombatMode.Missile)
{
// A launcher needs its ammo seen to first: combat's own launcher swap does that.
FinishRearmSwap(now, done: false, why: $"a launcher for '{target.Name}'");
if (!wasFight) _rearmedFor = _rearmVital;
return false;
}
_host.Log($"[EquipDiag] {HandsSwapLabel}: other weapons for '{target.Name}' ({_rearmSwap.Trail})");
StartHandsSwapForFight(now, wants, mode, target);
RearmSwapAdvance(now);
return true;
}
/// <summary>Everything the fight wants is in hand: its stance at once (past our own peace request).</summary>
private void FightSwapDone(DateTime now)
{
int main = _rearmWants.Count > 0 ? _rearmWants[0].Id : 0;
int mode = _handsSwapFightMode;
if (main != 0) SwapTracker.Confirmed(main, now);
_inHandReadAt = DateTime.MinValue; // read the hands fresh next tick
_offSlotReadAt = DateTime.MinValue;
// A launcher: only with fitting ammo on; otherwise the wielded branch puts it on, then asks.
bool ammoReady = mode != CombatMode.Missile || (HasWieldedAmmo() && !LauncherSwapHoldsStance(main));
_rearmStanceWanted = mode != 0 && mode != CombatMode.Magic && CurrentCombatMode != mode && ammoReady ? mode : 0;
_rearmStanceSince = now;
_rearmStanceForFight = true;
FinishRearmSwap(now, done: true);
RearmStanceStep(now);
}
/// <summary>The fight swap stopped: the client's own swap for that weapon for a while.</summary>
private void NoteFightSwapFailed(DateTime now, bool counted = true)
{
if (!counted) return;
int main = _rearmWants.Count > 0 ? _rearmWants[0].Id : 0;
if (main == 0) return;
_fightSwapFallbackFor = main;
_fightSwapFallbackUntil = now.AddSeconds(FightSwapFallbackSec);
_host.Log($"[EquipDiag] weapons for the fight: the client's own swap for 0x{(uint)main:X8} '{WeaponName(main)}' for {FightSwapFallbackSec:0} s");
}
}

View file

@ -0,0 +1,65 @@
using System;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
using System.Linq;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Weapons Back After Heals as it was before 2026-10-22 (RynthSuite e613280), kept for Fast Weapon
/// Swap off: a use of the main weapon (the client puts the wand away), then the off hand once the
/// swap gate lets it go. Fast Weapon Swap on goes through HandSwapSequence (RearmAfterVitalsStep).
/// </summary>
public partial class CombatManager
{
private bool LegacyRearmSwap(DateTime now, DateTime vital)
{
int inHand = InHandWeaponId();
if (inHand != _fightMainId)
{
if (SwapTracker.PendingId != 0) { FoldServerAnswer(SwapTracker, now); return true; } // our wield is on its way
var step = SwapStep(_fightMainId, inHand);
if (step == WeaponSwapTracker.Step.Wait) return true;
if (step != WeaponSwapTracker.Step.Swap) { _rearmedFor = vital; return false; }
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("rearm-after-vitals")) return true;
var prep = ClearOffhandFor(_fightMainId, OffhandMode.Auto, gateHeld: true);
if (prep == OffPrep.Busy) return true;
if (prep == OffPrep.Blocked) { _rearmedFor = vital; return false; }
SendWield(_fightMainId, inHand, "weapons back after heals");
return true;
}
int off = OffhandInSlot();
if (_fightOffId != 0 && off != _fightOffId && _fightOffId != _fightMainId
&& _worldFilter.PlayerHas(_fightOffId) != false && _settings.ItemRules.Any(r => r.Id == _fightOffId))
{
FoldServerAnswer(OffhandTracker, now);
if (OffhandTracker.PendingId != 0) return true;
if (off != 0) { DequipOffhand(off, $"to put 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}' back"); return true; }
var wo = _worldFilter[_fightOffId];
if (wo != null && _host.HasWieldItem && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("rearm-after-vitals-offhand")))
{
var stepOff = OffhandTracker.Next(_fightOffId, off, now, WeaponName);
if (stepOff == WeaponSwapTracker.Step.Swap && _host.WieldItem(unchecked((uint)_fightOffId), OffhandRules.ShieldSlot))
{
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
OffhandTracker.Sent(_fightOffId, 0, now);
_weaponSwapGate?.NoteMove(_fightOffId, wieldedNow: false);
_offhandSentId = _fightOffId;
_lastEquipTime = now;
_host.Log($"[EquipDiag] weapons back after heals: off hand 0x{(uint)_fightOffId:X8} '{wo.Name}'");
return true;
}
if (stepOff == WeaponSwapTracker.Step.Wait) return true;
}
_rearmedFor = vital; // the off hand can't go on now: the main hand is back, that will do
return false;
}
_rearmedFor = vital;
_host.Log($"[EquipDiag] weapons back after heals: 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}'" +
(_fightOffId != 0 ? $" and 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}'" : "") + " in hand");
return false;
}
}

View file

@ -4097,6 +4097,8 @@ public partial class CombatManager : IDisposable
public void OnHeartbeat()
{
NoteSwapPortal();
// The hands swap's steps (weapons back, or the fight's weapons) go before the gates; the macro stopping ends it (freeing the gate).
TickRearmSwap();
if (!_settings.IsMacroRunning)
{
@ -4481,7 +4483,8 @@ public partial class CombatManager : IDisposable
/// <summary>
/// The weapon to fight <paramref name="target"/> with (0 = none), and the element in
/// <paramref name="desired"/>. See WeaponPlanner for the order: this monster's Damage tab
/// weapon (listed only), a slayer of the monster, the Damage tab DEFAULT row's weapon, the
/// weapon, else its Monsters rule's weapon (listed or not), a slayer of the monster, the Damage
/// tab DEFAULT row's weapon, else the Monsters Default row's, the
/// Monsters rule's damage type, the weakness (weakest element a listed
/// weapon of the main kind has), else the weapon in hand, the learned best, the first.
/// Casters are skipped when the character has no War/Void Magic (IsUsableCombatWeapon).
@ -4495,10 +4498,11 @@ public partial class CombatManager : IDisposable
}
/// <summary>
/// The weapon and element for <paramref name="target"/> (WeaponPlanner's rule). Only weapons
/// in the Items list are candidates: a Damage-tab pick or a learned "best" weapon that is no
/// The weapon and element for <paramref name="target"/> (WeaponPlanner's rule). The candidates
/// are the Items list's weapons: a Damage-tab pick or a learned "best" weapon that is no
/// longer listed is ignored (logged once), which is how an unlisted fire wand used to be
/// wielded after the user removed it from the list (2026-09-30).
/// wielded after the user removed it from the list (2026-09-30). The one exception is a
/// weapon set on the Monsters tab, used listed or not (2026-10-22).
/// </summary>
internal WeaponPlan PlanFor(WorldObject target, MonsterRule? rule)
{
@ -4537,18 +4541,59 @@ public partial class CombatManager : IDisposable
uint wcid = 0;
if (_host.HasGetObjectWcid && _host.TryGetObjectWcid((uint)target.Id, out uint tw)) wcid = tw;
// The weapon the player fixed, the first usable of (owner's rule, 2026-10-22, problem report
// R-20261022-193411-fb72 "ignoring monster rules, specifically which weapon is set for the
// mob type": a Monsters rule's weapon was imported, shown and kept from trade/sell, but
// combat never read it, so the weakness pick wielded something else):
// 1. this monster's own Damage tab pick (by wcid) - WeaponPlanner step 1
// 2. the matched Monsters rule's weapon (not the Default row) - step 1
// 3. the Damage tab DEFAULT row's weapon - step 3 (a slayer beats it)
// 4. the Monsters tab Default row's weapon - step 3
// Only 1 needs the wcid: a rule weapon still applies to a monster whose wcid isn't known.
// One the character can't wield now (a requirement, or refused) is left out quietly, it is
// logged where the list drops it. A Damage tab pick must be in the Items list (an unlisted
// fire wand was wielded that way, 2026-09-30); one that isn't is logged once. A Monsters tab
// weapon (2 and 4) need not be (owner, 2026-10-22: "if it is in the monsters tab but not
// item list it should still use it"): it joins the candidates when carried and usable.
// Either way, when one can't be used the next is tried. A listed weapon for another build
// stays listed.
int fixedId = 0, learnedId = 0;
string fixedSource = "Damage tab";
bool fixedIsDefault = false;
var defaultRule = DefaultMonsterRule();
bool ownRule = rule != null && !ReferenceEquals(rule, defaultRule)
&& !rule.Name.Equals("Default", StringComparison.OrdinalIgnoreCase);
bool TryFixed(int id, string source, string noteAs, bool isDefault, bool listOnly)
{
if (fixedId != 0 || id == 0 || !CanWieldNow(id)) return false;
if (!listed.Any(c => c.Id == id))
{
if (listOnly) { NoteUnlisted(id, noteAs); return false; }
var extra = CandidateFor(id, null, InHandWeaponId(), admitCasters: false, noteAs + " weapon", out bool caster);
if (extra == null)
{
if (caster && _unlistedNoted.Add(id))
_host.Log($"[EquipDiag] {noteAs} weapon 0x{(uint)id:X8} '{WeaponName(id)}' is a caster and the character can't fight with magic: {CanMagicDiag()}");
return false;
}
if (_unlistedNoted.Add(id))
_host.Log($"[EquipDiag] {noteAs} weapon 0x{(uint)id:X8} '{extra.Name}' isn't in the Items list — using it (set on the Monsters tab)");
listed.Add(extra);
}
fixedId = id; fixedSource = source; fixedIsDefault = isDefault;
return true;
}
if (wcid != 0 && _damageStore != null)
TryFixed((int)_damageStore.GetManualWeapon(wcid), "Damage tab", "Damage tab", false, listOnly: true);
if (ownRule)
TryFixed(rule!.WeaponId, "Monsters rule weapon", $"Monsters rule '{rule.Name}'", false, listOnly: false);
if (_damageStore != null)
TryFixed((int)_damageStore.GetDefaultWeapon(), "Damage tab default", "Damage tab default", true, listOnly: true);
if (defaultRule != null)
TryFixed(defaultRule.WeaponId, "Monsters Default weapon", "Monsters Default row", true, listOnly: false);
if (wcid != 0 && _damageStore != null)
{
uint pick = _damageStore.GetManualWeapon(wcid);
if (pick == 0) { pick = _damageStore.GetDefaultWeapon(); fixedSource = "Damage tab default"; fixedIsDefault = true; }
// Not usable by this character right now (a requirement, or refused): left out quietly, it
// is logged where the list drops it. A listed weapon for another build stays listed.
if (pick != 0 && !CanWieldNow((int)pick)) pick = 0;
if (pick != 0 && !listed.Any(c => c.Id == (int)pick)) { NoteUnlisted((int)pick, fixedSource); pick = 0; }
fixedId = (int)pick;
uint best = _damageStore.GetBestWeapon(wcid);
if (best != 0 && !CanWieldNow((int)best)) best = 0;
if (best != 0 && !listed.Any(c => c.Id == (int)best)) { NoteUnlisted((int)best, "Damage tab learned"); best = 0; }
@ -4684,49 +4729,69 @@ public partial class CombatManager : IDisposable
var list = new List<WeaponCandidate>();
foreach (var r in _settings.ItemRules)
{
if (r.Id == 0) continue;
var wo = _worldFilter[r.Id];
if (wo == null) continue;
// Sold, dropped or traded: still known to the client, but not ours to wield (a sold
// Flaming Greataxe was tried three times, the character standing in the fight, 2026-10-14).
if (r.Id != inHand && _worldFilter.PlayerHas(r.Id) == false)
{
// Not within NotCarriedGraceMs of a wield or move of ours: mid-swap a weapon is
// briefly in neither hand nor the pack walk. Drakkon's Acid Hand Wraps were dropped
// from the choice that way on 2026-10-17 and he fought bare-handed.
if ((RynthClock.Now - _lastEquipTime).TotalMilliseconds >= NotCarriedGraceMs)
{
if (_notCarriedNoted.Add(r.Id))
_host.Log($"[EquipDiag] listed weapon 0x{(uint)r.Id:X8} '{wo.Name}' isn't in your pack (sold, dropped or traded?): skipped");
continue;
}
}
else _notCarriedNoted.Remove(r.Id);
if (!admitCasters && !IsUsableCombatWeapon(r.Id)) { (leftOut ??= new List<int>()).Add(r.Id); continue; }
if (r.Id != inHand && SkillTooLowFor(r.Id)) continue;
// A wield requirement the character doesn't meet: the client refuses the wield without
// asking the server, so no "skill too low" answer ever comes (the Tetsubo, 2026-10-18).
if (r.Id != inHand && WieldRequirements.Unmet(_host, _charSkills, unchecked((uint)r.Id)) is string unmet)
{
if (_wieldReqNoted.Add(r.Id))
{
_host.Log($"[EquipDiag] listed weapon 0x{(uint)r.Id:X8} '{wo.Name}' can't be wielded ({unmet}): left out of the weapon choice");
_host.WriteToChat($"[RynthAi] {wo.Name} can't be wielded ({unmet}), so combat doesn't use it.", 1);
}
continue;
}
if (list.Any(c => c.Id == r.Id)) continue;
if (wo.ObjectClass == AcObjectClass.MissileWeapon && IsAmmoItem(wo)) continue; // listed arrows are the ammo choice, never a weapon to wield
if (IsShieldItem(wo)) continue; // listed shields are the off hand's (CombatManager.Offhand.cs)
var info = ElementTracker.Read(r.Id, wo.Name);
string elem = WeaponElements.Normalize(r.Element);
if (elem.Length == 0) elem = info.Element;
var (slayType, slayBonus) = SlayerOf(r.Id);
list.Add(new WeaponCandidate(r.Id, wo.Name, WeaponKind(r.Id), elem, info.Rending, r.Id == inHand, slayType, slayBonus));
if (r.Id == 0 || list.Any(c => c.Id == r.Id)) continue;
var c = CandidateFor(r.Id, r.Element, inHand, admitCasters, "listed weapon", out bool casterLeftOut);
if (casterLeftOut) (leftOut ??= new List<int>()).Add(r.Id);
if (c != null) list.Add(c);
}
return list;
}
/// <summary>
/// One weapon as a candidate for the weapon choice, or null when it isn't one now: not known,
/// not carried, a caster the character can't fight with (<paramref name="casterLeftOut"/>),
/// a requirement not met, ammo or a shield. <paramref name="what"/> names it in the log
/// ("listed weapon", "Monsters rule 'X' weapon").
/// </summary>
private WeaponCandidate? CandidateFor(int id, string? setElement, int inHand, bool admitCasters, string what, out bool casterLeftOut)
{
casterLeftOut = false;
var wo = _worldFilter[id];
if (wo == null) return null;
// Sold, dropped or traded: still known to the client, but not ours to wield (a sold
// Flaming Greataxe was tried three times, the character standing in the fight, 2026-10-14).
if (id != inHand && _worldFilter.PlayerHas(id) == false)
{
// Not within NotCarriedGraceMs of a wield or move of ours: mid-swap a weapon is
// briefly in neither hand nor the pack walk. Drakkon's Acid Hand Wraps were dropped
// from the choice that way on 2026-10-17 and he fought bare-handed.
if ((RynthClock.Now - _lastEquipTime).TotalMilliseconds >= NotCarriedGraceMs)
{
if (_notCarriedNoted.Add(id))
_host.Log($"[EquipDiag] {what} 0x{(uint)id:X8} '{wo.Name}' isn't in your pack (sold, dropped or traded?): skipped");
return null;
}
}
else _notCarriedNoted.Remove(id);
if (!admitCasters && !IsUsableCombatWeapon(id)) { casterLeftOut = true; return null; }
if (id != inHand && SkillTooLowFor(id)) return null;
// A wield requirement the character doesn't meet: the client refuses the wield without
// asking the server, so no "skill too low" answer ever comes (the Tetsubo, 2026-10-18).
if (id != inHand && WieldRequirements.Unmet(_host, _charSkills, unchecked((uint)id)) is string unmet)
{
if (_wieldReqNoted.Add(id))
{
_host.Log($"[EquipDiag] {what} 0x{(uint)id:X8} '{wo.Name}' can't be wielded ({unmet}): left out of the weapon choice");
_host.WriteToChat($"[RynthAi] {wo.Name} can't be wielded ({unmet}), so combat doesn't use it.", 1);
}
return null;
}
if (wo.ObjectClass == AcObjectClass.MissileWeapon && IsAmmoItem(wo)) return null; // listed arrows are the ammo choice, never a weapon to wield
if (IsShieldItem(wo)) return null; // listed shields are the off hand's (CombatManager.Offhand.cs)
var info = ElementTracker.Read(id, wo.Name);
string elem = WeaponElements.Normalize(setElement);
if (elem.Length == 0) elem = info.Element;
var (slayType, slayBonus) = SlayerOf(id);
return new WeaponCandidate(id, wo.Name, WeaponKind(id), elem, info.Rending, id == inHand, slayType, slayBonus);
}
/// <summary>
/// A weapon the player picked on the Monsters tab (any rule's, the Default row's included).
/// It is theirs to fight with even when it isn't in the Items list (owner, 2026-10-22).
/// </summary>
internal bool IsMonstersTabWeapon(int id) =>
id != 0 && _settings.MonsterRules.Exists(m => m.WeaponId == id);
// The weapon in hand, read live at most every InHandReadMs (the read walks the inventory).
private int _inHandId;
private DateTime _inHandReadAt = DateTime.MinValue;
@ -4835,62 +4900,286 @@ public partial class CombatManager : IDisposable
_host.Log($"[EquipDiag] weapons back after heals: gave up after {RearmGiveUpMs / 1000:0} s (main 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}', off hand 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}')");
return false;
}
// Still ours to wield: listed, carried, not refused for skill.
if (!_settings.ItemRules.Any(r => r.Id == _fightMainId) || _worldFilter.PlayerHas(_fightMainId) == false || SkillTooLowFor(_fightMainId))
// Still ours to wield: listed (or set on the Monsters tab), carried, not refused for skill.
if (!(_settings.ItemRules.Any(r => r.Id == _fightMainId) || IsMonstersTabWeapon(_fightMainId))
|| _worldFilter.PlayerHas(_fightMainId) == false || SkillTooLowFor(_fightMainId))
{
_rearmedFor = vital;
return false;
}
int inHand = InHandWeaponId();
if (inHand != _fightMainId)
{
if (SwapTracker.PendingId != 0) { FoldServerAnswer(SwapTracker, now); return true; } // our wield is on its way
var step = SwapStep(_fightMainId, inHand);
if (step == WeaponSwapTracker.Step.Wait) return true;
if (step != WeaponSwapTracker.Step.Swap) { _rearmedFor = vital; return false; }
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("rearm-after-vitals")) return true;
var prep = ClearOffhandFor(_fightMainId, OffhandMode.Auto, gateHeld: true);
if (prep == OffPrep.Busy) return true;
if (prep == OffPrep.Blocked) { _rearmedFor = vital; return false; }
SendWield(_fightMainId, inHand, "weapons back after heals");
return true;
}
// Fast Weapon Swap off: as before 2026-10-22 (CombatManager.LegacySwap.cs).
if (!_settings.FastWeaponSwap) return LegacyRearmSwap(now, vital);
var hands = EquippedState.ReadFresh(_host, _worldFilter);
bool offWanted = _fightOffId != 0 && _fightOffId != _fightMainId
&& _worldFilter.PlayerHas(_fightOffId) != false && _settings.ItemRules.Any(r => r.Id == _fightOffId);
const int mainHand = HandSwapSequence.HandSlots & ~HandSwapSequence.ShieldSlot;
bool mainIn = hands.TryGetValue(_fightMainId, out int mainAt) && (mainAt & mainHand) != 0;
bool offIn = !offWanted || (hands.TryGetValue(_fightOffId, out int offAt) && (offAt & HandSwapSequence.ShieldSlot) != 0);
int off = OffhandInSlot();
if (_fightOffId != 0 && off != _fightOffId && _fightOffId != _fightMainId
&& _worldFilter.PlayerHas(_fightOffId) != false && _settings.ItemRules.Any(r => r.Id == _fightOffId))
// The weapons are back: the fight's stance, once, when the swap went through peace (a weapon
// wielded in a combat mode is put into its stance by the server itself; in peace it isn't).
if (!_rearmSwap.Active && mainIn && offIn)
{
FoldServerAnswer(OffhandTracker, now);
if (OffhandTracker.PendingId != 0) return true;
if (off != 0) { DequipOffhand(off, $"to put 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}' back"); return true; }
var wo = _worldFilter[_fightOffId];
if (wo != null && _host.HasWieldItem && (_weaponSwapGate == null || _weaponSwapGate.TryBeginSwap("rearm-after-vitals-offhand")))
{
var stepOff = OffhandTracker.Next(_fightOffId, off, now, WeaponName);
if (stepOff == WeaponSwapTracker.Step.Swap && _host.WieldItem(unchecked((uint)_fightOffId), OffhandRules.ShieldSlot))
{
if (_host.HasGetLastUseDone && _host.TryGetLastUseDone(out int uSeq, out _)) _swapUseDoneSeq = uSeq;
if (_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int wSeq, out _, out _, out _)) _swapWeenieSeq = wSeq;
OffhandTracker.Sent(_fightOffId, 0, now);
_weaponSwapGate?.NoteMove(_fightOffId, wieldedNow: false);
_offhandSentId = _fightOffId;
_lastEquipTime = now;
_host.Log($"[EquipDiag] weapons back after heals: off hand 0x{(uint)_fightOffId:X8} '{wo.Name}'");
return true;
}
if (stepOff == WeaponSwapTracker.Step.Wait) return true;
}
_rearmedFor = vital; // the off hand can't go on now: the main hand is back, that will do
if (_rearmStanceWanted != 0 && !RearmStanceStep(now)) return true; // held a moment (the pacer): next tick
_rearmedFor = vital;
_host.Log($"[EquipDiag] weapons back after heals: 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}'" +
(offWanted ? $" and 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}'" : "") + " in hand");
return false;
}
_rearmedFor = vital;
_host.Log($"[EquipDiag] weapons back after heals: 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}'" +
(_fightOffId != 0 ? $" and 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}'" : "") + " in hand");
return false;
// Weapons back as fast as the server allows (2026-10-22, HandSwapSequence): from Magic, peace
// first (one stance leg), the wand into a pack, the main weapon and the off hand, each the moment
// the server answers the last, then the fight's stance. Drakkon's Sceptre -> two Hand Wraps took
// 2.3 s: the use of the main weapon (the client puts the wand away after a forced stance change,
// 1.2 s), then the off hand once the gate let it go (a corpse open went first). The gate is held
// for the whole swap, so nothing else swaps between its steps.
if (!_rearmSwap.Active)
{
if (_weaponSwapGate != null && !_weaponSwapGate.TryBeginSwap("rearm-after-vitals")) return true;
var wants = new List<(int Id, int Slot)> { (_fightMainId, MainSlotFor(_fightMainId)) };
if (offWanted) wants.Add((_fightOffId, HandSwapSequence.ShieldSlot));
_rearmWants = wants;
int mode = CurrentCombatMode;
_rearmSwap.Start("weapons back", now, wants, peaceFirst: mode != CombatMode.NonCombat);
_handsSwapForFight = false;
_handsGateBy = "rearm-after-vitals";
_weaponSwapGate?.Hold(_handsGateBy, (long)_rearmSwap.GiveUpMs + 1000);
_rearmSwapOpen = true;
_rearmLastMoved = 0;
_host.Log($"[EquipDiag] weapons back after heals: 0x{(uint)_fightMainId:X8} '{WeaponName(_fightMainId)}'" +
(offWanted ? $" + off hand 0x{(uint)_fightOffId:X8} '{WeaponName(_fightOffId)}'" : "") + $" (mode {mode})");
}
_rearmVital = vital;
return RearmSwapAdvance(now);
}
/// <summary>
/// The weapons-back swap's next step. Called from RearmAfterVitalsStep and, so the steps don't wait
/// on the combat tick's gates (the pacer holds them while our own peace request settles, and a
/// corpse open slipped in between on Drakkon, 10-22 22:45), from the top of each heartbeat.
/// True while it is under way.
/// </summary>
private bool RearmSwapAdvance(DateTime now)
{
var hands = EquippedState.ReadFresh(_host, _worldFilter);
var step = _rearmSwap.Next(hands, CurrentCombatMode, now);
switch (step.Act)
{
case HandSwapSequence.Act.Wait:
return true;
case HandSwapSequence.Act.Stance:
{
int burst = SwapBurstEnabled?.Invoke() == true ? TryRearmBurst(hands, now) : 0;
if (burst != 0) return true;
if (_host.ChangeCombatModeFor(step.Slot, "Combat", "weapons back: peace first, then the hands"))
_rearmSwap.Sent(step, now);
return true;
}
case HandSwapSequence.Act.MoveToPack:
{
int pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: 1);
if (pack == 0)
{
WorldObjectCache.WarnPackFull(_host, "can't put the wand away to put the weapons back");
bool fight = _handsSwapForFight;
FinishRearmSwap(now, done: false, why: "no pack with room");
if (fight) NoteFightSwapFailed(now); else _rearmedFor = _rearmVital;
return false;
}
_host.MoveItemInternal((uint)step.Id, (uint)pack, 0, 1); // amount>=1 (engine rejects 0)
_rearmSwap.Sent(step, now);
_rearmLastMoved = step.Id;
EquippedState.Invalidate();
_host.Log($"[EquipDiag] {HandsSwapLabel}: 0x{(uint)step.Id:X8} '{WeaponName(step.Id)}' -> pack 0x{(uint)pack:X8} {(now - _rearmSwap.StartedAt).TotalMilliseconds:0} ms in");
return true;
}
case HandSwapSequence.Act.Wield:
{
bool off = step.Slot == HandSwapSequence.ShieldSlot;
if (_host.HasWieldItem) _host.WieldItem((uint)step.Id, (uint)step.Slot);
else _host.UseFor((uint)step.Id, "Combat", $"wield: {HandsSwapLabel}");
_rearmSwap.Sent(step, now);
_rearmLastMoved = step.Id;
NoteRearmWield(step.Id, off, now);
_host.Log($"[EquipDiag] {HandsSwapLabel}: wielding 0x{(uint)step.Id:X8} '{WeaponName(step.Id)}' ({(off ? "off hand" : "main hand")}) {(now - _rearmSwap.StartedAt).TotalMilliseconds:0} ms in");
return true;
}
case HandSwapSequence.Act.Done:
if (_handsSwapForFight)
{
FightSwapDone(now);
return true;
}
_rearmStanceWanted = _rearmSwap.WentThroughPeace ? WeaponKind(_fightMainId) : 0;
if (_rearmStanceWanted == CombatMode.Magic) _rearmStanceWanted = 0;
_rearmStanceSince = now;
_rearmStanceForFight = false;
FinishRearmSwap(now, done: true);
RearmStanceStep(now); // at once: the server starts it when the peace animation ends
return true;
default:
{
bool fight = _handsSwapForFight;
FinishRearmSwap(now, done: false, why: step.Why);
if (fight) NoteFightSwapFailed(now);
else _rearmedFor = _rearmVital; // combat's own equip step takes it from here
return false;
}
}
}
private void NoteRearmWield(int id, bool off, DateTime now)
{
if (off) { _offhandSentId = id; _lastEquipTime = now; EquippedState.Invalidate(); }
else MarkWieldSent(id, InHandWeaponId());
}
/// <summary>
/// The fight's stance after a weapons-back swap through peace, once (past our own peace request
/// only: the server holds it until the peace animation ends). True when it went or isn't wanted.
/// </summary>
private bool RearmStanceStep(DateTime now)
{
if (_rearmStanceWanted == 0 || (_settings.PeaceModeWhenIdle && !_rearmStanceForFight) || CurrentCombatMode != CombatMode.NonCombat
|| (now - _rearmStanceSince).TotalMilliseconds >= RearmStanceWaitMs)
{
_rearmStanceWanted = 0;
return true;
}
var a = ActionPacer.Current(_host);
bool onlyOurPeace = a == null || (a.Kind == PacedKind.CombatMode && a.ModeTarget == CombatMode.NonCombat && a.Who == "Combat");
if (!_host.ChangeCombatModeFor(_rearmStanceWanted, "Combat", "weapons back: the fight's stance", force: onlyOurPeace))
return false;
_host.Log($"[EquipDiag] {(_rearmStanceForFight ? "weapons for the fight" : "weapons back after heals")}: {(_rearmStanceWanted == CombatMode.Missile ? "Missile" : "Melee")} mode");
if (_rearmStanceForFight)
{
// Combat's own stance request (the wielded branch) waits its retry delay behind this one.
lastStanceAttempt = RynthClock.Now;
NoteStanceFlipSent();
}
_rearmStanceWanted = 0;
return true;
}
/// <summary>
/// The weapons-back burst (test toggle, /ra swaptest burst on): peace, the wand out (raw
/// PutItemInContainer) and the main hand and the off hand wielded, queued in one tick so they go
/// out in one frame. Only with no combat-mode change for BurstQuietMs. 0 = not tried, 1 = held this
/// tick, 2 = sent. See BuffManager.TryWandBurst.
/// </summary>
private int TryRearmBurst(IReadOnlyDictionary<int, int> hands, DateTime now)
{
if (!_host.HasPutItemInContainer || !_host.HasWieldItem) return 0;
// BuffManager's read when the plugin wired it (every heartbeat); this manager's own tick doesn't run
// while buffing has the tick, so its read saw the switch to Magic only at the weapons-back tick
// and held every burst (Drakkon, 10-22 23:06-23:21).
DateTime changed = LastModeChangeAt?.Invoke() ?? _cmModeChangedAt;
if ((now - changed).TotalMilliseconds < RearmBurstQuietMs) return 0;
var moves = _rearmSwap.Blockers(hands);
if (moves.Count > 2) return 0;
int pack = 0;
if (moves.Count > 0)
{
pack = OpenPackOverride?.Invoke() ?? WorldObjectCache.FindPackFor(_host, _worldFilter, includeMainPack: true, requireFree: moves.Count);
if (pack == 0) return 0;
}
if (!_host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", $"{HandsSwapLabel} burst: peace, the wand out and the weapons on at once")) return 1;
foreach (int id in moves) _host.PutItemInContainer(unchecked((uint)id), unchecked((uint)pack), 0);
var wants = _rearmWants;
foreach (var (id, slot) in wants)
{
_host.WieldItem(unchecked((uint)id), unchecked((uint)slot));
NoteRearmWield(id, slot == HandSwapSequence.ShieldSlot, now);
}
_rearmSwap.SentBurst(moves, now);
_rearmLastMoved = wants.Count > 0 ? wants[^1].Id : 0;
_host.Log($"[EquipDiag] {HandsSwapLabel} burst {(now - _rearmSwap.StartedAt).TotalMilliseconds:0} ms in: peace, " +
(moves.Count > 0 ? string.Join(", ", moves.ConvertAll(id => $"0x{(uint)id:X8} '{WeaponName(id)}'")) + $" -> pack 0x{(uint)pack:X8}, " : "") +
string.Join(", ", wants.ConvertAll(w => $"0x{(uint)w.Id:X8} '{WeaponName(w.Id)}' on")) + ", in one frame");
return 2;
}
/// <summary>The test toggle for the burst (/ra swaptest burst on), from BuffManager; set by the plugin.</summary>
public Func<bool>? SwapBurstEnabled { get; set; }
/// <summary>When the combat mode last changed (BuffManager's every-heartbeat read); set by the plugin.</summary>
public Func<DateTime>? LastModeChangeAt { get; set; }
private const double RearmBurstQuietMs = 1300;
private int _cmLastSeenMode = -1;
private DateTime _cmModeChangedAt = DateTime.MinValue;
private DateTime _rearmVital = DateTime.MinValue;
private List<(int Id, int Slot)> _rearmWants = new();
/// <summary>Each heartbeat: the weapons-back swap's steps, and when the combat mode last changed.</summary>
private void TickRearmSwap()
{
DateTime now = RynthClock.Now;
int m = CurrentCombatMode;
if (m != _cmLastSeenMode)
{
if (_cmLastSeenMode != -1) _cmModeChangedAt = now;
_cmLastSeenMode = m;
}
if (_rearmSwap.Active)
{
if (!_settings.IsMacroRunning)
{
bool fight = _handsSwapForFight;
FinishRearmSwap(now, done: false, why: "the macro stopped");
if (fight) NoteFightSwapFailed(now, counted: false);
}
// A target arriving doesn't end it: combat's equip points it at the fight's weapons, or ends
// it for a wand (FightJoinsHandsSwap). Ending it freed the gate only after the full 3 s.
else RearmSwapAdvance(now);
}
else if (_rearmStanceWanted != 0 && (_activeTargetId == 0 || _rearmStanceForFight) && _settings.IsMacroRunning)
RearmStanceStep(now);
}
// The weapons-back swap (HandSwapSequence) and what it owes once it ends.
private readonly HandSwapSequence _rearmSwap = new();
private bool _rearmSwapOpen;
private int _rearmLastMoved;
private int _rearmStanceWanted;
private DateTime _rearmStanceSince = DateTime.MinValue;
private const double RearmStanceWaitMs = 3000;
/// <summary>The slot a weapon goes back into: its own (two-handed, missile, held), else the main hand.</summary>
private int MainSlotFor(int id)
{
int valid = _worldFilter[id]?.Values(LongValueKey.Locations, 0) ?? 0;
if ((valid & HandSwapSequence.TwoHandedSlot) != 0) return HandSwapSequence.TwoHandedSlot;
if ((valid & HandSwapSequence.MissileSlot) != 0) return HandSwapSequence.MissileSlot;
if ((valid & HandSwapSequence.MeleeSlot) != 0) return HandSwapSequence.MeleeSlot;
if ((valid & HandSwapSequence.HeldSlot) != 0) return HandSwapSequence.HeldSlot;
return HandSwapSequence.MeleeSlot;
}
private void FinishRearmSwap(DateTime now, bool done, string why = "")
{
if (!_rearmSwapOpen) return;
_rearmSwapOpen = false;
double ms = (now - _rearmSwap.StartedAt).TotalMilliseconds;
string trail = _rearmSwap.Trail;
string what = HandsSwapLabel;
_rearmSwap.Cancel();
_handsSwapForFight = false;
_weaponSwapGate?.Release(_handsGateBy, _rearmLastMoved);
LastRearmSwapMs = ms;
_host.Log(done
? $"[EquipDiag] {what} in hand {ms:0} ms after the swap began ({trail})"
: $"[EquipDiag] {what} stopped after {ms:0} ms: {why} ({trail})");
}
/// <summary>The last weapons-back swap's length (ms).</summary>
internal double LastRearmSwapMs { get; private set; }
// Logged once per pair: what the slot reads say for two wielded weapons (the off-hand diagnosis).
private readonly HashSet<string> _twoInHandNoted = new();
@ -5346,6 +5635,14 @@ public partial class CombatManager : IDisposable
return EnsureUnarmedStance();
}
// Fast Weapon Swap: a hands swap is under way (weapons back after heals, or this one): it goes on
// with this fight's weapons, or ends for a wand. True = wait for it.
if (_settings.FastWeaponSwap && _rearmSwap.Active && FightJoinsHandsSwap(target, rule, targetWeaponId, weaponObj))
{
LastCombatSkipReason = "hand-swap";
return false;
}
// Another weapon in hand: one swap at a time, capped, no flip-flop. When the tracker
// says hold (the chosen one failed its tries, or it is the weapon just swapped away
// from), carry on with the one in hand.
@ -5426,6 +5723,16 @@ public partial class CombatManager : IDisposable
: CombatMode.Melee;
_chosenWeaponMode = desiredMode;
// Fast Weapon Swap: a caster in hand and a melee weapon or launcher wanted (a monster came while
// healing): peace, the wand out, the weapons on (one frame when the server is quiet), then the
// fight's stance. The client's own use took 1.4-1.7 s and paid a forced stance change.
if (_settings.FastWeaponSwap && allowWield && desiredMode != CombatMode.Magic && inHand != 0 && inHand != targetWeaponId
&& WeaponKind(inHand) == CombatMode.Magic && TryStartFightHandsSwap(target, rule, targetWeaponId, desiredMode))
{
LastCombatSkipReason = "hand-swap";
return false;
}
bool diagNow = (RynthClock.Now - _lastEquipDiagAt).TotalSeconds > 5;
// Use CurrentWieldedLocation (stype=10) — has an InqInt fallback that works even

View file

@ -53,4 +53,28 @@ internal static class EquippedState
/// <summary>Drop the cached read (a wield or move was just sent, or tests).</summary>
public static void Invalidate() { lock (Gate) _fresh = false; }
/// <summary>
/// What is wielded and where (item id -> EquipMask), read fresh: the tracker's list, or without
/// it (an engine before v87) the client's own fields, a slot read 0 guessed from the item's kind.
/// A copy, safe to hold across ticks (the hand swaps, HandSwapSequence).
/// </summary>
public static Dictionary<int, int> ReadFresh(RynthCoreHost host, WorldObjectCache? cache)
{
Invalidate();
if (TryGet(host, out var map)) return new Dictionary<int, int>(map);
var m = new Dictionary<int, int>();
if (cache == null) return m;
foreach (var wo in cache.GetDirectInventory(forceRefresh: true))
{
if (!WorldObjectCache.IsWieldedByPlayer(host, wo)) continue;
int slot = wo.Values(LongValueKey.CurrentWieldedLocation, 0);
if (slot == 0)
slot = WeaponList.IsWand(wo) ? HandSwapSequence.HeldSlot
: wo.ObjectClass == AcObjectClass.MissileWeapon ? HandSwapSequence.MissileSlot
: wo.ObjectClass == AcObjectClass.MeleeWeapon ? HandSwapSequence.MeleeSlot : 0;
if (slot != 0) m[wo.Id] = slot;
}
return m;
}
}

View file

@ -0,0 +1,314 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// One weapon swap as a short list of server steps, each sent the moment the server has answered
/// the last (2026-10-22). Pure: the caller reads the hands (EquippedState, id -> EquipMask), the
/// combat mode and the clock, does what <see cref="Next"/> says and reports it with <see cref="Sent"/>.
///
/// Why (Drakkon, DreamWeave, 2026-10-22 21:25): Acid + Frost Hand Wraps -> Sceptre took 7.2 s to
/// the first cast and about 3 s with no weapon in hand. The off hand went into the pack (answered in
/// 1.24 s), then 1.8 s of nothing, the main hand (answered in 2 ms), 2.9 s of nothing, the wand. The
/// waits were the swap gate's flat 3 s after every pack move. The client's own use of the wand was
/// no better while dual wielding: it takes the main hand first, one server answer per step (3.7 s).
///
/// What ACE does (Player_Inventory.cs, Player_Combat.cs, Creature_Combat.cs; the stance lengths from
/// the human motion table, 0x09000001):
/// * Every stance change goes through peace: melee -> Magic is melee -> peace (0.55 s) plus
/// peace -> Magic (0.52 s). A change to or from peace is one leg.
/// * Putting a wielded weapon into a pack in a combat mode first plays a forced change to bare
/// hands (1.15 s) and moves the item when it ends; after the move the server picks a stance for
/// what is left in hand, another change (and two weapons bounce between stances). In peace the
/// move is answered at once, with no stance change.
/// * A Held-slot caster needs both hands empty (CheckWeaponCollision); a wield runs at once.
/// * A cast that arrives while a stance change is still queued is cancelled by it; on a PK
/// character (DreamWeave casts that way) a cast can be left hanging behind an overlapping stance
/// animation (the 2 min 45 s hold on 10-06 13:58).
/// So, from a combat mode: peace first (one stance leg), both hands into the pack (each answered in a
/// round trip), the wand, then Magic (one leg). Magic is up about 0.6 s in instead of 2.4 s (the best
/// order in melee mode) or 6 s (before), and no stance change is ever queued behind another. Peace
/// drops weapon defense, for about 0.6 s; the melee route keeps it up to the last weapon but gets
/// to Magic 1.2-3.6 s later, and the old route went without a weapon in hand for about 3 s.
///
/// Bounded: a step unanswered in <see cref="StepResolveMs"/> is sent again, at most
/// <see cref="MaxSendsPerStep"/> times; the whole swap gives up after <see cref="GiveUpMs"/>.
/// </summary>
internal sealed class HandSwapSequence
{
public const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000, MissileSlot = 0x00400000,
AmmoSlot = 0x00800000, HeldSlot = 0x01000000, TwoHandedSlot = 0x02000000;
/// <summary>The slots that hold a hand (ammo is not one: arrows stay on).</summary>
public const int HandSlots = MeleeSlot | ShieldSlot | MissileSlot | HeldSlot | TwoHandedSlot;
/// <summary>AC combat modes (CombatMode).</summary>
public const int NonCombat = 1, Melee = 2, Missile = 4, Magic = 8;
public enum Act
{
/// <summary>A step is on its way to the server: nothing to send.</summary>
Wait,
/// <summary>Ask for combat mode <see cref="Step.Slot"/> (peace before the hands are cleared).</summary>
Stance,
/// <summary>Put <see cref="Step.Id"/> into a pack.</summary>
MoveToPack,
/// <summary>Wield <see cref="Step.Id"/> into <see cref="Step.Slot"/>.</summary>
Wield,
/// <summary>Everything wanted is in hand (or the sequence isn't running).</summary>
Done,
/// <summary>It can't finish now (<see cref="Step.Why"/>); the sequence has stopped.</summary>
Failed,
}
public readonly record struct Step(Act Act, int Id = 0, int Slot = 0, string Why = "");
/// <summary>A step's answer: the engine may hold an item action while the character animates (up to
/// 2.5 s, AcMainThreadQueue), then the server's answer (a forced stance change, about 1.2 s, if it
/// isn't in peace) and the round trip.</summary>
public double StepResolveMs { get; set; } = 4000;
/// <summary>The peace step: the mode reads peace within this, or the swap goes on without it.</summary>
public double PeaceResolveMs { get; set; } = 1500;
public int MaxSendsPerStep { get; set; } = 2;
public double GiveUpMs { get; set; } = 12_000;
private readonly List<(int Id, int Slot)> _wants = new();
private readonly HashSet<int> _keep = new();
private readonly Dictionary<int, int> _sends = new();
private readonly StringBuilder _trail = new();
private DateTime _startedAt, _flightAt;
private Act _flightAct = Act.Wait; // Wait = nothing in flight
private int _flightId, _flightSlot;
private bool _peaceWanted, _peaceDone;
// The burst (SentBurst): peace, every move and the wield sent in one frame.
private bool _burst;
private DateTime _burstAt;
private readonly HashSet<int> _burstPending = new();
/// <summary>A burst's steps all land within this, or the rest goes one step at a time.</summary>
public double BurstResolveMs { get; set; } = 2500;
public bool Active { get; private set; }
public string Label { get; private set; } = "";
public DateTime StartedAt => _startedAt;
/// <summary>The item of the step on its way (0 = none, or a stance step).</summary>
public int InFlightId => _flightAct == Act.Wait ? 0 : _flightId;
/// <summary>A step or a burst is on its way to the server (a new Start now could send it twice).</summary>
public bool InFlight => _burst || _flightAct != Act.Wait;
/// <summary>What the swap ends with, in order.</summary>
public IReadOnlyList<(int Id, int Slot)> Wants => _wants;
/// <summary>The item whose step went unanswered when the swap failed (0 = it failed some other way).</summary>
public int FailedId { get; private set; }
/// <summary>The steps so far with the server's answer times, for the log.</summary>
public string Trail => _trail.ToString();
/// <summary>The swap went through peace (the caller then asks for the stance its wants need).</summary>
public bool WentThroughPeace { get; private set; }
/// <summary>
/// Begins a swap that ends with each of <paramref name="wants"/> wielded in its slot, in order.
/// <paramref name="peaceFirst"/>: from a combat mode, ask for peace before anything leaves a hand.
/// Items in <paramref name="keep"/> are never taken off: one blocking a want fails the swap.
/// </summary>
public void Start(string label, DateTime now, IReadOnlyList<(int Id, int Slot)> wants, bool peaceFirst = false, IEnumerable<int>? keep = null)
{
_wants.Clear();
_wants.AddRange(wants);
_keep.Clear();
if (keep != null) foreach (int k in keep) if (k != 0) _keep.Add(k);
_sends.Clear();
_trail.Clear();
_startedAt = now;
_flightAct = Act.Wait;
_flightId = _flightSlot = 0;
_peaceWanted = peaceFirst;
_peaceDone = false;
_burst = false;
_burstPending.Clear();
WentThroughPeace = false;
FailedId = 0;
Label = label;
Active = true;
}
public void Cancel()
{
Active = false;
_flightAct = Act.Wait;
_flightId = _flightSlot = 0;
}
/// <summary>What to do now, given what the server says is wielded (item id -> EquipMask) and the combat mode.</summary>
public Step Next(IReadOnlyDictionary<int, int> wielded, int combatMode, DateTime now)
{
if (!Active) return new Step(Act.Done);
if (_burst)
{
double bms = (now - _burstAt).TotalMilliseconds;
if (combatMode == NonCombat) WentThroughPeace = true;
foreach (int id in new List<int>(_burstPending))
{
int slot = WantedSlot(id);
bool landed = slot != 0 ? wielded.TryGetValue(id, out int at) && (at & slot) != 0 : !wielded.ContainsKey(id);
if (!landed) continue;
Note($"{(slot != 0 ? "on" : "off")} 0x{(uint)id:X8} {bms / 1000:0.00} s");
_burstPending.Remove(id);
}
if (_burstPending.Count > 0 && bms < BurstResolveMs) return new Step(Act.Wait);
if (_burstPending.Count > 0) Note($"burst incomplete after {bms / 1000:0.0} s: the rest one step at a time");
_burst = false;
}
if (_flightAct != Act.Wait)
{
double ms = (now - _flightAt).TotalMilliseconds;
bool landed = _flightAct switch
{
Act.Stance => combatMode == _flightSlot,
Act.MoveToPack => !wielded.ContainsKey(_flightId),
_ => wielded.TryGetValue(_flightId, out int at) && (at & _flightSlot) != 0,
};
if (landed)
{
Note(_flightAct switch
{
Act.Stance => $"peace {ms / 1000:0.00} s",
Act.MoveToPack => $"off 0x{(uint)_flightId:X8} {ms / 1000:0.00} s",
_ => $"on 0x{(uint)_flightId:X8} {ms / 1000:0.00} s",
});
if (_flightAct == Act.Stance) { _peaceDone = true; WentThroughPeace = true; }
_flightAct = Act.Wait;
}
else if (_flightAct == Act.Stance)
{
if (ms < PeaceResolveMs) return new Step(Act.Wait, 0, _flightSlot);
// Not read in time: go on without it (the moves still work in a combat mode, slower).
Note($"peace not read in {ms / 1000:0.0} s");
_peaceDone = true;
_flightAct = Act.Wait;
}
else if (ms < StepResolveMs)
return new Step(Act.Wait, _flightId, _flightSlot);
else
{
Note($"0x{(uint)_flightId:X8} no answer in {ms / 1000:0.0} s");
int id = _flightId;
_flightAct = Act.Wait;
if (_sends.TryGetValue(id, out int n) && n >= MaxSendsPerStep)
{
FailedId = id;
return Fail($"0x{(uint)id:X8} wasn't answered after {n} sends");
}
}
}
if ((now - _startedAt).TotalMilliseconds > GiveUpMs)
return Fail($"not done in {GiveUpMs / 1000:0} s");
// Anything in a hand that isn't wanted there comes off first: the off hand before the rest.
int blocker = 0;
foreach (var kv in wielded)
{
if ((kv.Value & HandSlots) == 0 || WantedThere(kv.Key, kv.Value)) continue;
if (blocker == 0 || (kv.Value & ShieldSlot) != 0) blocker = kv.Key;
if ((kv.Value & ShieldSlot) != 0) break;
}
if (blocker != 0 && _keep.Contains(blocker))
return Fail($"0x{(uint)blocker:X8} is in the way and may not be taken off");
// Peace before the first item leaves a hand: the moves are then answered at once, and the
// stance changes the server makes around a combat-mode unwield never happen.
if (blocker != 0 && _peaceWanted && !_peaceDone)
{
if (combatMode == NonCombat) _peaceDone = true;
else return new Step(Act.Stance, 0, NonCombat);
}
if (blocker != 0) return new Step(Act.MoveToPack, blocker, 0);
foreach (var (id, slot) in _wants)
{
if (wielded.TryGetValue(id, out int at) && (at & slot) != 0) continue;
return new Step(Act.Wield, id, slot);
}
Active = false;
return new Step(Act.Done);
}
/// <summary>The caller sent <paramref name="step"/> (a stance request, a pack move or a wield).</summary>
public void Sent(Step step, DateTime now)
{
if (step.Act is not (Act.Stance or Act.MoveToPack or Act.Wield)) return;
_flightAct = step.Act;
_flightId = step.Id;
_flightSlot = step.Slot;
_flightAt = now;
if (step.Act != Act.Stance)
_sends[step.Id] = (_sends.TryGetValue(step.Id, out int n) ? n : 0) + 1;
}
/// <summary>
/// What would come off first, in order (the off hand before the rest), for a burst: every item in a
/// hand that isn't wanted where it is. Empty when one may not be taken off.
/// </summary>
public List<int> Blockers(IReadOnlyDictionary<int, int> wielded)
{
var off = new List<int>();
var rest = new List<int>();
foreach (var kv in wielded)
{
if ((kv.Value & HandSlots) == 0 || WantedThere(kv.Key, kv.Value)) continue;
if (_keep.Contains(kv.Key)) return new List<int>();
((kv.Value & ShieldSlot) != 0 ? off : rest).Add(kv.Key);
}
off.AddRange(rest);
return off;
}
/// <summary>
/// The caller sent peace, every move in <paramref name="moved"/> and the wield of each want in one
/// frame (BuffManager's burst). Next waits for all of them to land (<see cref="BurstResolveMs"/>),
/// then goes on one step at a time with whatever didn't.
/// </summary>
public void SentBurst(IEnumerable<int> moved, DateTime now)
{
_burst = true;
_burstAt = now;
_peaceDone = true;
_burstPending.Clear();
foreach (int id in moved) _burstPending.Add(id);
foreach (var (id, _) in _wants) _burstPending.Add(id);
foreach (int id in _burstPending) _sends[id] = (_sends.TryGetValue(id, out int n) ? n : 0) + 1;
_flightAct = Act.Wait;
Note("burst");
}
private int WantedSlot(int id)
{
foreach (var w in _wants) if (w.Id == id) return w.Slot;
return 0;
}
/// <summary>The caller couldn't send the step (no pack with room, no wield call): stop here.</summary>
public Step Abandon(string why) => Fail(why);
private bool WantedThere(int id, int slot)
{
foreach (var w in _wants)
if (w.Id == id && (slot & w.Slot) != 0) return true;
return false;
}
private Step Fail(string why)
{
Note("failed: " + why);
Cancel();
return new Step(Act.Failed, Why: why);
}
private void Note(string s)
{
if (_trail.Length > 0) _trail.Append(", ");
_trail.Append(s);
}
}

View file

@ -66,9 +66,12 @@ internal static class DamageStyles
/// other way round, except for a slayer (owner's rule, 2026-10-05: a monster is always
/// attacked with a slayer of it before an element choice, even when another weapon's element
/// meets a lower resistance; only a weapon the player set for that monster trumps it):
/// 1. The weapon set on THIS monster's own Damage tab row is used as set, slayer or not; it
/// must be in the Items list. Its element is the rule's, else its own, else the weakest
/// the character can cast.
/// 1. The weapon set on THIS monster's own Damage tab row, else on the Monsters rule that
/// matched it (not the Default row), is used as set, slayer or not (2026-10-22: the
/// rule's weapon used to be ignored, report R-20261022-193411-fb72). A Damage tab pick
/// must be in the Items list; a Monsters tab weapon need not be (CombatManager adds it to
/// the candidates). Its element is the rule's, else its own, else the weakest the
/// character can cast.
/// 2. A slayer: a listed weapon of the character's main kind whose SlayerCreatureType is
/// the monster's CreatureType and whose SlayerDamageBonus is above 1 or not known (ACE
/// multiplies the whole hit by it, so it beats any element choice, and never sends the
@ -78,7 +81,8 @@ internal static class DamageStyles
/// is the wand's own, else a melee/missile weapon's own, else the rule's, else the
/// weakest the character can cast. Creature type unknown: no slayer step.
/// A slayer of another kind (a melee slayer for a mage) is not a candidate.
/// 3. The Damage tab DEFAULT row's weapon (listed only): above the element steps, below a slayer.
/// 3. The Damage tab DEFAULT row's weapon (listed only), else the Monsters tab Default row's:
/// above the element steps, below a slayer.
/// 4. A Monsters rule damage type (not Auto) is the element; wield the listed weapon of that
/// element (a matching rending first, then the one in hand, then list order).
/// Whatever is chosen, a wand casts its own element when it has one (owner's rule,
@ -100,8 +104,11 @@ internal static class DamageStyles
/// Void Magic) replaces that: the pool is the listed weapons of that style, for a character
/// who uses two kinds and wants to choose. With none listed (or none the character can use,
/// e.g. Void without Void Magic) it falls back to Auto, the main kind, rather than not fighting.
/// The monster's own Damage tab weapon (step 1) still wins; the DEFAULT row's weapon only when
/// it is of the preferred style; War Magic never casts Nether and Void Magic nothing else.
/// The monster's own Damage tab or Monsters rule weapon (step 1) still wins; the DEFAULT row's
/// weapon only when it is of the preferred style; War Magic never casts Nether and Void Magic nothing else.
/// Which fixed weapon is passed in (and whether it is a step-1 pick or a DEFAULT one) is
/// CombatManager.ComputePlan's: this monster's Damage tab pick, its Monsters rule's weapon, the
/// Damage tab DEFAULT row's, the Monsters Default row's, the first one usable and listed.
/// </summary>
internal static class WeaponPlanner
{
@ -154,10 +161,11 @@ internal static class WeaponPlanner
bool ruleSet = rule.Length > 0;
WeaponCandidate? fixedPick = fixedWeaponId != 0 ? Find(listed, fixedWeaponId) : null;
// 1. The weapon the player set on this monster's own Damage tab row (listed only): honoured,
// slayer or not (owner, 2026-10-05: "the only time a slayer property gets trumped is if
// the player manually inputs a weapon without it"). The DEFAULT row's weapon is not a
// pick for this monster: a slayer of it beats that one (step 3).
// 1. The weapon the player set on this monster's own Damage tab row, or on the Monsters
// rule that matched it (a candidate; see the class note): honoured, slayer or not (owner, 2026-10-05: "the
// only time a slayer property gets trumped is if the player manually inputs a weapon
// without it"). A DEFAULT row's weapon (Damage tab or Monsters tab) is not a pick for
// this monster: a slayer of it beats that one (step 3).
if (fixedPick != null && !fixedIsDefault)
return FixedPlan(fixedPick, Slays(fixedPick, creatureType)
? fixedSource + ", " + SlayerSource(creatureType, fixedPick.SlayerBonus) : fixedSource, rule, weak, canCast);
@ -202,7 +210,8 @@ internal static class WeaponPlanner
}
}
// 3. The Damage tab DEFAULT row's weapon (listed only): no slayer of this monster is listed.
// 3. The Damage tab DEFAULT row's weapon, else the Monsters Default row's:
// no slayer of this monster is listed.
if (fixedPick != null && (!styled || pool.Contains(fixedPick)))
return FixedPlan(fixedPick, fixedSource, rule, weak, canCast);

View file

@ -26,6 +26,8 @@ public sealed class WeaponSwapGate
private string _lastSwapBy = "";
private int _movingId;
private long _claims;
private string _heldBy = "";
private long _heldUntilMs;
/// <summary>Swaps claimed so far: a caller can tell whether another swap went out after its own.</summary>
public long Claims { get { lock (_lock) { return _claims; } } }
@ -62,6 +64,7 @@ public sealed class WeaponSwapGate
long now = NowMs();
lock (_lock)
{
if (_heldBy.Length > 0 && now < _heldUntilMs) return false; // a multi-step swap is running (Hold)
long since = now - _lastSwapTickMs;
if (since < MinIntervalMs && !LastSwapDone(since))
return false;
@ -73,6 +76,38 @@ public sealed class WeaponSwapGate
}
}
/// <summary>
/// A multi-step swap (HandSwapSequence, 2026-10-22) that has claimed the gate keeps it for its
/// steps: no other swap goes until <see cref="Release"/>, or <paramref name="maxMs"/> as a backstop.
/// Its own steps are paced on the server's answers, not by this gate.
/// </summary>
public void Hold(string by, long maxMs)
{
lock (_lock)
{
_heldBy = by ?? "?";
_heldUntilMs = NowMs() + maxMs;
}
}
/// <summary>
/// The held swap is over. <paramref name="lastMovedId"/> (its last pack move or slot wield, 0 =
/// none) holds the next swap the full <see cref="MinIntervalMs"/> from now, as a noted move does.
/// </summary>
public void Release(string by, int lastMovedId)
{
lock (_lock)
{
if (_heldBy != (by ?? "?")) return;
_heldBy = "";
_lastSwapTickMs = NowMs();
_movingId = lastMovedId;
}
}
/// <summary>Who holds the gate for a multi-step swap ("" = no one; diagnostics).</summary>
public string HeldBy { get { lock (_lock) { return _heldBy.Length > 0 && NowMs() < _heldUntilMs ? _heldBy : ""; } } }
/// <summary>
/// The claimed swap moved <paramref name="itemId"/> into or out of a hand without a use (a
/// pack move or a slot wield): the next swap waits the full MinIntervalMs, as before.

View file

@ -10,7 +10,8 @@ namespace RynthCore.Plugin.RynthAi;
/// server, so a refused wield never got an answer and was retried: Drakkon's Tetsubo (Two Handed
/// Combat, untrained) took the off-hand weapon off for every fight (2026-10-18), his Electric Baton
/// and Acid Staff (War Magic) held up buffing. Read from the item's appraisal; unknown = not known
/// (the caller decides), never "met".
/// (the caller decides), never "met". A Skill requirement is checked against the buffed skill (vitae
/// lowers it, as on the server); a RawSkill one against the base skill (vitae doesn't).
/// </summary>
internal static class WieldRequirements
{
@ -30,7 +31,7 @@ internal static class WieldRequirements
host.TryGetObjectIntProperty(itemId, pDiff, out int diff);
switch (req)
{
case 1: case 2: case 8: // Skill (buffed), RawSkill (base: only the buffed one is read), Training
case 1: case 2: case 8: // Skill (buffed), RawSkill (base), Training
{
if (skills == null || !host.TryGetObjectIntProperty(itemId, pSkill, out int stype)) continue;
AcSkillType? skill = SkillOf((uint)stype);
@ -38,8 +39,23 @@ internal static class WieldRequirements
var s = skills[skill.Value];
string name = Name(skill.Value);
if (s.Training < 2) return $"needs {name}, untrained";
if (req == 8) continue;
if (diff > 0 && s.Buffed > 0 && s.Buffed < diff) return $"needs {name} {diff}, you have {s.Buffed}";
if (req == 8 || diff <= 0) continue;
if (req == 2)
{
// RawSkill: the base skill, without buffs and without vitae (ACE CreatureSkill.Base;
// the client's own raw read, which is what the client checks before it sends the
// wield). The buffed read carries the vitae penalty: at 40% vitae a Shashqa
// (base Two Handed Combat 420) read as 371 and was left out of the weapon choice,
// though it wields fine (2026-10-23). Base not readable: not known.
uint pid = host.GetPlayerId();
if (pid != 0 && host.HasGetObjectSkillBuffed
&& host.TryGetObjectSkillLevel(pid, (uint)stype, raw: 1, out int baseLevel) && baseLevel > 0
&& baseLevel < diff)
return $"needs base {name} {diff}, you have {baseLevel}";
continue;
}
// Skill: the buffed skill, vitae included (ACE CreatureSkill.Current), as read.
if (s.Buffed > 0 && s.Buffed < diff) return $"needs {name} {diff}, you have {s.Buffed}";
continue;
}
case 7: // Level

View file

@ -0,0 +1,176 @@
// ============================================================================
// RynthAi - Dashboard/DashboardPrefs.cs
// The dashboard window's own choices: minimized, the target bar, the vitals, the
// open drawers (one per side) and the drawers moved to the side they don't start
// on. One file for the PC, like the engine's dashboard state was (every client
// shows the dashboard the same way): %AppData%\RynthCore\rynthai_dashboard.txt,
// "key=value" lines. The first time, it starts from the engine dashboard's file
// (rynthai_avalonia.cache: line 1 minimized, 3 the target bar, 4 the vitals, 12
// the moved drawers), so the switch to RynthAi's own window keeps them.
// The engine's file also says which look is on (line 14, classic|modern): the
// Classic look is still RynthCore's face, so RynthAi's window steps aside for it
// (ClassicLook).
//
// The window sets the fields on the render thread; the plugin tick saves them
// (SaveIfChanged), never the render thread.
// ============================================================================
using System;
using System.IO;
using System.Linq;
namespace RynthCore.Plugin.RynthAi.Dashboard;
internal sealed class DashboardPrefs
{
// The drawers, in the order their tabs stack (the engine dashboard's keys, so its moves carry over).
public const string RangesDrawer = "ranges", FilesDrawer = "files", PatrolDrawer = "patrol",
RemoteDrawer = "remote", PinnedDrawer = "quick";
/// <summary>Every drawer key; My settings (quick) starts on the right, the rest on the left.</summary>
public static readonly string[] Drawers = { RangesDrawer, FilesDrawer, PatrolDrawer, RemoteDrawer, PinnedDrawer };
public static bool StartsRight(string key) => key == PinnedDrawer;
private static string Folder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore");
private static string FilePath => Path.Combine(Folder, "rynthai_dashboard.txt");
/// <summary>The engine dashboard's state (RynthCore UI/RynthAiDashboardState.cs).</summary>
private static string EngineStatePath => Path.Combine(Folder, "rynthai_avalonia.cache");
private volatile bool _minimized, _showTarget = true, _showVitals = true;
private volatile string _left = string.Empty, _right = string.Empty;
private volatile string[] _moved = Array.Empty<string>();
private volatile bool _dirty;
public bool Minimized => _minimized;
public bool ShowTarget => _showTarget;
public bool ShowVitals => _showVitals;
public void SetMinimized(bool v) { _minimized = v; _dirty = true; }
public void SetShowTarget(bool v) { _showTarget = v; _dirty = true; }
public void SetShowVitals(bool v) { _showVitals = v; _dirty = true; }
/// <summary>The drawer is on the right edge now (its start side, or the other one when moved).</summary>
public bool OnRight(string key) => StartsRight(key) != (Array.IndexOf(_moved, key) >= 0);
/// <summary>The drawer open on that side, or "".</summary>
public string OpenOn(bool right) => right ? _right : _left;
public bool IsOpen(string key) => (OnRight(key) ? _right : _left) == key;
/// <summary>Opens <paramref name="key"/>'s drawer (closing the one open on its side), or closes it when it is open.</summary>
public void ToggleDrawer(string key)
{
if (OnRight(key)) _right = _right == key ? string.Empty : key;
else _left = _left == key ? string.Empty : key;
_dirty = true;
}
public void CloseDrawer(string key)
{
if (_left == key) _left = string.Empty;
if (_right == key) _right = string.Empty;
_dirty = true;
}
/// <summary>Moves the drawer to the other edge; open, it opens there (closing the one open there).</summary>
public void MoveDrawer(string key)
{
bool wasOpen = IsOpen(key);
CloseDrawer(key);
_moved = Array.IndexOf(_moved, key) >= 0 ? _moved.Where(k => k != key).ToArray() : _moved.Append(key).ToArray();
if (wasOpen) ToggleDrawer(key);
_dirty = true;
}
private static bool IsDrawer(string key) => Array.IndexOf(Drawers, key) >= 0;
/// <summary>Reads the file, or starts from the engine dashboard's state. Plugin init.</summary>
public static DashboardPrefs Load()
{
var p = new DashboardPrefs();
try
{
string[] engine = File.Exists(EngineStatePath) ? File.ReadAllLines(EngineStatePath) : Array.Empty<string>();
bool movedRead = false;
if (File.Exists(FilePath))
{
string legacyDrawer = string.Empty;
foreach (string raw in File.ReadAllLines(FilePath))
{
int eq = raw.IndexOf('=');
if (eq <= 0) continue;
string key = raw[..eq].Trim(), value = raw[(eq + 1)..].Trim();
bool on = value == "1";
switch (key)
{
case "minimized": p._minimized = on; break;
case "target": p._showTarget = on; break;
case "vitals": p._showVitals = on; break;
case "left": p._left = IsDrawer(value) ? value : string.Empty; break;
case "right": p._right = IsDrawer(value) ? value : string.Empty; break;
case "drawer": legacyDrawer = value; break; // before 2026-10-21's two sides
case "moved":
movedRead = true;
p._moved = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Where(IsDrawer).ToArray();
break;
}
}
if (!movedRead) p._moved = EngineMoved(engine);
if (legacyDrawer.Length > 0 && IsDrawer(legacyDrawer) && p.OpenOn(p.OnRight(legacyDrawer)).Length == 0)
p.ToggleDrawer(legacyDrawer);
p._dirty = !movedRead || legacyDrawer.Length > 0;
return p;
}
// First time: the engine dashboard's choices, so nothing changes at the switch.
if (engine.Length > 0) p._minimized = engine[0].Trim() == "minimized";
if (engine.Length > 2) p._showTarget = engine[2].Trim() != "notarget";
if (engine.Length > 3) p._showVitals = engine[3].Trim() != "novitals";
p._moved = EngineMoved(engine);
p._dirty = true;
}
catch { /* unreadable: the defaults */ }
return p;
}
/// <summary>The engine dashboard's moved drawers (line 12, "moved:files,patrol").</summary>
private static string[] EngineMoved(string[] engine)
{
if (engine.Length < 12) return Array.Empty<string>();
string line = engine[11].Trim();
if (!line.StartsWith("moved:", StringComparison.OrdinalIgnoreCase)) return Array.Empty<string>();
return line[6..].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Where(IsDrawer).ToArray();
}
/// <summary>Writes the file when something changed. Plugin tick.</summary>
public void SaveIfChanged()
{
if (!_dirty) return;
_dirty = false;
try
{
Directory.CreateDirectory(Folder);
File.WriteAllText(FilePath,
"minimized=" + (_minimized ? 1 : 0) + "\n" +
"target=" + (_showTarget ? 1 : 0) + "\n" +
"vitals=" + (_showVitals ? 1 : 0) + "\n" +
"left=" + _left + "\n" +
"right=" + _right + "\n" +
"moved=" + string.Join(",", _moved) + "\n");
}
catch { /* best effort: the next change tries again */ }
}
/// <summary>
/// True while the engine dashboard's look is Classic (its file's line 14), the retail-style window
/// RynthCore still draws: RynthAi's window then steps aside. Plugin tick (a small file read).
/// </summary>
public static bool ClassicLook()
{
try
{
if (!File.Exists(EngineStatePath)) return false;
string[] lines = File.ReadAllLines(EngineStatePath);
return lines.Length > 13 && lines[13].Trim().Equals("classic", StringComparison.OrdinalIgnoreCase);
}
catch { return false; }
}
}

File diff suppressed because it is too large Load diff

View file

@ -26,6 +26,7 @@ internal enum TickStep
LocalFeatures,
GiveQueue,
Jumper,
Dashboard,
// In world.
VTankYield,
VitalsRead,
@ -112,6 +113,7 @@ internal sealed class TickGuard
Add(TickStep.LocalFeatures, "HUDs and panels", LogCat.Huds);
Add(TickStep.GiveQueue, "give queue", LogCat.Inventory);
Add(TickStep.Jumper, "jumper", LogCat.Jumper, essential: true);
Add(TickStep.Dashboard, "dashboard window", LogCat.UI);
Add(TickStep.VTankYield, "VTank yield", LogCat.General, essential: true);
Add(TickStep.VitalsRead, "vitals read", LogCat.Buffing, essential: true);

View file

@ -719,7 +719,10 @@ internal sealed class MiniRemoteHud
// Ctrl+wheel over the grid: bigger / smaller boxes (the window / drawer refits to them).
var io = ImGui.GetIO();
if (io.KeyCtrl && io.MouseWheel != 0f && ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem))
{
ResizeSlots(s, io.MouseWheel > 0f ? SlotSizeStep : -SlotSizeStep);
io.MouseWheel = 0f; // the boxes took it: not the panel's size too
}
}
/// <summary>

View file

@ -68,14 +68,45 @@ internal static class SectionsManifest
return views;
}
/// <summary>The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1).</summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections)
/// <summary>
/// RynthAi's dashboard window (RynthAiPlugin.Dashboard.cs, 2026-10-21): the engine's "RynthAi" panel's
/// place ("takeOver": its saved spot, bar button, hotkeys and /rc commands), drawn whole by RynthAi
/// ("chrome": "none") and as tall as it draws ("fitHeight"), plugin API v90. The Robot icon is the
/// engine bar's for RynthAi.
/// </summary>
public const string DashboardTitle = "RynthAi", DashboardSurface = "window:dashboard";
/// <summary>
/// The manifest JSON for <paramref name="views"/> (UTF-8 text, schema version 1), with the dashboard
/// window when <paramref name="dashboard"/>.
/// </summary>
public static string Build(IReadOnlyList<View> views, IReadOnlyList<Section> sections, bool dashboard = false)
{
using var stream = new MemoryStream(4096);
using (var w = new Utf8JsonWriter(stream))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
if (dashboard)
{
w.WriteStartArray("windows");
w.WriteStartObject();
w.WriteString("id", "dashboard");
w.WriteString("title", DashboardTitle);
w.WriteString("surface", DashboardSurface);
w.WriteString("icon", "");
w.WriteNumber("width", 296);
w.WriteNumber("height", 240);
w.WriteNumber("minWidth", 280);
w.WriteNumber("minHeight", 54);
w.WriteBoolean("bar", true);
w.WriteBoolean("edgeToEdge", true);
w.WriteBoolean("takeOver", true);
w.WriteString("chrome", "none");
w.WriteBoolean("fitHeight", true);
w.WriteEndObject();
w.WriteEndArray();
}
w.WriteStartArray("sections");
foreach (Section s in sections)
{

View file

@ -340,6 +340,9 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.Checkbox("Weapons Back After Heals", ref _settings.RearmAfterVitals);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("After a heal, restam or remana spell with nothing to fight, put the last fight's weapons (main hand and off hand) back on.");
ImGui.Checkbox("Fast Weapon Swap", ref _settings.FastWeaponSwap);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Switch weapons through peace mode, every step the moment the server allows:\nthe wand is in hand about 0.2 s after the switch begins (4-7 s without),\nand the weapons go back as fast, also when a monster comes while the wand\nis out (swinging again in about 1 s). On by default. Peace mode costs your weapon's defense\nfor about half a second; the slow way goes without a weapon for about 3 s.");
ImGui.Checkbox("Start Macro On Login", ref _settings.StartMacroOnLogin);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Automatically starts the macro when RynthAi loads.");

View file

@ -0,0 +1,84 @@
// LegacyDashboardRenderer.Instrument.cs — what RynthAi's own dashboard window shows (Dashboard/
// InstrumentDashboard.cs, 2026-10-21): the fields the engine's dashboard read from the snapshot JSON,
// read directly, plus the vitals refresh that the engine's snapshot poll used to drive.
using System;
using System.IO;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// <summary>
/// One frame of the dashboard: the macro, the subsystems, the bot's activity, the target and the vitals.
/// The target is the selection, or the monster RynthAi is fighting (TargetIsFight: combat doesn't
/// select it). TargetHealth is 0..1, or -1 while the server hasn't said.
/// </summary>
internal readonly record struct DashboardReadout(
bool MacroRunning,
string MetaState,
string Activity,
bool Combat, bool Buffing, bool Navigation, bool Looting, bool Meta,
uint TargetId, string TargetLabel, float TargetHealth,
bool ShowTargetStaminaMana, uint TargetStamina, uint TargetMaxStamina, uint TargetMana, uint TargetMaxMana,
uint Health, uint MaxHealth, uint Stamina, uint MaxStamina, uint Mana, uint MaxMana,
bool Locked, float Opacity,
string LootPath,
bool TargetIsFight = false);
/// <summary>The loaded-files pickers: each list, and the entry in use.</summary>
internal sealed record DashboardFiles(
string[] Profiles, int ProfileIdx,
string[] Navs, int NavIdx,
string[] Loots, int LootIdx,
string[] Metas, int MetaIdx,
string[] Buffs, int BuffIdx,
string ProfileName, string NavName, string LootName, string MetaName, string BuffName);
internal sealed partial class LegacyDashboardRenderer
{
/// <summary>The dashboard's frame. Any thread: plain field reads (strings are replaced, never changed).</summary>
internal DashboardReadout ReadDashboard()
{
string activity = ActivityArbiter.DisplayLabel(_settings.BotAction, _settings.BuffingLabel);
if (string.IsNullOrWhiteSpace(activity) || activity == "Default") activity = "Idle";
string state = string.IsNullOrWhiteSpace(_settings.CurrentState) ? "Default" : _settings.CurrentState;
return new DashboardReadout(
_settings.IsMacroRunning, state, activity,
_settings.EnableCombat, _settings.EnableBuffing, _settings.EnableNavigation, _settings.EnableLooting, _settings.EnableMeta,
_currentTargetId, _targetLabel ?? "NO TARGET", _targetHealthPercent,
_settings.ShowTargetStaminaMana, _targetStamina, _targetMaxStamina, _targetMana, _targetMaxMana,
_playerHealth, _playerMaxHealth, _playerStamina, _playerMaxStamina, _playerMana, _playerMaxMana,
_isLocked, _bgOpacity,
!string.IsNullOrEmpty(_vendorProfilePath?.Invoke()) ? _vendorProfilePath!.Invoke() : _settings.CurrentLootPath ?? string.Empty);
}
/// <summary>The five pickers' lists (copied under the lists' lock) and the entry in use. Any thread.</summary>
internal DashboardFiles ReadDashboardFiles()
{
string[] profiles, navs, loots, metas, buffs;
lock (_profileListsLock)
{
profiles = _profiles.ToArray();
navs = _navFiles.ToArray();
loots = _lootFiles.ToArray();
metas = _metaFiles.ToArray();
buffs = _buffFiles.ToArray();
}
string profile = _settings.SelectedProfile ?? "Default";
return new DashboardFiles(
profiles, Math.Max(0, Array.IndexOf(profiles, profile)),
navs, _selectedNavIdx,
loots, _settings.LootProfileIdx,
metas, _settings.MetaProfileIdx,
buffs, _settings.BuffProfileIdx,
profile,
string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath),
string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath),
string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath),
string.IsNullOrEmpty(_settings.CurrentBuffProfilePath) ? BuiltInBuffProfileLabel : Path.GetFileNameWithoutExtension(_settings.CurrentBuffProfilePath));
}
/// <summary>
/// The player's vitals from the engine, for the dashboard. The engine's snapshot poll did this
/// (BuildSnapshotJson) while its dashboard was open; RynthAi's own window has no poll. Pump thread.
/// </summary>
internal void RefreshDashboardVitals() => RefreshPlayerVitals();
}

View file

@ -2025,6 +2025,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.EnableGroundLoot = tmp.EnableGroundLoot;
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
dst.RearmAfterVitals = tmp.RearmAfterVitals;
dst.FastWeaponSwap = tmp.FastWeaponSwap;
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;

View file

@ -308,6 +308,17 @@ public sealed class LegacyUiSettings
/// <summary>After a heal, restam or remana spell with no monster to fight, put the last fight's
/// weapons (main hand and off hand) back on instead of waiting for the next target.</summary>
public bool RearmAfterVitals;
/// <summary>
/// Weapon swaps (to the wand for a heal or a buff, and Weapons Back After Heals) through peace
/// mode (2026-10-22, HandSwapSequence): with the server quiet, peace, the moves out of the hands and
/// the wields go in one frame (the burst: the wand in hand 0.1-0.26 s after the swap begins on
/// Drakkon); else each step the moment the server answers the last (about 1 s). Before: 4-7 s.
/// Also combat's own equip when a monster comes with the wand in hand (2026-10-23).
/// On by default since 2026-10-23, saved under a new name: the opt-in build saved "FastWeaponSwap":
/// false into every profile it touched, and that no longer loads. Off: the swap as before (*.LegacySwap.cs).
/// </summary>
[JsonPropertyName("FastWeaponSwapOn")]
public bool FastWeaponSwap = true;
public bool RebuffWhenIdle;
/// <summary>
/// Re-cast a self buff when its remaining duration drops below this many seconds.

View file

@ -183,6 +183,7 @@ public sealed partial class RynthAiPlugin
["enablemeta"] = "EnableMeta",
["opendoors"] = "OpenDoors",
["idlepeacemode"] = "PeaceModeWhenIdle",
["fastweaponswap"] = "FastWeaponSwap",
["idlebufftopoff"] = "RebuffWhenIdle",
["summonpets"] = "SummonPets",
["combinesalvage"] = "EnableCombineSalvage",

View file

@ -3618,6 +3618,7 @@ internal sealed partial class ExpressionEngine
["SalvageWithoutPanel"] = (() => B(s.SalvageWithoutPanel), v => s.SalvageWithoutPanel = ToDouble(v) != 0),
["PeaceModeWhenIdle"] = (() => B(s.PeaceModeWhenIdle), v => s.PeaceModeWhenIdle = ToDouble(v) != 0),
["RearmAfterVitals"] = (() => B(s.RearmAfterVitals), v => s.RearmAfterVitals = ToDouble(v) != 0),
["FastWeaponSwap"] = (() => B(s.FastWeaponSwap), v => s.FastWeaponSwap = ToDouble(v) != 0),
["RebuffWhenIdle"] = (() => B(s.RebuffWhenIdle), v => s.RebuffWhenIdle = ToDouble(v) != 0),
["UsePotions"] = (() => B(s.UsePotions), v => s.UsePotions = ToDouble(v) != 0),
["UseBuffItems"] = (() => B(s.UseBuffItems), v => s.UseBuffItems = ToDouble(v) != 0),

View file

@ -140,7 +140,8 @@ public static unsafe class PluginExports
{
if (surface == null) return 0;
ReadOnlySpan<byte> name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface);
if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length];
bool popped = name.EndsWith(":popout"u8);
if (popped) name = name[..^":popout"u8.Length];
var plugin = Runtime.Plugin;
if (plugin == null) return 0;
System.Numerics.Vector2 want;
@ -149,6 +150,12 @@ public static unsafe class PluginExports
{
return plugin.MarkEngineMiniRemote() ? 1 : 0;
}
else if (name.SequenceEqual("window:dashboard"u8))
{
// RynthAi's own dashboard window (RynthAiPlugin.Dashboard.cs): 1 drawn, 0 not ready, -2 failed.
int drawn = plugin.RenderDashboard(popped, out want);
if (drawn != 1) return drawn;
}
else if (name.StartsWith("section:"u8))
{
// Section names are short ASCII ids (Huds/SectionsManifest.cs); anything longer isn't ours.

View file

@ -0,0 +1,222 @@
// RynthAiPlugin.Dashboard.cs — RynthAi's dashboard window (Dashboard/InstrumentDashboard.cs, 2026-10-21).
//
// RynthAi draws its dashboard itself now: the sections manifest declares the window (Huds/
// SectionsManifest.cs, DashboardWindow) as "RynthAi" with "takeOver", so it takes the engine
// panel's place (its saved spot, bar button, hotkeys and /rc commands), and with RynthCore's
// plugin API v90 "chrome": "none" and "fitHeight": RynthAi draws the whole window, frame
// included, and the engine fits its height. On an older engine the window isn't declared and
// RynthCore's own dashboard stays.
//
// The Classic (retail) look is still RynthCore's face: picking it here runs "/rc dashboard
// classic" and drops the window, so the engine's face comes back for it; switching back to the
// modern look there brings this window back (the engine's state file says which look is on).
//
// The tick side: the window's queued clicks, the player's vitals (the engine's snapshot poll
// refreshed them while its dashboard was open), the monster RynthAi is fighting for the target
// bar (combat doesn't select it since 2026-06-03, so the selection alone left the bar empty in a
// fight), the prefs' save, and the settings' save after an opacity or lock change.
using System;
using System.Collections.Concurrent;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Plugin.RynthAi.Dashboard;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
public sealed partial class RynthAiPlugin
{
internal const string DashboardSurface = "window:dashboard";
private InstrumentDashboard? _instrument; // render thread
private DashboardBridge? _dashBridge; // render thread
private DashboardPrefs _dashPrefs = new(); // loaded in Initialize
private readonly ConcurrentQueue<Action> _dashActions = new();
private readonly DateTime _dashLoadedUtc = DateTime.UtcNow;
private long _dashDrawnMs = long.MinValue / 2; // render thread writes, tick reads
private long _nextDashVitalsMs, _nextDashClassicMs, _dashSaveAtMs;
private volatile bool _classicLook; // the engine's look is Classic (its file)
private long _classicAskedMs; // "Classic look" clicked: the window steps aside now
private volatile FightTarget? _dashFight; // tick writes, render reads
private int _dashFailures; // draws in a row that threw
/// <summary>The monster RynthAi is fighting, for the target bar: its name, health (0..1, -1 unknown) and vitals.</summary>
internal sealed record FightTarget(uint Id, string Name, float Health, uint Stamina, uint MaxStamina, uint Mana, uint MaxMana);
internal DashboardPrefs DashPrefs => _dashPrefs;
internal DateTime DashLoadedUtc => _dashLoadedUtc;
/// <summary>The engine (RynthPluginBase.Host is protected).</summary>
internal RynthCoreHost DashHost => Host;
/// <summary>
/// The dashboard window goes in the manifest: an engine with frameless windows (v90), and not
/// while the Classic look is on (RynthCore's face draws that). Render thread (the manifest poll).
/// </summary>
private bool DashboardWindowWanted =>
Host.HasFramelessWindows && !_classicLook && Interlocked.Read(ref _classicAskedMs) == 0;
/// <summary>
/// RynthPluginRenderEmbed "window:dashboard": the dashboard, into the host's window (docked, or
/// popped out in its own context). 1 drawn, 0 not ready, -2 failed (three draws in a row threw:
/// the engine switches the surface off and says so). Render thread.
/// </summary>
internal int RenderDashboard(bool popped, out Vector2 want)
{
want = default;
if (!_initialized || !_loginComplete || _dashboard == null || Host.ImGuiContext == IntPtr.Zero) return 0;
Volatile.Write(ref _dashDrawnMs, Environment.TickCount64);
IntPtr previous = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(EmbedContext());
try
{
_dashBridge ??= new DashboardBridge(this);
_instrument ??= new InstrumentDashboard(_dashBridge);
want = _instrument.Draw(popped);
_dashFailures = 0;
return 1;
}
catch (Exception ex)
{
RynthLog.Exception(LogCat.UI, ex, "RenderDashboard");
return ++_dashFailures >= 3 ? -2 : 0;
}
finally
{
ImGui.SetCurrentContext(previous);
}
}
/// <summary>Plugin tick: the window's clicks, the vitals and the fight while it shows, the look, the saves.</summary>
private void TickDashboard()
{
while (_dashActions.TryDequeue(out Action? act))
{
try { act(); }
catch (Exception ex) { Host.Log("[RynthAi] Dashboard: " + ex.Message); }
}
long now = Environment.TickCount64;
bool shown = now - Volatile.Read(ref _dashDrawnMs) < 2000;
if (shown && now >= _nextDashVitalsMs)
{
_nextDashVitalsMs = now + 100;
_dashboard?.RefreshDashboardVitals();
_dashFight = ReadFightTarget(_dashFight);
}
if (now >= _nextDashClassicMs)
{
_nextDashClassicMs = now + 2000;
bool classic = DashboardPrefs.ClassicLook();
_classicLook = classic;
long asked = Interlocked.Read(ref _classicAskedMs);
// Once the engine's file says Classic (or 10 s on, if it never does) the click has landed.
if (asked != 0 && (classic || now - asked > 10_000)) Interlocked.Exchange(ref _classicAskedMs, 0);
}
_dashPrefs.SaveIfChanged();
// An opacity or lock change from the window, saved with the profile a moment later (a few
// clicks on the opacity buttons make one save).
if (_dashSaveAtMs != 0 && now >= _dashSaveAtMs)
{
_dashSaveAtMs = 0;
_dashboard?.SaveSettings();
}
}
/// <summary>The window changed something the settings profile keeps (opacity, lock). Plugin tick.</summary>
internal void ScheduleDashSave() => _dashSaveAtMs = Environment.TickCount64 + 1000;
/// <summary>
/// The monster combat is on while the macro runs, or null: its name, the health the server sends
/// for the mob we fight, and its stamina and mana when known. The last one again when nothing
/// changed (no allocation). Plugin tick.
/// </summary>
private FightTarget? ReadFightTarget(FightTarget? last)
{
var settings = _dashboard?.Settings;
int id = _combatManager?.activeTargetId ?? 0;
if (id == 0 || settings == null || !settings.IsMacroRunning || !settings.EnableCombat) return null;
uint uid = unchecked((uint)id);
float health = _objectCache?.GetHealthRatio(id) ?? -1f;
uint st = 0, maxSt = 0, mn = 0, maxMn = 0;
if (Host.HasGetTargetVitals) Host.TryGetTargetVitals(uid, out _, out _, out st, out maxSt, out mn, out maxMn);
if (last != null && last.Id == uid && last.Health == health && last.Stamina == st && last.MaxStamina == maxSt
&& last.Mana == mn && last.MaxMana == maxMn)
return last;
string name = last != null && last.Id == uid ? last.Name : _objectCache?[id]?.Name ?? string.Empty;
if (name.Length == 0) name = "0x" + uid.ToString("X8");
return new FightTarget(uid, name, health, st, maxSt, mn, maxMn);
}
/// <summary>The readout with the target bar on the monster RynthAi is fighting, when it is fighting one. Render thread.</summary>
internal DashboardReadout WithFightTarget(DashboardReadout r)
{
FightTarget? f = _dashFight;
if (f == null) return r;
return r with
{
TargetId = f.Id, TargetLabel = f.Name, TargetHealth = f.Health, TargetIsFight = true,
TargetStamina = f.Stamina, TargetMaxStamina = f.MaxStamina, TargetMana = f.Mana, TargetMaxMana = f.MaxMana,
};
}
/// <summary>"Classic look": RynthCore's face draws it; this window steps aside at once. Render thread.</summary>
internal void UseClassicLook()
{
Interlocked.Exchange(ref _classicAskedMs, Math.Max(1, Environment.TickCount64));
QueueDashCommand("/rc dashboard classic");
}
internal void QueueDashAction(Action action)
{
if (_dashActions.Count < 64) _dashActions.Enqueue(action);
}
/// <summary>A chat command for the tick (RynthCore's /rc, another plugin's /ro ...).</summary>
internal void QueueDashCommand(string command)
{
if (!Host.HasInvokeChatParser || _engineCommands.Count >= MaxQueuedEngineCommands) return;
_engineCommands.Enqueue(command);
}
/// <summary>The Mini Remote drawer: RynthAi's remote, into the current window. Render thread.</summary>
internal bool DrawDashMiniRemote(out Vector2 want)
{
want = default;
var huds = _huds;
if (huds == null) return false;
want = huds.RenderEmbedded(false, true);
return true;
}
}
/// <summary>What the dashboard window reads and asks (Dashboard/InstrumentDashboard.cs): RynthAi, queued for its tick.</summary>
internal sealed class DashboardBridge : IDashboardHost
{
private readonly RynthAiPlugin _p;
public DashboardBridge(RynthAiPlugin plugin) => _p = plugin;
private LegacyDashboardRenderer Renderer => _p.DashboardRenderer ?? throw new InvalidOperationException("RynthAi's dashboard isn't ready.");
public RynthCoreHost Host => _p.DashHost;
public DashboardReadout Read() => _p.WithFightTarget(Renderer.ReadDashboard());
public DashboardFiles ReadFiles() => Renderer.ReadDashboardFiles();
public DashboardPrefs Prefs => _p.DashPrefs;
public string Version => RynthPluginInfo.Version;
public DateTime LoadedUtc => _p.DashLoadedUtc;
public void Queue(Action action) => _p.QueueDashAction(action);
public void Command(string command) => _p.QueueDashCommand(command);
public void ToggleMacro() => Queue(_p.ToggleMacroFromPanel); // refuses a start while VTank runs
public void SetSubsystem(int id, bool on) => Queue(() => _p.DashboardRenderer?.SetSubsystemEnabled(id, on));
public void ForceRebuff() => Queue(() => _p.DashboardRenderer?.RequestForceRebuff());
public void CancelForceRebuff() => Queue(() => _p.DashboardRenderer?.RequestCancelForceRebuff());
public void AdjustOpacity(float delta) => Queue(() => { _p.DashboardRenderer?.AdjustOpacity(delta); _p.ScheduleDashSave(); });
public void ToggleLock() => Queue(() => { _p.DashboardRenderer?.TogglePanelLock(); _p.ScheduleDashSave(); });
public void SelectProfile(int kind, int index) => Queue(() => _p.DashboardRenderer?.SelectProfileAtIndex(kind, index));
public void StartPatrol() => Queue(_p.HandleDungeonNavPatrol);
public void ToggleSpells() => _p.EnqueueRemoteCommand("spells", "toggle");
public void UseClassicLook() => _p.UseClassicLook();
public bool DrawMiniRemote(out Vector2 want) => _p.DrawDashMiniRemote(out want);
}

View file

@ -480,7 +480,8 @@ public sealed partial class RynthAiPlugin
public string? BuildSectionsJson()
{
if (!_initialized || !_loginComplete) return null;
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections);
return Huds.SectionsManifest.Build(Huds.SectionsManifest.Views(), Huds.SectionsManifest.OwnSections,
dashboard: DashboardWindowWanted);
}
/// <summary>Chat Translate window in the dashboard colours (no-op while hidden).</summary>
private void RenderTranslateWindow()

View file

@ -220,6 +220,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
InitSessionStats();
// The overlay windows (OnRenderOverlay) must draw through the engine's cimgui module.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => RynthLog.Write(LogCat.UI, msg));
// RynthAi's own dashboard window (RynthAiPlugin.Dashboard.cs): the engine's look, and its prefs.
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
_dashPrefs = RynthCore.Plugin.RynthAi.Dashboard.DashboardPrefs.Load();
_dashboard = new LegacyDashboardRenderer(Host);
_killClock.MacroRunning = () => _dashboard?.Settings.IsMacroRunning == true;
_dashboard.KillClock = _killClock;
@ -737,6 +740,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager.Vitals = _vitals; // the script hook's request carries the player's vitals
_combatManager.HoldIdlePeace = LootHoldsIdlePeace;
_combatManager.LastVitalCastAt = () => _buffManager?.LastVitalCastAt ?? DateTime.MinValue;
_combatManager.SwapBurstEnabled = () => _buffManager?.SwapBurst == true;
_combatManager.LastModeChangeAt = () => _buffManager?.LastModeChangeAt ?? DateTime.MinValue;
_combatManager.BuffingWantsTick = () => _buffManager != null
&& (_buffManager.PendingSpellId != 0 || _buffManager.WantsVitalRecharge
|| (_dashboard?.Settings?.EnableBuffing == true && _buffManager.NeedsAnyBuff()));
@ -1454,6 +1459,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
Guard(TickStep.CombatHook, CombatHook.ObserveUseDone); // ctx.last.err: the answer to the hook's last cast
Guard(TickStep.DelayedCommands, TickDelayedCommands); // /ub delay
Guard(TickStep.GameInput, GameInput.Pump); // release keys held for /mt movement | jump | strafe
Guard(TickStep.Dashboard, TickDashboard); // the dashboard window's clicks, vitals and prefs
Guard(TickStep.EngineCommands, DrainEngineCommands); // fellowship command buttons (RynthCore's Fellowship section)
Guard(TickStep.PropertyDump, () => TickPropertyDump()); // /ub propertydump: waits for the ID, chat in chunks
if (_loginComplete) Guard(TickStep.PackSetup, () => _dashboard?.TickPackSetup(_objectCache, _playerId)); // new/copied profile items
@ -3996,6 +4002,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "forcebuff": HandleForceBuff(); break;
case "cancelforcebuff": HandleCancelForceBuff(); break;
case "buff": HandleBuffCommand(parts); break;
case "swaptest":
if (_buffManager == null) { ChatLine("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
_buffManager.RequestSwapTest(parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : "");
break;
case "bufftest":
if (_buffManager == null) { ChatLine("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
_buffManager.EnableCastRegistryDiagnostic = !_buffManager.EnableCastRegistryDiagnostic;

View file

@ -67,6 +67,9 @@
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<!-- ImGui text calls for non-literal text ('%' escaped; RynthILT links the same file). -->
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<!-- The engine's look for RynthAi's own windows (the instrument dashboard, 2026-10-21; RynthNet links them too). -->
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
<!-- A server plugin's part of the Mini Remote (RynthServer.Hub) and RynthAi.Hub (what server plugins borrow). -->
<Compile Include="..\Shared\RynthServerHubApi.cs" Link="Shared\RynthServerHubApi.cs" />
<Compile Include="..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />

View file

@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthCore.Plugin.RynthDefective;
/// <summary>
/// What the windows and the commands act on: the character's data, the use controller, and the
/// things a player does to slots (set one from the selected item, clear, move, bind a key). The
/// host-facing parts are delegates, so all of it runs offline in the tests.
/// </summary>
internal sealed class DefSession
{
public DefData Data = new();
public readonly UseController Use = new();
public readonly HotkeyLookup Keys;
/// <summary>Everything carried now (cached by the plugin; at most a moment old).</summary>
public Func<IReadOnlyList<CarriedItem>> Items = () => Array.Empty<CarriedItem>();
public Func<uint> SelectedId = () => 0;
public Func<long> Now = () => Environment.TickCount64;
/// <summary>Types a line to the engine's chat parser ("/rc hotkey add F9 /rdef use 3"); false when it can't.</summary>
public Func<string, bool> RunChat = _ => false;
/// <summary>Asks for the character's file to be written soon.</summary>
public Action Save = () => { };
/// <summary>The pictures and bar buttons need op level 2 script windows.</summary>
public bool IconsAvailable;
public bool LoggedIn;
public string Character = string.Empty;
// The line under the bar: the last thing that happened.
private string _status = string.Empty;
private long _statusAtMs;
private bool _statusIsWarning;
public const long StatusShownMs = 9000;
public DefSession(HotkeyLookup keys) => Keys = keys;
public DefSettings Settings => Data.Settings;
public void SetStatus(string text, bool warning = false)
{
_status = text;
_statusIsWarning = warning;
_statusAtMs = Now();
}
/// <summary>The status line while it is fresh; empty after <see cref="StatusShownMs"/>.</summary>
public string Status(out bool warning)
{
warning = _statusIsWarning;
return _status.Length > 0 && Now() - _statusAtMs < StatusShownMs ? _status : string.Empty;
}
// ── Using ───────────────────────────────────────────────────────────────
/// <summary>The slot's button or key: use what it holds. Returns what to tell the player when nothing could be queued.</summary>
public string? UseSlot(int slotNumber)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
DefSlot slot = Data.Slots[slotNumber - 1];
if (slot.Item == null) return $"Slot {slotNumber} is empty. Set it from the bar (Edit slots) or with /rdef set {slotNumber}.";
Use.Request(new UseRequest(slot.Item, null, slot.Mode, "slot " + slotNumber, Now()));
return null;
}
/// <summary>/rdef use &lt;name&gt;: an item by what the player typed.</summary>
public void UseByName(string name) =>
Use.Request(new UseRequest(null, name, UseMode.Auto, "name '" + name + "'", Now()));
/// <summary>The picker: wield this weapon.</summary>
public void Wield(ItemRef item) =>
Use.Request(new UseRequest(item, null, UseMode.Equip, "picker", Now()));
// ── Slots ───────────────────────────────────────────────────────────────
public string SetFromSelected(int slotNumber)
{
uint sel = SelectedId();
if (sel == 0) return "Select the item in the game first (click it in your pack), then set the slot.";
CarriedItem? it = FindById(sel);
if (it == null) return "The selected object isn't in your pack, so it can't go in a slot.";
return SetSlot(slotNumber, it);
}
/// <summary>An item dragged onto the slot (its object id).</summary>
public string SetFromId(int slotNumber, uint objectId)
{
CarriedItem? it = FindById(objectId);
if (it == null) return "That isn't in your pack, so it can't go in a slot.";
return SetSlot(slotNumber, it);
}
public string SetFromName(int slotNumber, string name)
{
CarriedItem? it = ItemMatcher.FindByName(name, Items());
if (it == null) return $"No item named '{name}' in your pack.";
return SetSlot(slotNumber, it);
}
public string SetSlot(int slotNumber, CarriedItem it)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
DefSlot slot = Data.Slots[slotNumber - 1];
slot.Item = ItemRef.From(it);
slot.Mode = UseMode.Auto;
Save();
ItemKind kind = ItemKinds.Classify(it);
return $"Slot {slotNumber}: {it.FullName} ({UseModes.Describe(ItemKinds.DefaultAction(kind))} when pressed).";
}
public string ClearSlot(int slotNumber)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
Data.Slots[slotNumber - 1] = new DefSlot();
Save();
return $"Slot {slotNumber} cleared.";
}
/// <summary>Swaps slot <paramref name="a"/> with <paramref name="b"/> (1-based), as moving one place.</summary>
public bool SwapSlots(int a, int b)
{
int max = Settings.SlotCount;
if (a < 1 || b < 1 || a > max || b > max || a == b) return false;
(Data.Slots[a - 1], Data.Slots[b - 1]) = (Data.Slots[b - 1], Data.Slots[a - 1]);
Save();
return true;
}
public void SetSlotMode(int slotNumber, UseMode mode)
{
Data.Slots[slotNumber - 1].Mode = mode;
Save();
}
public void SetSlotCount(int count)
{
Settings.SlotCount = Math.Clamp(count, DefSettings.SlotsMin, DefSettings.SlotsMax);
Save();
}
public CarriedItem? FindById(uint id)
{
foreach (CarriedItem it in Items())
if (it.Id == id) return it;
return null;
}
/// <summary>
/// After an inventory read: every slot, favourite and recent entry follows the item it stands for
/// (a used-up stack's replacement, a new picture). Never clears anything. Returns whether a
/// save is due. Skipped while nothing at all is carried (the inventory isn't loaded yet).
/// </summary>
public bool Maintain(IReadOnlyList<CarriedItem> items)
{
if (items.Count == 0) return false;
bool changed = false;
foreach (DefSlot s in Data.Slots)
if (s.Item != null && ItemMatcher.Maintain(s.Item, items)) changed = true;
foreach (ItemRef f in Data.Favourites)
if (ItemMatcher.Maintain(f, items)) changed = true;
foreach (ItemRef r in Data.Recent)
if (ItemMatcher.Maintain(r, items)) changed = true;
return changed;
}
// ── Keys ────────────────────────────────────────────────────────────────
/// <summary>The key bound to slot <paramref name="slotNumber"/> or to its item by name, or null.</summary>
public string? KeyOfSlot(int slotNumber)
{
long now = Now();
string? key = Keys.KeyFor(DefCommandParser.UseCommand(slotNumber), now);
if (key != null) return key;
ItemRef? item = Data.Slots[slotNumber - 1].Item;
return item == null ? null : Keys.KeyFor(NameCommand(item), now);
}
public static string NameCommand(ItemRef item) => "/rdef use " + item.FullName;
/// <summary>Binds a key to the slot ("/rdef use 3") or, with <paramref name="byName"/>, to its item's name ("/rdef use Stamina Kit"). Returns the message.</summary>
public string BindKey(int slotNumber, string combo, bool byName)
{
combo = (combo ?? string.Empty).Trim();
if (combo.Length == 0) return "Type the key first, e.g. F9 or Ctrl+1.";
if (combo.IndexOf(' ') >= 0) return "A key has no spaces, e.g. Ctrl+F9.";
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
ItemRef? item = Data.Slots[slotNumber - 1].Item;
if (byName && item == null) return $"Slot {slotNumber} is empty: nothing to bind by name.";
string command = byName ? NameCommand(item!) : DefCommandParser.UseCommand(slotNumber);
UnbindQuiet(slotNumber);
if (!RunChat($"/rc hotkey add {combo} {command}"))
return $"This engine can't bind keys from here. Type: /rc hotkey add {combo} {command}";
Keys.Invalidate();
return $"Binding {combo} to {command} (the engine confirms in chat; Settings > Hotkeys lists it).";
}
public string UnbindKey(int slotNumber)
{
if (slotNumber < 1 || slotNumber > DefSettings.SlotsMax) return $"There is no slot {slotNumber}.";
string? key = UnbindQuiet(slotNumber);
Keys.Invalidate();
return key == null ? $"Slot {slotNumber} has no key." : $"Key {key} removed from slot {slotNumber}.";
}
/// <summary>Removes the slot's current key (either way of binding); returns it.</summary>
private string? UnbindQuiet(int slotNumber)
{
string? key = KeyOfSlot(slotNumber);
if (key == null) return null;
string combo = key.EndsWith(" (off)", StringComparison.Ordinal) ? key[..^6] : key;
RunChat($"/rc hotkey remove {combo}");
return combo;
}
// ── Favourites ──────────────────────────────────────────────────────────
public string ToggleFavourite(ItemRef r)
{
bool now = Data.ToggleFavourite(r);
Save();
return now ? $"{r.FullName} is a favourite." : $"{r.FullName} is no longer a favourite.";
}
/// <summary>/rdef fav: the item selected in the game.</summary>
public string ToggleSelectedFavourite()
{
uint sel = SelectedId();
if (sel == 0) return "Select a weapon in the game first.";
CarriedItem? it = FindById(sel);
if (it == null) return "The selected object isn't in your pack.";
return ToggleFavourite(ItemRef.From(it));
}
}

View file

@ -0,0 +1,42 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Items;
/// <summary>
/// One thing the character carries or wears, as the client reports it. A plain data holder: the
/// reader (HostInventory) fills it, everything else (slot matching, item kinds, the weapon picker)
/// works on it without the host, so it can be tested offline.
/// </summary>
internal sealed class CarriedItem
{
public uint Id;
public string Name = string.Empty;
public uint Wcid;
/// <summary>MaterialType (int 131): "Silver" in "Silver Wand"; 0 = none / unknown.</summary>
public int Material;
/// <summary>ItemType flags (the client's TryGetItemType).</summary>
public uint ItemType;
/// <summary>PublicWeenieDesc bitfield (healer, food ...); 0 when the engine can't read it.</summary>
public uint Bitfield;
/// <summary>Stack size (at least 1) and the largest stack (1 = not stackable).</summary>
public int Stack = 1, MaxStack = 1;
/// <summary>Uses left / most uses (Structure 92 / MaxStructure 91): kits, essences; MaxUses 0 = none.</summary>
public int Uses, MaxUses;
/// <summary>ValidLocations (int 9): the EquipMask slots it can go into; 0 = it can't be worn or wielded.</summary>
public int ValidLocations;
/// <summary>The slot it is wielded in now (0 = in a pack).</summary>
public int WieldedLocation;
/// <summary>CombatUse (int 51): 1 melee, 2 missile, 3 ammo, 4 shield, 5 two-handed.</summary>
public int CombatUse;
/// <summary>DamageType (int 45) and UiEffects (int 18): the element of a caster.</summary>
public int DamageType, UiEffects;
/// <summary>Icon, underlay and overlay texture ids (0x06......), 0 = none.</summary>
public uint Icon, Underlay, Overlay;
public bool Wielded => WieldedLocation != 0;
/// <summary>The name with the material in front ("Silver Wand"), as the character sees it in the game.</summary>
public string FullName => ItemNames.Full(Name, Material);
public override string ToString() => $"0x{Id:X8} {FullName}";
}

View file

@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Items;
/// <summary>
/// Reads what the character carries and wears from the client into <see cref="CarriedItem"/>s.
/// Plugin pump thread only. Everything comes from what the client already has (the engine's
/// object snapshot and its property caches); nothing is sent to the server.
/// GetContainerContents(player) returns the main pack's items, the side packs and the worn and
/// wielded items; each side pack's items come from GetContainerContents(pack). What an item IS
/// (name, wcid, material, kind, picture) is kept per object id once read; what changes (stack,
/// uses left, whether it is in hand) is read every time.
/// </summary>
internal sealed class HostInventory
{
// STypeInt
private const uint StackSize = 12, MaxStackSize = 11, ValidLocations = 9, CurrentWieldedLocation = 10, UiEffects = 18,
DamageType = 45, CombatUse = 51, MaterialType = 131, Structure = 92, MaxStructure = 91;
// STypeDID
private const uint DidIcon = 8, DidIconOverlay = 50, DidIconUnderlay = 52;
private const int MaxContents = 1024;
private const int MaxNesting = 3;
private const uint ItemTypeContainer = 0x200;
/// <summary>A caster whose damage type has not arrived (it comes with an identify) is read again after this.</summary>
private const long RecheckMs = 15_000;
private sealed class Static
{
public string Name = string.Empty;
public uint Wcid;
public int Material;
public uint ItemType, Bitfield;
public int MaxStack = 1, MaxUses, ValidLocations, CombatUse, DamageType, UiEffects;
public uint Icon, Underlay, Overlay;
public bool IsContainer;
public long ReadMs;
}
private readonly Dictionary<uint, Static> _static = new();
private readonly uint[] _contents = new uint[MaxContents];
public void Reset() => _static.Clear();
/// <summary>Everything carried and worn; empty when the character or its inventory isn't readable yet.</summary>
public List<CarriedItem> Read(RynthCoreHost host, long nowMs)
{
var items = new List<CarriedItem>();
if (!host.HasGetPlayerId || !host.HasGetContainerContents) return items;
uint player = host.GetPlayerId();
if (player == 0) return items;
ScanInto(host, player, player, items, 0, nowMs);
return items;
}
private void ScanInto(RynthCoreHost host, uint container, uint player, List<CarriedItem> items, int depth, long nowMs)
{
int n = host.GetContainerContents(container, _contents);
if (n <= 0) return;
uint[] ids = new uint[n];
Array.Copy(_contents, ids, n);
var packs = new List<uint>();
foreach (uint id in ids)
{
if (id == 0) continue;
Ownership(host, id, out uint c, out uint w, out uint loc);
bool worn = w == player && w != 0;
if (!worn && c != container && c != 0) continue; // moved away since the engine's snapshot
CarriedItem? it = ReadItem(host, id, nowMs, out Static? st);
if (it == null) continue;
if (worn)
{
if (loc == 0 && host.TryGetObjectIntProperty(id, CurrentWieldedLocation, out int l)) loc = unchecked((uint)l);
it.WieldedLocation = loc == 0 ? 1 : unchecked((int)loc); // worn but the slot unreadable: still "in hand"
}
else if (st!.IsContainer && depth < MaxNesting)
{
packs.Add(id);
continue; // a pack is not something to use or wield
}
items.Add(it);
}
foreach (uint pack in packs)
ScanInto(host, pack, player, items, depth + 1, nowMs);
}
/// <summary>One item as the client has it now (null if it has no name yet or is gone).</summary>
public CarriedItem? ReadOne(RynthCoreHost host, uint id, long nowMs)
{
uint player = host.HasGetPlayerId ? host.GetPlayerId() : 0;
CarriedItem? it = ReadItem(host, id, nowMs, out _);
if (it == null) return null;
Ownership(host, id, out _, out uint w, out uint loc);
if (w != 0 && w == player)
{
if (loc == 0 && host.TryGetObjectIntProperty(id, CurrentWieldedLocation, out int l)) loc = unchecked((uint)l);
it.WieldedLocation = loc == 0 ? 1 : unchecked((int)loc);
}
return it;
}
private CarriedItem? ReadItem(RynthCoreHost host, uint id, long nowMs, out Static? st)
{
st = null;
if (!_static.TryGetValue(id, out st) || Stale(st, nowMs))
{
st = ReadStatic(host, id, nowMs);
if (st == null) return null;
_static[id] = st;
}
var it = new CarriedItem
{
Id = id,
Name = st.Name,
Wcid = st.Wcid,
Material = st.Material,
ItemType = st.ItemType,
Bitfield = st.Bitfield,
MaxStack = st.MaxStack,
MaxUses = st.MaxUses,
ValidLocations = st.ValidLocations,
CombatUse = st.CombatUse,
DamageType = st.DamageType,
UiEffects = st.UiEffects,
Icon = st.Icon,
Underlay = st.Underlay,
Overlay = st.Overlay,
};
if (host.TryGetObjectIntProperty(id, StackSize, out int stack) && stack > 0) it.Stack = stack;
if (st.MaxUses > 0 && host.TryGetObjectIntProperty(id, Structure, out int uses)) it.Uses = Math.Max(0, uses);
return it;
}
private static bool Stale(Static st, long nowMs) =>
(st.ItemType & ItemKinds.TypeCaster) != 0 && st.DamageType == 0 && nowMs - st.ReadMs >= RecheckMs;
private static Static? ReadStatic(RynthCoreHost host, uint id, long nowMs)
{
if (!host.TryGetObjectName(id, out string name) || string.IsNullOrWhiteSpace(name)) return null;
var st = new Static { Name = name.Trim(), ReadMs = nowMs };
if (host.TryGetItemType(id, out uint type)) st.ItemType = type;
st.IsContainer = (st.ItemType & ItemTypeContainer) != 0;
if (host.HasGetObjectWcid && host.TryGetObjectWcid(id, out uint wcid)) st.Wcid = wcid;
if (host.HasGetObjectBitfield && host.TryGetObjectBitfield(id, out uint bf)) st.Bitfield = bf;
if (host.TryGetObjectIntProperty(id, MaterialType, out int material)) st.Material = Math.Max(0, material);
if (host.TryGetObjectIntProperty(id, MaxStackSize, out int maxStack)) st.MaxStack = Math.Max(1, maxStack);
if (host.TryGetObjectIntProperty(id, MaxStructure, out int maxUses) && maxUses > 0) st.MaxUses = maxUses;
if (host.TryGetObjectIntProperty(id, ValidLocations, out int valid)) st.ValidLocations = valid;
if (host.TryGetObjectIntProperty(id, CombatUse, out int use)) st.CombatUse = use;
if (host.TryGetObjectIntProperty(id, DamageType, out int dt)) st.DamageType = dt;
if (host.TryGetObjectIntProperty(id, UiEffects, out int fx)) st.UiEffects = fx;
if (host.HasGetObjectDataIdProperty)
{
if (host.TryGetObjectDataIdProperty(id, DidIcon, out uint icon)) st.Icon = icon;
if (host.TryGetObjectDataIdProperty(id, DidIconUnderlay, out uint under)) st.Underlay = under;
if (host.TryGetObjectDataIdProperty(id, DidIconOverlay, out uint over)) st.Overlay = over;
}
return st;
}
private static void Ownership(RynthCoreHost host, uint id, out uint container, out uint wielder, out uint location)
{
container = wielder = location = 0;
if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out container, out wielder, out location)) return;
if (host.HasGetObjectWielderInfo && host.TryGetObjectWielderInfo(id, out uint w, out uint loc)) { wielder = w; location = loc; }
}
}

View file

@ -0,0 +1,145 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Items;
/// <summary>What an item is, as far as using it goes.</summary>
internal enum ItemKind
{
/// <summary>Anything used by itself: potions, scrolls, food, gems, summons ...</summary>
Other,
/// <summary>A healing or stamina kit: used on yourself.</summary>
Kit,
Melee,
Missile,
/// <summary>A wand, staff or orb that casts war magic (any element but Nether).</summary>
WarWand,
/// <summary>A caster of Nether: void magic.</summary>
VoidWand,
Shield,
Armor,
Jewelry,
Ammo,
}
/// <summary>What pressing an item's slot does with it.</summary>
internal enum UseAction
{
/// <summary>UseObject: double-clicking it (potions, scrolls, food).</summary>
Use,
/// <summary>UseObjectOn(item, you): healing and stamina kits.</summary>
UseOnSelf,
/// <summary>UseObjectOn(item, the selected target).</summary>
UseOnSelected,
/// <summary>Wield or wear it (UseObject: the client's double-click takes what is in the way off).</summary>
Equip,
}
/// <summary>The weapon picker's groups, in the order they are listed.</summary>
internal enum WeaponGroup { Melee, Missile, WarMagic, VoidMagic, Shield, Ammo }
internal static class ItemKinds
{
// ItemType flags
public const uint TypeMelee = 0x1, TypeArmor = 0x2, TypeClothing = 0x4, TypeJewelry = 0x8, TypeMissile = 0x100, TypeCaster = 0x8000;
// PublicWeenieDesc bitfield: the healer bit
public const uint BitfieldHealer = 0x10000;
// EquipMask slots
public const int ShieldSlot = 0x00200000, AmmoSlot = 0x00800000;
// CombatUse values
public const int CombatUseAmmo = 3, CombatUseShield = 4;
// DamageType / UiEffects bits of Nether
public const int DamageNether = 0x400, EffectNether = 0x1000;
public static ItemKind Classify(CarriedItem it)
{
bool equippable = it.ValidLocations != 0;
if (!equippable)
{
if ((it.Bitfield & BitfieldHealer) != 0) return ItemKind.Kit;
// The engine couldn't read the bitfield: RynthAi's own test for the kits it uses.
if (it.Bitfield == 0 && it.Name.EndsWith(" Kit", StringComparison.OrdinalIgnoreCase)) return ItemKind.Kit;
return ItemKind.Other;
}
bool weaponClass = (it.ItemType & (TypeMelee | TypeMissile | TypeCaster)) != 0 || IsWandName(it.Name);
if (it.CombatUse == CombatUseAmmo || (it.ValidLocations & AmmoSlot) != 0) return ItemKind.Ammo;
if (it.CombatUse == CombatUseShield || (!weaponClass && (it.ValidLocations & ShieldSlot) != 0)) return ItemKind.Shield;
if ((it.ItemType & TypeCaster) != 0 || (weaponClass && (it.ItemType & (TypeMelee | TypeMissile)) == 0))
return IsNether(it) ? ItemKind.VoidWand : ItemKind.WarWand;
if ((it.ItemType & TypeMissile) != 0) return ItemKind.Missile;
if ((it.ItemType & TypeMelee) != 0) return ItemKind.Melee;
if ((it.ItemType & TypeJewelry) != 0) return ItemKind.Jewelry;
return ItemKind.Armor; // armor, clothing and anything else that is worn
}
/// <summary>What a slot does with the item when the player has set nothing else.</summary>
public static UseAction DefaultAction(ItemKind kind) => kind switch
{
ItemKind.Kit => UseAction.UseOnSelf,
ItemKind.Other => UseAction.Use,
_ => UseAction.Equip,
};
public static bool IsWeapon(ItemKind k) => k is ItemKind.Melee or ItemKind.Missile or ItemKind.WarWand or ItemKind.VoidWand;
/// <summary>The picker group of a kind, or null when the picker doesn't list it.</summary>
public static WeaponGroup? GroupOf(ItemKind k) => k switch
{
ItemKind.Melee => WeaponGroup.Melee,
ItemKind.Missile => WeaponGroup.Missile,
ItemKind.WarWand => WeaponGroup.WarMagic,
ItemKind.VoidWand => WeaponGroup.VoidMagic,
ItemKind.Shield => WeaponGroup.Shield,
ItemKind.Ammo => WeaponGroup.Ammo,
_ => null,
};
public static string Label(WeaponGroup g) => g switch
{
WeaponGroup.Melee => "Melee",
WeaponGroup.Missile => "Missile",
WeaponGroup.WarMagic => "War Magic",
WeaponGroup.VoidMagic => "Void Magic",
WeaponGroup.Shield => "Shields",
_ => "Ammunition",
};
/// <summary>A caster whose element is Nether (the damage type, the icon's glow, or the name).</summary>
public static bool IsNether(CarriedItem it) =>
(it.DamageType & DamageNether) != 0
|| (it.DamageType == 0 && (it.UiEffects & EffectNether) != 0)
|| (it.DamageType == 0 && it.UiEffects == 0 && HasWord(it.Name, "Nether", "Void"));
/// <summary>The element a caster is named or glows for, for the picker's second column ("" = none known).</summary>
public static string Element(CarriedItem it)
{
if ((it.DamageType & 0x400) != 0) return "Nether";
if ((it.DamageType & 0x10) != 0) return "Fire";
if ((it.DamageType & 0x08) != 0) return "Cold";
if ((it.DamageType & 0x40) != 0) return "Lightning";
if ((it.DamageType & 0x20) != 0) return "Acid";
int fx = it.UiEffects;
if ((fx & 0x1000) != 0) return "Nether";
if ((fx & 0x0020) != 0) return "Fire";
if ((fx & 0x0080) != 0) return "Cold";
if ((fx & 0x0040) != 0) return "Lightning";
if ((fx & 0x0100) != 0) return "Acid";
if ((fx & 0x0400) != 0) return "Slash";
if ((fx & 0x0800) != 0) return "Pierce";
if ((fx & 0x0200) != 0) return "Bludgeon";
return string.Empty;
}
public static bool IsWandName(string? name) => HasWord(name, "Orb", "Staff", "Wand", "Scepter", "Sceptre", "Baton", "Crozier");
private static bool HasWord(string? name, params string[] words)
{
if (string.IsNullOrEmpty(name)) return false;
foreach (string w in words)
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
/// <summary>A launcher needs ammunition in hand; a thrown weapon (a stack of darts) does not.</summary>
public static bool NeedsAmmo(CarriedItem it) => it.MaxStack <= 1;
}

View file

@ -0,0 +1,33 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Items;
/// <summary>Display names: a weapon's material in front of the base name the client reports.</summary>
internal static class ItemNames
{
/// <summary>ACE's MaterialType names, index = the id (0 = none).</summary>
private static readonly string[] Materials =
{
"", "Ceramic", "Porcelain", "Cloth", "Linen", "Satin", "Silk", "Velvet", "Wool", "Gem",
"Agate", "Amber", "Amethyst", "Aquamarine", "Azurite", "Black Garnet", "Black Opal", "Bloodstone", "Carnelian", "Citrine",
"Diamond", "Emerald", "Fire Opal", "Green Garnet", "Green Jade", "Hematite", "Imperial Topaz", "Jet", "Lapis Lazuli", "Lavender Jade",
"Malachite", "Moonstone", "Onyx", "Opal", "Peridot", "Red Garnet", "Red Jade", "Rose Quartz", "Ruby", "Sapphire",
"Smokey Quartz", "Sunstone", "Tiger Eye", "Tourmaline", "Turquoise", "White Jade", "White Quartz", "White Sapphire", "Yellow Garnet", "Yellow Topaz",
"Zircon", "Ivory", "Leather", "Armoredillo Hide", "Gromnie Hide", "Reed Shark Hide", "Metal", "Brass", "Bronze", "Copper",
"Gold", "Iron", "Pyreal", "Silver", "Steel", "Stone", "Alabaster", "Granite", "Marble", "Obsidian",
"Sandstone", "Serpentine", "Wood", "Ebony", "Mahogany", "Oak", "Pine", "Teak",
};
public static string Material(int id) => id > 0 && id < Materials.Length ? Materials[id] : string.Empty;
/// <summary>"Silver Wand": the material in front, unless the name already starts with it.</summary>
public static string Full(string? baseName, int material)
{
string name = (baseName ?? string.Empty).Trim();
string mat = Material(material);
if (mat.Length == 0 || name.Length == 0) return name;
if (name.StartsWith(mat + " ", StringComparison.OrdinalIgnoreCase) || name.Equals(mat, StringComparison.OrdinalIgnoreCase))
return name;
return mat + " " + name;
}
}

View file

@ -0,0 +1,85 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection }
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | panels (the game panel buttons) | selection]";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
public static DefCommand Parse(string? args)
{
string a = (args ?? string.Empty).Trim();
if (a.Length == 0) return new DefCommand(DefVerb.Toggle);
int sp = a.IndexOf(' ');
string verb = (sp < 0 ? a : a[..sp]).ToLowerInvariant();
string rest = sp < 0 ? string.Empty : a[(sp + 1)..].Trim();
switch (verb)
{
case "help": case "?": return new DefCommand(DefVerb.Help);
case "list": case "ls": return new DefCommand(DefVerb.List);
case "status": return new DefCommand(DefVerb.Status);
case "panels": case "panel": return new DefCommand(DefVerb.Panels);
case "selection": case "target":
// "/rdef selection 0x80001234": select that object (a test hook for the Selection window).
return new DefCommand(DefVerb.Selection, Text: rest);
case "fav": case "favourite": case "favorite": return new DefCommand(DefVerb.Favourite);
case "weapons": case "weapon": case "picker": return new DefCommand(DefVerb.Weapons, Text: rest);
case "use": case "wield": case "equip":
if (rest.Length == 0) return Fail($"Use which slot or item? e.g. /rdef use 1 or /rdef use Peerless Healing Kit");
return TrySlot(rest, out int n) ? new DefCommand(DefVerb.Use, n) : new DefCommand(DefVerb.Use, Text: rest);
case "set":
{
SplitSlot(rest, out string? slotText, out string tail);
if (slotText == null || !TrySlot(slotText, out int slot)) return Fail("Which slot? e.g. /rdef set 3 (the item selected in the game goes in slot 3) or /rdef set 3 Peerless Healing Kit");
return new DefCommand(DefVerb.Set, slot, tail);
}
case "clear":
{
return TrySlot(rest, out int slot) ? new DefCommand(DefVerb.Clear, slot) : Fail("Which slot? e.g. /rdef clear 3");
}
case "bind":
{
SplitSlot(rest, out string? slotText, out string key);
if (slotText == null || !TrySlot(slotText, out int slot) || key.Length == 0)
return Fail("Usage: /rdef bind <slot> <key>, e.g. /rdef bind 3 F9 or /rdef bind 3 Ctrl+1");
return new DefCommand(DefVerb.Bind, slot, key);
}
case "unbind":
return TrySlot(rest, out int us) ? new DefCommand(DefVerb.Unbind, us) : Fail("Which slot? e.g. /rdef unbind 3");
case "slots":
return int.TryParse(rest, out int count) && count >= DefSettings.SlotsMin && count <= DefSettings.SlotsMax
? new DefCommand(DefVerb.Slots, count)
: Fail($"How many slots? {DefSettings.SlotsMin} to {DefSettings.SlotsMax}, e.g. /rdef slots 10");
default:
// "/rdef Stamina Kit" is a shorthand for use.
return new DefCommand(DefVerb.Use, Text: a);
}
}
/// <summary>The slot number a hotkey runs for slot <paramref name="slot"/> (1-based).</summary>
public static string UseCommand(int slot) => "/rdef use " + slot;
private static bool TrySlot(string text, out int slot)
{
slot = 0;
return int.TryParse(text.Trim(), out slot) && slot >= 1 && slot <= DefSettings.SlotsMax;
}
private static void SplitSlot(string rest, out string? first, out string tail)
{
int sp = rest.IndexOf(' ');
first = rest.Length == 0 ? null : (sp < 0 ? rest : rest[..sp]);
tail = sp < 0 ? string.Empty : rest[(sp + 1)..].Trim();
}
private static DefCommand Fail(string error) => new(DefVerb.Error, Error: error);
}

View file

@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One slot of the bar: an item (or nothing) and how pressing it uses that item.</summary>
internal sealed class DefSlot
{
/// <summary>The item the slot holds; null = empty.</summary>
public ItemRef? Item;
/// <summary>How pressing it uses the item. <see cref="UseMode.Auto"/> picks by what the item is.</summary>
public UseMode Mode = UseMode.Auto;
public bool Empty => Item == null;
public DefSlot Clone() => new() { Item = Item?.Clone(), Mode = Mode };
}
/// <summary>The "use as" choice of a slot.</summary>
internal enum UseMode { Auto, Use, OnSelf, OnSelected, Equip }
internal static class UseModes
{
public static readonly string[] Labels =
{
"Automatic (by item)", "Use it", "Use it on me", "Use it on the selected target", "Wield / wear it",
};
/// <summary>The action for a slot's mode and the item's kind.</summary>
public static UseAction ActionFor(UseMode mode, ItemKind kind) => mode switch
{
UseMode.Use => UseAction.Use,
UseMode.OnSelf => UseAction.UseOnSelf,
UseMode.OnSelected => UseAction.UseOnSelected,
UseMode.Equip => UseAction.Equip,
_ => ItemKinds.DefaultAction(kind),
};
public static string Describe(UseAction a) => a switch
{
UseAction.Use => "used",
UseAction.UseOnSelf => "used on you",
UseAction.UseOnSelected => "used on the selected target",
_ => "wielded",
};
}
/// <summary>The kind of weapon the picker is narrowed to.</summary>
internal enum KindFilter { All, Melee, Missile, War, Void }
/// <summary>RynthDefective's settings for one character.</summary>
internal sealed class DefSettings
{
public const int SlotsMin = 1, SlotsMax = 24, PerRowMin = 1, PerRowMax = 12, ButtonMin = 20, ButtonMax = 64,
PickerIconMin = 20, PickerIconMax = 48;
/// <summary>
/// The shortcut bar (2026-10-22, plugin API v90): its first 18 slots are AC's own (the retail
/// toolbar's, its keys AC's keymap), the rest this plugin's own slots (Slots, keys the engine's
/// hotkeys). The player picks how many it shows.
/// </summary>
public const int RetailSlots = 18, BarSlotsMin = 1, BarSlotsMax = RetailSlots + SlotsMax;
public int BarSlots = RetailSlots;
public int SlotCount = 8;
public int SlotsPerRow = 8;
/// <summary>Icon size of the slot buttons, in logical units.</summary>
public int ButtonSize = 36;
/// <summary>Icon size in the weapon picker's rows.</summary>
public int PickerIconSize = 32;
public bool ShowIcons = true;
/// <summary>Counts and uses left under the slot buttons.</summary>
public bool ShowCounts = true;
/// <summary>The weapon kind the picker shows; All = every kind.</summary>
public KindFilter PreferredKind = KindFilter.All;
/// <summary>Weapon swaps are refused while RynthAi's macro runs (it picks the weapon itself); this lets them through.</summary>
public bool SwapWhileBotRuns;
public bool BarOpen;
public bool PickerOpen;
public void Clamp()
{
SlotCount = Math.Clamp(SlotCount, SlotsMin, SlotsMax);
BarSlots = Math.Clamp(BarSlots, BarSlotsMin, BarSlotsMax);
SlotsPerRow = Math.Clamp(SlotsPerRow, PerRowMin, PerRowMax);
ButtonSize = Math.Clamp(ButtonSize, ButtonMin, ButtonMax);
PickerIconSize = Math.Clamp(PickerIconSize, PickerIconMin, PickerIconMax);
if (!Enum.IsDefined(PreferredKind)) PreferredKind = KindFilter.All;
}
}
/// <summary>One character's slots, favourites, recent weapons and settings.</summary>
internal sealed class DefData
{
public const int MaxFavourites = 64, MaxRecent = 8;
public DefSettings Settings = new();
/// <summary>Always <see cref="DefSettings.SlotsMax"/> entries: shrinking the bar hides slots, it doesn't forget them.</summary>
public List<DefSlot> Slots = NewSlots();
public List<ItemRef> Favourites = new();
/// <summary>The weapons wielded from the picker or a slot, newest first.</summary>
public List<ItemRef> Recent = new();
public static List<DefSlot> NewSlots()
{
var l = new List<DefSlot>(DefSettings.SlotsMax);
for (int i = 0; i < DefSettings.SlotsMax; i++) l.Add(new DefSlot());
return l;
}
/// <summary>Pads or cuts the slot list to the fixed length.</summary>
public void FixLength()
{
while (Slots.Count < DefSettings.SlotsMax) Slots.Add(new DefSlot());
if (Slots.Count > DefSettings.SlotsMax) Slots.RemoveRange(DefSettings.SlotsMax, Slots.Count - DefSettings.SlotsMax);
}
public bool IsFavourite(ItemRef r) => Favourites.Exists(f => f.SameAs(r));
/// <summary>Adds or removes a favourite; returns whether it is one now.</summary>
public bool ToggleFavourite(ItemRef r)
{
int i = Favourites.FindIndex(f => f.SameAs(r));
if (i >= 0) { Favourites.RemoveAt(i); return false; }
if (Favourites.Count >= MaxFavourites) return false;
Favourites.Add(r.Clone());
return true;
}
/// <summary>Puts a weapon first in the recent list (once), at most <see cref="MaxRecent"/>.</summary>
public void NoteRecent(ItemRef r)
{
Recent.RemoveAll(x => x.SameAs(r));
Recent.Insert(0, r.Clone());
if (Recent.Count > MaxRecent) Recent.RemoveRange(MaxRecent, Recent.Count - MaxRecent);
}
/// <summary>The slot (1-based number) that holds an item of this identity, or 0.</summary>
public int SlotOf(ItemRef r)
{
for (int i = 0; i < Slots.Count; i++)
if (Slots[i].Item is { } x && x.SameAs(r)) return i + 1;
return 0;
}
}

View file

@ -0,0 +1,246 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// Per-character files: &lt;SuiteDir&gt;\RynthDefective\characters\&lt;server_character&gt;.json, written by
/// hand and read with JsonDocument (plugin types never go through System.Text.Json's serializer,
/// which roots them across hot reloads). A broken or odd file reads as defaults for whatever is
/// wrong in it; the next save rewrites it.
/// </summary>
internal sealed class DefStore
{
/// <summary>RynthDefective's folder (tests point it at a temp folder).</summary>
public string Root;
public DefStore()
{
Root = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthDefective");
}
public DefStore(string root) => Root = root;
/// <summary>"server_character" made safe as a file name (the same rule RynthSort and RynthLua use).</summary>
public static string FileStem(string server, string character) => SafeFileName($"{server}_{character}");
public string PathFor(string server, string character) => Path.Combine(Root, "characters", FileStem(server, character) + ".json");
/// <summary>The character's data; defaults for a new character or a broken file (<paramref name="problem"/> says which).</summary>
public DefData Load(string server, string character, out string? problem)
{
problem = null;
string path = PathFor(server, character);
if (!File.Exists(path)) return new DefData();
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path),
new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
return Parse(doc.RootElement);
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException)
{
problem = $"{Path.GetFileName(path)}: {ex.Message}";
return new DefData();
}
}
internal static DefData Parse(JsonElement root)
{
if (root.ValueKind != JsonValueKind.Object) throw new JsonException("the file isn't a JSON object");
var d = new DefData();
if (root.TryGetProperty("settings", out JsonElement s) && s.ValueKind == JsonValueKind.Object)
{
DefSettings st = d.Settings;
st.SlotCount = Int(s, "slotCount", st.SlotCount);
st.BarSlots = Int(s, "barSlots", st.BarSlots);
st.SlotsPerRow = Int(s, "slotsPerRow", st.SlotsPerRow);
st.ButtonSize = Int(s, "buttonSize", st.ButtonSize);
st.PickerIconSize = Int(s, "pickerIconSize", st.PickerIconSize);
st.ShowIcons = Bool(s, "showIcons", st.ShowIcons);
st.ShowCounts = Bool(s, "showCounts", st.ShowCounts);
st.PreferredKind = (KindFilter)Int(s, "preferredKind", (int)st.PreferredKind);
st.SwapWhileBotRuns = Bool(s, "swapWhileBotRuns", st.SwapWhileBotRuns);
st.BarOpen = Bool(s, "barOpen", st.BarOpen);
st.PickerOpen = Bool(s, "pickerOpen", st.PickerOpen);
st.Clamp();
}
if (root.TryGetProperty("slots", out JsonElement slots) && slots.ValueKind == JsonValueKind.Array)
{
int i = 0;
foreach (JsonElement e in slots.EnumerateArray())
{
if (i >= DefSettings.SlotsMax) break;
DefSlot slot = d.Slots[i++];
if (e.ValueKind != JsonValueKind.Object) continue;
slot.Item = ParseRef(e, "item");
int mode = Int(e, "mode", 0);
slot.Mode = mode >= 0 && mode <= (int)UseMode.Equip ? (UseMode)mode : UseMode.Auto;
}
}
ParseRefs(root, "favourites", d.Favourites, DefData.MaxFavourites);
ParseRefs(root, "recent", d.Recent, DefData.MaxRecent);
return d;
}
private static void ParseRefs(JsonElement root, string name, List<ItemRef> into, int max)
{
if (!root.TryGetProperty(name, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return;
foreach (JsonElement e in arr.EnumerateArray())
{
if (into.Count >= max) break;
ItemRef? r = ParseRefObject(e);
if (r != null) into.Add(r);
}
}
private static ItemRef? ParseRef(JsonElement owner, string name) =>
owner.TryGetProperty(name, out JsonElement e) ? ParseRefObject(e) : null;
private static ItemRef? ParseRefObject(JsonElement e)
{
if (e.ValueKind != JsonValueKind.Object) return null;
string name = Str(e, "name");
if (name.Length == 0) return null; // an item with no name can't be found again
return new ItemRef
{
Id = UInt(e, "id"),
Name = name,
Wcid = UInt(e, "wcid"),
Material = Int(e, "material", 0),
Icon = UInt(e, "icon"),
Underlay = UInt(e, "underlay"),
Overlay = UInt(e, "overlay"),
};
}
/// <summary>Writes the character's file (temp file, then moved over the old one). Returns an error or null.</summary>
public string? Save(string server, string character, DefData d)
{
string path = PathFor(server, character);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, ToJson(d), new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
internal static string ToJson(DefData d)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
w.WriteStartObject("settings");
DefSettings s = d.Settings;
w.WriteNumber("slotCount", s.SlotCount);
w.WriteNumber("barSlots", s.BarSlots);
w.WriteNumber("slotsPerRow", s.SlotsPerRow);
w.WriteNumber("buttonSize", s.ButtonSize);
w.WriteNumber("pickerIconSize", s.PickerIconSize);
w.WriteBoolean("showIcons", s.ShowIcons);
w.WriteBoolean("showCounts", s.ShowCounts);
w.WriteNumber("preferredKind", (int)s.PreferredKind);
w.WriteBoolean("swapWhileBotRuns", s.SwapWhileBotRuns);
w.WriteBoolean("barOpen", s.BarOpen);
w.WriteBoolean("pickerOpen", s.PickerOpen);
w.WriteEndObject();
w.WriteStartArray("slots");
foreach (DefSlot slot in d.Slots)
{
w.WriteStartObject();
if (slot.Item != null) WriteRef(w, "item", slot.Item);
w.WriteNumber("mode", (int)slot.Mode);
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteStartArray("favourites");
foreach (ItemRef r in d.Favourites) WriteRefValue(w, r);
w.WriteEndArray();
w.WriteStartArray("recent");
foreach (ItemRef r in d.Recent) WriteRefValue(w, r);
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray()) + "\n";
}
private static void WriteRef(Utf8JsonWriter w, string name, ItemRef r)
{
w.WritePropertyName(name);
WriteRefValue(w, r);
}
private static void WriteRefValue(Utf8JsonWriter w, ItemRef r)
{
w.WriteStartObject();
w.WriteNumber("id", r.Id);
w.WriteString("name", r.Name);
if (r.Wcid != 0) w.WriteNumber("wcid", r.Wcid);
if (r.Material != 0) w.WriteNumber("material", r.Material);
if (r.Icon != 0) w.WriteNumber("icon", r.Icon);
if (r.Underlay != 0) w.WriteNumber("underlay", r.Underlay);
if (r.Overlay != 0) w.WriteNumber("overlay", r.Overlay);
w.WriteEndObject();
}
private static bool Bool(JsonElement o, string name, bool fallback) =>
o.TryGetProperty(name, out JsonElement v) && (v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
? v.GetBoolean()
: fallback;
private static string Str(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? string.Empty).Trim() : string.Empty;
private static uint UInt(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return 0;
if (v.TryGetUInt32(out uint u)) return u;
return v.TryGetDouble(out double dbl) && dbl >= 0 && dbl <= uint.MaxValue && dbl == Math.Floor(dbl) ? (uint)dbl : 0;
}
private static int Int(JsonElement o, string name, int fallback)
{
if (!o.TryGetProperty(name, out JsonElement v) || v.ValueKind != JsonValueKind.Number) return fallback;
if (v.TryGetInt32(out int i)) return i;
return v.TryGetDouble(out double dbl) && dbl >= int.MinValue && dbl <= int.MaxValue ? (int)Math.Round(dbl) : fallback;
}
private static readonly HashSet<string> ReservedNames = new(StringComparer.OrdinalIgnoreCase)
{
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$",
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
};
/// <summary>RynthLua's LibraryStorage.SafeFileName, so the suite names a character's file one way.</summary>
public static string SafeFileName(string? name)
{
var invalid = Path.GetInvalidFileNameChars();
var chars = (name ?? string.Empty).Trim().ToCharArray();
for (int i = 0; i < chars.Length; i++)
if (Array.IndexOf(invalid, chars[i]) >= 0 || chars[i] < 32) chars[i] = '_';
string n = new string(chars).TrimEnd('.', ' ');
if (n.Length > 80) n = n[..80].TrimEnd('.', ' ');
if (n.Length == 0 || n.Trim('.').Length == 0) n = "_" + n;
string stem = n.Split('.')[0];
if (ReservedNames.Contains(stem)) n = "_" + n;
return n;
}
}

View file

@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// Which keys the engine's hotkey system has bound to a chat command, read from its file
/// (%LOCALAPPDATA%\RynthCore\hotkeys.txt, one binding a line: "on|off TAB combo TAB command TAB text",
/// the action "command" for a chat command). Read only: the plugin adds and removes bindings by
/// typing "/rc hotkey add|remove ..." to the engine, never by writing the file. The file is
/// shared by every client on the PC and the engine picks up changes within 2 s, so a binding
/// shows here a moment after it was made.
/// </summary>
internal sealed class HotkeyLookup
{
public const string EnvOverride = "RYNTHCORE_HOTKEYS_FILE";
private readonly Func<string> _path;
private DateTime _stamp = DateTime.MinValue;
private long _nextCheckMs;
private List<(string Combo, string Command, bool On)> _bindings = new();
public HotkeyLookup() : this(DefaultPath) { }
public HotkeyLookup(Func<string> path) => _path = path;
public static string DefaultPath()
{
if (Environment.GetEnvironmentVariable(EnvOverride) is { Length: > 0 } p) return p;
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(root, "RynthCore", "hotkeys.txt");
}
/// <summary>The combo bound to exactly this chat command ("/rdef use 3"), or null. Looks at the file at most once a second.</summary>
public string? KeyFor(string command, long nowMs)
{
Refresh(nowMs);
string want = Normalize(command);
foreach (var b in _bindings)
if (b.On && b.Command == want) return b.Combo;
foreach (var b in _bindings)
if (b.Command == want) return b.Combo + " (off)";
return null;
}
/// <summary>Forget what was read: the next lookup reads the file again.</summary>
public void Invalidate() { _stamp = DateTime.MinValue; _nextCheckMs = 0; }
private void Refresh(long nowMs)
{
if (nowMs < _nextCheckMs) return;
_nextCheckMs = nowMs + 1000;
try
{
string path = _path();
if (!File.Exists(path))
{
_bindings = new();
_stamp = DateTime.MinValue;
return;
}
DateTime stamp = File.GetLastWriteTimeUtc(path);
if (stamp == _stamp) return;
_stamp = stamp;
_bindings = Parse(File.ReadAllText(path));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The engine is writing it right now: the old list stays, the next look tries again.
}
}
internal static List<(string Combo, string Command, bool On)> Parse(string? text)
{
var list = new List<(string, string, bool)>();
if (string.IsNullOrEmpty(text)) return list;
foreach (string raw in text.Split('\n'))
{
string line = raw.TrimEnd('\r');
if (line.Trim().Length == 0 || line.TrimStart().StartsWith('#')) continue;
string[] f = line.Split('\t', 4);
if (f.Length < 4) continue;
if (!f[2].Trim().Equals("command", StringComparison.OrdinalIgnoreCase)) continue;
string combo = f[1].Trim();
if (combo.Length == 0) continue;
list.Add((combo, Normalize(f[3]), !f[0].Trim().Equals("off", StringComparison.OrdinalIgnoreCase)));
}
return list;
}
private static string Normalize(string command) =>
string.Join(' ', (command ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToLowerInvariant();
}

View file

@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// One item identity, as a slot, a favourite or a recent weapon keeps it: the object id it was
/// last seen with, and what the item IS (name, wcid, material) so another carried item of the same
/// identity can stand in when the object is gone (a used-up kit stack, a replaced weapon). The
/// icon ids are the last ones seen, to draw the item dimmed while none is carried.
/// </summary>
internal sealed class ItemRef
{
public uint Id;
public string Name = string.Empty;
public uint Wcid;
public int Material;
public uint Icon, Underlay, Overlay;
public static ItemRef From(CarriedItem it)
{
var r = new ItemRef();
r.CopyFrom(it);
return r;
}
/// <summary>Takes the item's identity and picture (the slot follows the item it is bound to).</summary>
public void CopyFrom(CarriedItem it)
{
Id = it.Id;
Name = it.Name;
Wcid = it.Wcid;
Material = it.Material;
if (it.Icon != 0) { Icon = it.Icon; Underlay = it.Underlay; Overlay = it.Overlay; }
}
public ItemRef Clone() => (ItemRef)MemberwiseClone();
public string FullName => ItemNames.Full(Name, Material);
/// <summary>
/// Whether <paramref name="it"/> is this item or another of the same kind: the same name (any
/// case), and the same wcid and material wherever both sides know them. The id is not part of
/// it - that is how a stack that was used up is replaced by the next one.
/// </summary>
public bool Matches(CarriedItem it)
{
if (!string.Equals(Name, it.Name, StringComparison.OrdinalIgnoreCase)) return false;
if (Wcid != 0 && it.Wcid != 0 && Wcid != it.Wcid) return false;
if (Material != 0 && it.Material != 0 && Material != it.Material) return false;
return true;
}
/// <summary>Two references to the same thing (the same id, or the same identity).</summary>
public bool SameAs(ItemRef other) =>
(Id != 0 && Id == other.Id) || (string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& Wcid == other.Wcid && Material == other.Material);
}
/// <summary>What a slot shows: the item it is bound to now, how many of it there are, and its state.</summary>
internal readonly record struct SlotStatus(CarriedItem? Item, int Count, int Uses, bool Rebound)
{
public bool Missing => Item == null;
}
/// <summary>Finding the carried item for a reference, and the counts a slot shows.</summary>
internal static class ItemMatcher
{
/// <summary>
/// The carried item for <paramref name="r"/>: the very object when it is still carried (and still
/// the same kind of item - an id can be reused), else another item of the same identity:
/// not wielded before wielded, then the smaller stack (a used-up stack is gone sooner and the
/// pack stays tidier), then the lower id. Null when nothing matches.
/// </summary>
public static CarriedItem? Find(ItemRef r, IReadOnlyList<CarriedItem> items, out bool rebound)
{
rebound = false;
if (string.IsNullOrEmpty(r.Name)) return null;
CarriedItem? best = null;
foreach (CarriedItem it in items)
{
if (!r.Matches(it)) continue;
if (it.Id == r.Id) return it;
if (best == null || Better(it, best)) best = it;
}
rebound = best != null;
return best;
}
private static bool Better(CarriedItem a, CarriedItem b)
{
if (a.Wielded != b.Wielded) return !a.Wielded;
if (a.Stack != b.Stack) return a.Stack < b.Stack;
return a.Id < b.Id;
}
/// <summary>The slot's item, how many of it are carried (stack sizes added up) and the uses left on them all.</summary>
public static SlotStatus Status(ItemRef r, IReadOnlyList<CarriedItem> items)
{
CarriedItem? it = Find(r, items, out bool rebound);
if (it == null) return new SlotStatus(null, 0, 0, false);
int count = 0, uses = 0;
foreach (CarriedItem other in items)
{
if (!r.Matches(other)) continue;
count += Math.Max(1, other.Stack);
if (other.MaxUses > 0) uses += Math.Max(0, other.Uses);
}
return new SlotStatus(it, count, uses, rebound);
}
/// <summary>
/// Keeps a slot's reference up to date with what is carried: bound to the object found (a
/// replacement after the old one is gone), with that object's name, picture and so on. A
/// missing item changes nothing. Returns whether the reference changed (the caller saves).
/// </summary>
public static bool Maintain(ItemRef r, IReadOnlyList<CarriedItem> items)
{
CarriedItem? it = Find(r, items, out _);
if (it == null) return false;
uint id = r.Id, icon = r.Icon, under = r.Underlay, over = r.Overlay;
int material = r.Material;
uint wcid = r.Wcid;
r.CopyFrom(it);
return id != r.Id || icon != r.Icon || under != r.Underlay || over != r.Overlay || material != r.Material || wcid != r.Wcid;
}
/// <summary>
/// Finds an item by what the player typed (/rdef use Peerless Healing Kit): the full name, the
/// name, then names that start with the text, then ones that contain it (every word); the
/// first by the same order as <see cref="Find"/>.
/// </summary>
public static CarriedItem? FindByName(string text, IReadOnlyList<CarriedItem> items)
{
string q = (text ?? string.Empty).Trim();
if (q.Length == 0) return null;
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
CarriedItem? best = null;
int bestRank = int.MaxValue;
foreach (CarriedItem it in items)
{
int rank = NameRank(it, q, words);
if (rank == int.MaxValue) continue;
if (best == null || rank < bestRank || (rank == bestRank && Better(it, best)))
{
best = it;
bestRank = rank;
}
}
return best;
}
private static int NameRank(CarriedItem it, string q, string[] words)
{
string full = it.FullName;
if (string.Equals(full, q, StringComparison.OrdinalIgnoreCase)) return 0;
if (string.Equals(it.Name, q, StringComparison.OrdinalIgnoreCase)) return 1;
if (full.StartsWith(q, StringComparison.OrdinalIgnoreCase) || it.Name.StartsWith(q, StringComparison.OrdinalIgnoreCase)) return 2;
foreach (string w in words)
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return int.MaxValue;
return 3;
}
}

View file

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One line of the "pick from your pack" list: an item kind and how many of it are carried.</summary>
internal sealed record PackChoice(CarriedItem Item, int Count);
internal static class PackList
{
/// <summary>
/// The carried items for a slot to choose from: one line per kind of item (the same name, wcid
/// and material), with the stack sizes added up, A-Z, narrowed by the search words (all of them
/// must be in the name). At most <paramref name="max"/> lines; <paramref name="total"/> says how many matched.
/// </summary>
public static List<PackChoice> Build(IReadOnlyList<CarriedItem> items, string search, int max, out int total)
{
string[] words = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
var byKind = new Dictionary<string, (CarriedItem Rep, int Count)>(StringComparer.OrdinalIgnoreCase);
foreach (CarriedItem it in items)
{
string full = it.FullName;
bool all = true;
foreach (string w in words)
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) { all = false; break; }
if (!all) continue;
string key = $"{full}|{it.Wcid}";
if (byKind.TryGetValue(key, out var have))
{
// The representative: not in hand, then the smaller stack (what a slot would pick).
CarriedItem rep = have.Rep;
if ((rep.Wielded && !it.Wielded) || (rep.Wielded == it.Wielded && it.Stack < rep.Stack)) rep = it;
byKind[key] = (rep, have.Count + Math.Max(1, it.Stack));
}
else byKind[key] = (it, Math.Max(1, it.Stack));
}
var list = new List<PackChoice>(byKind.Count);
foreach (var kv in byKind) list.Add(new PackChoice(kv.Value.Rep, kv.Value.Count));
list.Sort((a, b) => string.Compare(a.Item.FullName, b.Item.FullName, StringComparison.OrdinalIgnoreCase));
total = list.Count;
if (list.Count > max) list.RemoveRange(max, list.Count - max);
return list;
}
}

View file

@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthDefective.Items;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>One row of the weapon picker.</summary>
internal sealed record PickerRow(CarriedItem Item, WeaponGroup Group, string Element, bool InHand, bool Favourite);
/// <summary>A picker group: a kind of weapon and the rows under it.</summary>
internal sealed record PickerGroup(WeaponGroup Group, List<PickerRow> Rows);
/// <summary>What the picker shows: favourites and recent weapons first, then every kind.</summary>
internal sealed class PickerModel
{
public List<PickerRow> Favourites = new();
public List<PickerRow> Recent = new();
public List<PickerGroup> Groups = new();
/// <summary>Weapons carried (before the search and kind filter).</summary>
public int Total;
/// <summary>Rows that passed the search and the kind filter.</summary>
public int Shown;
}
/// <summary>
/// The weapon picker's list, pure: the carried weapons and wands grouped by kind (melee, missile,
/// war magic, void magic, then shields and ammunition), narrowed by the search words and the kind
/// filter. Favourites and the recently wielded come first, as shortcuts: they are also listed under
/// their kind, so a weapon is always where its kind says. Inside a group, A-Z by full name.
/// </summary>
internal static class WeaponPicker
{
public static PickerModel Build(IReadOnlyList<CarriedItem> items, IReadOnlyList<ItemRef> favourites,
IReadOnlyList<ItemRef> recent, string search, KindFilter filter)
{
var model = new PickerModel();
string[] words = (search ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
var rows = new List<PickerRow>();
foreach (CarriedItem it in items)
{
ItemKind kind = ItemKinds.Classify(it);
if (ItemKinds.GroupOf(kind) is not { } group) continue;
model.Total++;
if (!PassesFilter(group, filter)) continue;
if (!MatchesSearch(it, group, words)) continue;
rows.Add(new PickerRow(it, group, ItemKinds.Element(it), it.Wielded, IsFavourite(it, favourites)));
}
model.Shown = rows.Count;
rows.Sort(CompareRows);
foreach (WeaponGroup g in Enum.GetValues<WeaponGroup>())
{
var inGroup = rows.Where(r => r.Group == g).ToList();
if (inGroup.Count > 0) model.Groups.Add(new PickerGroup(g, inGroup));
}
// Shortcuts keep their own order: favourites as the player listed them, recent newest first.
foreach (ItemRef f in favourites)
AddFirstMatch(model.Favourites, rows, f);
foreach (ItemRef r in recent)
AddFirstMatch(model.Recent, rows, r);
return model;
}
private static void AddFirstMatch(List<PickerRow> into, List<PickerRow> rows, ItemRef r)
{
PickerRow? best = null;
foreach (PickerRow row in rows)
{
if (!r.Matches(row.Item)) continue;
if (row.Item.Id == r.Id) { best = row; break; }
best ??= row;
}
if (best != null && !into.Contains(best)) into.Add(best);
}
public static bool IsFavourite(CarriedItem it, IReadOnlyList<ItemRef> favourites)
{
foreach (ItemRef f in favourites)
if (f.Id == it.Id || f.Matches(it)) return true;
return false;
}
private static bool PassesFilter(WeaponGroup g, KindFilter f) => f switch
{
KindFilter.Melee => g == WeaponGroup.Melee,
KindFilter.Missile => g == WeaponGroup.Missile || g == WeaponGroup.Ammo,
KindFilter.War => g == WeaponGroup.WarMagic,
KindFilter.Void => g == WeaponGroup.VoidMagic,
_ => true,
};
/// <summary>Every search word is in the weapon's full name, its element or its kind's label.</summary>
private static bool MatchesSearch(CarriedItem it, WeaponGroup group, string[] words)
{
if (words.Length == 0) return true;
string full = it.FullName;
string element = ItemKinds.Element(it);
string label = ItemKinds.Label(group);
foreach (string w in words)
{
if (full.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
if (element.Length > 0 && element.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
if (label.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) continue;
return false;
}
return true;
}
private static int CompareRows(PickerRow a, PickerRow b)
{
int c = string.Compare(a.Item.FullName, b.Item.FullName, StringComparison.OrdinalIgnoreCase);
return c != 0 ? c : a.Item.Id.CompareTo(b.Item.Id);
}
public static string KindLabel(KindFilter f) => f switch
{
KindFilter.Melee => "Melee",
KindFilter.Missile => "Missile",
KindFilter.War => "War",
KindFilter.Void => "Void",
_ => "All",
};
}

View file

@ -0,0 +1,103 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
/// <summary>
/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take
/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs.
/// RynthDefective draws through the engine's script windows (host calls from its own tick), so it
/// exports no render callback and keeps no buffer the engine reads later.
/// </summary>
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<RynthDefectivePlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
// UTF-8 literals live in the module's read-only data: nothing to allocate or free.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => LiteralPointer("RynthDefective"u8);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
{
fixed (byte* p = literal)
return (IntPtr)p;
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) =>
Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// ── The shortcut bar's window (plugin API v90; RynthDefectivePlugin.Bar.cs) ──
private static string? _sectionsJson;
private static IntPtr _sectionsPtr;
/// <summary>The sections manifest (polled every ~2 s): the bar's window. Kept until it changes.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSectionsJson()
{
try
{
RynthDefectivePlugin? plugin = Runtime.Plugin;
if (plugin == null) return IntPtr.Zero;
string json = plugin.SectionsJson();
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
_sectionsJson = json;
IntPtr fresh = Marshal.StringToCoTaskMemUTF8(json);
IntPtr old = System.Threading.Interlocked.Exchange(ref _sectionsPtr, fresh);
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
return fresh;
}
catch { return IntPtr.Zero; }
}
/// <summary>The bar's and the panel buttons' window bodies ("window:bar", "window:panels"; ":popout" when popped out). 1 drawn, 0 not ready, -2 failed.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
{
try
{
if (surface == null) return 0;
string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty;
bool popped = name.EndsWith(":popout", StringComparison.Ordinal);
if (popped) name = name[..^":popout".Length];
RynthDefectivePlugin? plugin = Runtime.Plugin;
if (plugin == null) return 0;
int result;
float wantH;
if (name == RynthDefectivePlugin.BarSurface) result = plugin.RenderBar(popped, out wantH);
else if (name == RynthDefectivePlugin.PanelsSurface) result = plugin.RenderPanels(out wantH);
else if (name == RynthDefectivePlugin.SelectionSurface) result = plugin.RenderSelection(out wantH);
else return 0;
if (result != 1) return result;
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = wantH > 0 ? wantH : height;
return 1;
}
catch { return 0; }
}
}

View file

@ -0,0 +1,93 @@
# RynthDefective
An item bar for RynthCore with one-touch use, and a fast weapon picker. Version 0.1.0.
Credit: RynthDefective is an independent implementation of the ideas of **Defective**, the Decal
item-bar plugin written by Hazridi and modified by Aun (<https://github.com/aunrela/Defective>). It
contains no code from it: it was written from the plugin's public feature description
against RynthCore's own APIs. (Defective's repository states no licence; ask Aun if you want a
literal port or shared code.)
## What it does
**Slots.** The bar is a row (or grid) of slots, each holding one item: a healing kit, a stamina kit,
a potion, a scroll, a weapon, a wand, a shield... Click a slot, or press its key, and the item is used
**without selecting anything in the game**:
| Item | What a press does |
| --- | --- |
| Healing / stamina kit | used on yourself |
| Potion, scroll, food, gem, anything else | used (a double-click) |
| Weapon, wand, shield, armor, jewelry | wielded / worn (a double-click); an item already in hand is left alone |
A slot can be set to another way: use it, use it on me, use it on the selected target, or wield it.
**Put an item in a slot** (Edit slots in the bar): *Set from selected* takes the item you have selected
in the game, or *Pick from pack* chooses from a searchable list of what you carry. `/rdef set 3` does the
first, `/rdef set 3 Health Potion` the second.
**A slot keeps the item's identity, not just the object.** It remembers the item's name, wcid and
material as well as its object id. When the exact object is gone (a used-up stack, a replaced weapon)
the slot uses another carried item of the same identity: not in hand before in hand, the smaller stack
first. A slot with nothing to use shows the last picture seen, dimmed, and "none"; it fills itself again
when you carry another.
**Counts.** Under each slot: the uses left on all the kits of that kind (28), the stack count (x120), "in
hand" for the weapon you hold, "none" when none is carried, and the slot's key.
**Keys.** Keys are the engine's hotkeys running `/rdef use <slot>`. Type a key in the slot editor (F9,
Ctrl+1, Alt+Shift+Num3) and press *Bind to this slot* (follows the slot) or *Bind to this item* (runs
`/rdef use <the item's name>`, works for every character on this PC). The same from chat: `/rdef bind 3 F9`.
Any item can also be bound by name straight from Settings > Hotkeys or `/rc hotkey add F9 /rdef use Stamina Kit`.
`/rdef use <name>` takes a full name, the start of a name or words in it ("Greater Stamina Kit",
"stamina kit"); of several matches the one not in hand, with the smaller stack, then the lower id, is used.
**The weapon picker** (the *Weapons* button, `/rdef weapons [search]`): every weapon, wand, shield and ammunition
stack you carry, as big rows with the item's picture, grouped by kind (melee, missile, war magic, void
magic, shields, ammunition), A-Z. Type words in the search box ("fire wand", "axe", "void"); the kind
buttons (All, Melee, Missile, War, Void) narrow it, and the one you leave pressed is remembered. The weapon in
hand is highlighted. **One click wields.** `+` in front of a row adds a favourite; favourites and the last
weapons you wielded are listed first (they are also in their kind's group).
## Busy, combat and RynthAi
* One item action at a time: a request waits while the client is busy, a gesture animates, RynthAi waits on
the server, or the last action is unanswered (the server's UseDone; a wield is answered by the item
reading in hand). Pressing again while one waits does not queue a second; pressing another slot replaces the
waiting one. A request not sent within 6 s gives up and says why.
* After a wield from a fighting stance the stance follows the weapon (wand: magic, melee weapon: melee,
launcher with ammunition in hand: missile) once the character is still. At peace you stay at peace. A bow
without arrows in hand returns you to peace rather than leaving a stance it can't use. Shields, armor and
rings leave the stance alone.
* While RynthAi's macro runs, weapons/wands/shields are **not** wielded (it picks the weapon itself and would
swap back) unless *Allow weapon swaps while RynthAi's macro runs* is on. Kits, potions and the rest always work.
## Commands
```
/rdef show / hide the bar
/rdef use <slot | item name> use the slot's item, or the carried item with that name
/rdef set <slot> [item name] put the selected item (or the named one) in a slot
/rdef clear <slot> empty a slot
/rdef bind <slot> <key> bind a key (F9, Ctrl+1 ...) to the slot; /rdef unbind <slot>
/rdef weapons [search] show the weapon picker
/rdef fav make the selected weapon a favourite (or take it out)
/rdef slots <n> how many slots (1-24)
/rdef list | status | help
```
## Settings
Slots (1-24), slots per row, button size, picker row icon size, item icons on/off, counts and keys on/off,
allow weapon swaps under RynthAi. Kept per character with the slots, favourites and recent weapons in
`<RynthSuite>\RynthDefective\characters\<server>_<character>.json`.
## Not in 0.1
Pages, spell slots, arrow auto-equip, gear highlight, summon cooldown counters and the war-magic element
changer (Defective has them).
## Needs
RynthCore engine API 71 with ImGui for the windows (op level 2 for pictures; text buttons without it).
`/rdef use` works on any engine with UseObject.

View file

@ -0,0 +1,64 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthDefective: an item bar with one-touch use, and a fast weapon picker. Slots hold one
item each (a kit, a potion, a weapon...): clicking a slot or pressing its key uses it without
selecting anything in the game; a slot that loses its exact item takes another carried item
of the same name. The picker lists every carried weapon and wand by kind, with a search box,
favourites and the recently used, and wields one with one click. Keys are the engine's
hotkeys running /rdef use <slot or item name>; /rdef. An independent implementation of the
ideas of Defective, the Decal plugin by Hazridi / Aun (no code from it). UI: the engine's
script windows (ImGui), no Avalonia.
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.RynthDefective</RootNamespace>
<AssemblyName>RynthCore.Plugin.RynthDefective</AssemblyName>
<Platforms>x86</Platforms>
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
highest API use NOT behind a Has*/version check. Script windows (v71, HasUi, op level 2 for
pictures) are checked first; so are the UseDone count (v63), wield/refusal info (v70) and
the chat parser the key binding goes through. Below v71 it still uses items (/rdef use). -->
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
<RynthPluginDescription>Item bar: one-touch use of kits, potions and weapons by slot or key, and a fast weapon picker.</RynthPluginDescription>
</PropertyGroup>
<ItemGroup>
<!-- What RynthAi is doing (read only), so a weapon swap stays out of its way. -->
<Compile Include="..\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<!-- An older RynthAi without RynthAi.Activity: its RynthAi.Status macro bit instead. -->
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
<ItemGroup>
<!-- The shortcut bar (2026-10-22): drawn with ImGui.NET bound to the engine's cimgui, in the
engine's look (Shared\RynthUi; plugin API v90 hosts the frameless window and gives AC's
shortcut slots, keys and item pictures). -->
<Compile Include="..\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,195 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Bar.cs
// The shortcut bar (2026-10-22), in place of AC's retail toolbar: RynthCore
// hosts a frameless window (sections manifest, plugin API v90) and RynthDefective
// draws it (ShortcutBar/ShortcutBarWindow.cs). Its first 18 slots are AC's own
// (the retail toolbar's items and AC's keys, so both always agree), the rest
// this plugin's slots. On an engine without v90's shortcuts the old script
// window bar stays.
//
// The tick: the window's clicks (queued from the render thread), the snapshot
// it draws (4 times a second while it shows).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Globalization;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin : IBarActions
{
internal const string BarSurface = "window:bar", PanelsSurface = "window:panels";
private BarSnapshotBuilder? _barBuilder;
private ShortcutBarWindow? _shortcutBar; // render thread
private PanelButtonsWindow? _panelButtons; // render thread
private int _panelsFailures;
private volatile BarSnapshot _barView = BarSnapshot.NotReady; // tick writes, render reads
private readonly ConcurrentQueue<Action> _barActions = new();
private long _barDrawnMs = long.MinValue / 2, _nextBarBuildMs;
private int _barFailures;
/// <summary>The engine has v90's shortcuts and frameless windows: the new bar, not the script window one.</summary>
internal bool UsesShortcutBar => Host.HasShortcuts && Host.HasFramelessWindows;
/// <summary>AC's panels can be opened from here: the engine has v90's AcPanel (the buttons in the corner).</summary>
internal bool UsesPanelButtons => UsesShortcutBar && Host.HasAcPanels;
/// <summary>The sections manifest: the bar's window and the panel buttons' (only on an engine that has what they need).</summary>
internal string SectionsJson()
{
if (!UsesShortcutBar) return "{\"version\":1}";
string bar = "{\"id\":\"bar\",\"title\":\"" + ShortcutBarWindow.Title + "\",\"surface\":\"" + BarSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.Lightning[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":420,\"height\":120,\"minWidth\":90,\"minHeight\":40,\"bar\":true,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"scale\":\"draw\"}";
// Nine 22-unit buttons and the grip in a row, first in the bottom-right corner.
string panels = !UsesPanelButtons ? "" :
",{\"id\":\"panels\",\"title\":\"" + PanelButtonsWindow.Title + "\",\"surface\":\"" + PanelsSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.SquaresFour[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":236,\"height\":30,\"minWidth\":30,\"minHeight\":20,\"bar\":false,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"corner\":\"bottomRight\",\"scale\":\"draw\"}";
// What is selected and its health, first at the top centre.
string selection = ",{\"id\":\"selection\",\"title\":\"" + SelectionWindow.Title + "\",\"surface\":\"" + SelectionSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.Crosshair[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":280,\"height\":46,\"minWidth\":120,\"minHeight\":24,\"bar\":false,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"corner\":\"top\",\"scale\":\"draw\"}";
return "{\"version\":1,\"windows\":[" + bar + panels + selection + "]}";
}
/// <summary>RynthPluginRenderEmbed "window:panels". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderPanels(out float wantHeight)
{
wantHeight = 0;
if (!UsesPanelButtons) return 0;
try
{
_panelButtons ??= new PanelButtonsWindow(Host);
wantHeight = _panelButtons.Draw();
_panelsFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] panel buttons draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_panelsFailures >= 3 ? -2 : 0;
}
}
/// <summary>RynthPluginRenderEmbed "window:bar". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderBar(bool popped, out float wantHeight)
{
wantHeight = 0;
if (!UsesShortcutBar) return 0;
System.Threading.Volatile.Write(ref _barDrawnMs, Environment.TickCount64);
try
{
_shortcutBar ??= new ShortcutBarWindow(Host, this);
wantHeight = _shortcutBar.Draw(_barView, popped);
_barFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] shortcut bar draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_barFailures >= 3 ? -2 : 0;
}
}
/// <summary>Plugin tick: the bar's clicks, then its snapshot while it shows.</summary>
private void TickBar(long now)
{
while (_barActions.TryDequeue(out Action? act))
{
try { act(); }
catch (Exception ex) { Host.Log($"[RynthDefective] bar action failed: {ex.GetType().Name}: {ex.Message}"); }
}
if (!UsesShortcutBar || !_identityKnown) return;
bool shown = now - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000;
if (!shown || now < _nextBarBuildMs) return;
_nextBarBuildMs = now + 250;
_barBuilder ??= new BarSnapshotBuilder(Host);
_barView = _barBuilder.Build(_session, _session.Items(), now);
}
private void QueueBar(Action action)
{
if (_barActions.Count < 32) _barActions.Enqueue(action);
}
private static bool IsRetail(int number) => number <= DefSettings.RetailSlots;
// ── IBarActions (render thread: queue only) ─────────────────────────────
public void Use(int number) => QueueBar(() =>
{
if (IsRetail(number))
{
if (!Host.ShortcutAction(RynthShortcutOp.Use, number - 1)) _session.SetStatus($"Slot {number} can't be used now.", warning: true);
return;
}
string? problem = _session.UseSlot(number - DefSettings.RetailSlots);
if (problem != null) { _session.SetStatus(problem, warning: true); Print(problem); }
});
public void SetFromSelected(int number) => QueueBar(() =>
{
if (IsRetail(number))
{
uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
if (sel == 0) { Print("Select the item in the game first, then put it in the slot."); return; }
if (!Host.ShortcutAction(RynthShortcutOp.Set, number - 1, sel)) Print($"Slot {number} can't be changed now.");
_nextBarBuildMs = 0;
return;
}
Print(_session.SetFromSelected(number - DefSettings.RetailSlots));
_nextBarBuildMs = 0;
});
public void Clear(int number) => QueueBar(() =>
{
if (IsRetail(number))
{
if (!Host.ShortcutAction(RynthShortcutOp.Clear, number - 1)) Print($"Slot {number} can't be changed now.");
_nextBarBuildMs = 0;
return;
}
Print(_session.ClearSlot(number - DefSettings.RetailSlots));
_nextBarBuildMs = 0;
});
public void DropItem(int number, uint objectId) => QueueBar(() =>
{
if (IsRetail(number))
{
// The retail toolbar's own "make a shortcut": AC checks the item (and says why not).
if (!Host.ShortcutAction(RynthShortcutOp.Set, number - 1, objectId)) Print($"Slot {number} can't be changed now.");
}
else Print(_session.SetFromId(number - DefSettings.RetailSlots, objectId));
_nextBarBuildMs = 0;
});
public void ChangeSlotCount(int delta) => QueueBar(() =>
{
DefSettings st = _session.Settings;
st.BarSlots = Math.Clamp(st.BarSlots + delta, DefSettings.BarSlotsMin, DefSettings.BarSlotsMax);
RequestSave();
_nextBarBuildMs = 0;
});
public void KeysChanged() => QueueBar(() =>
{
_barBuilder?.InvalidateKeys();
_session.Keys.Invalidate();
_nextBarBuildMs = 0;
});
public void ShowWeapons() => QueueBar(() => ShowPicker(true));
public void Hide() => QueueBar(() => Host.SetPanelOpen(ShortcutBarWindow.Title, RynthPanelOpen.Close));
}

View file

@ -0,0 +1,120 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Selection.cs
// The Selection window (2026-10-22): what is selected, how far and which way,
// and a creature's health, as the retail toolbar showed it
// (ShortcutBar/SelectionWindow.cs draws it).
//
// The tick builds the view 10 times a second: the selected object
// (GetSelectedItemId), its name, where it is from the player (positions in
// landblock coordinates: 192 units a landblock; the facing from the player's
// pose, as RynthAi's combat turns), and its health from AC's health updates
// (OnUpdateHealth), asked for when a creature is selected and every 2 s after.
// ============================================================================
using System;
using System.Globalization;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin
{
internal const string SelectionSurface = "window:selection";
private SelectionWindow? _selectionWindow; // render thread
private volatile SelectionView _selectionView = SelectionView.NotReady;
private long _selectionDrawnMs = long.MinValue / 2, _nextSelectionMs, _nextHealthQueryMs;
private uint _selectionId;
private int _selectionFailures;
// The last health AC sent for the selected object (game thread writes, tick reads).
private volatile HealthSeen? _health;
private sealed record HealthSeen(uint Id, float Ratio, uint Current, uint Max);
private const uint CreatureType = 0x10; // ItemType.Creature
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
if (targetId != 0 && targetId == _selectionId)
_health = new HealthSeen(targetId, healthRatio, currentHealth, maxHealth);
}
/// <summary>RynthPluginRenderEmbed "window:selection". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderSelection(out float wantHeight)
{
wantHeight = 0;
if (!UsesShortcutBar) return 0;
System.Threading.Volatile.Write(ref _selectionDrawnMs, Environment.TickCount64);
try
{
_selectionWindow ??= new SelectionWindow(Host, id => QueueBar(() => { if (!Host.UseObject(id)) Print("That can't be used now."); }));
wantHeight = _selectionWindow.Draw(_selectionView);
_selectionFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] selection draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_selectionFailures >= 3 ? -2 : 0;
}
}
/// <summary>Plugin tick: the selection's view while its window shows.</summary>
private void TickSelection(long now)
{
if (!UsesShortcutBar || !_identityKnown) return;
if (now - System.Threading.Volatile.Read(ref _selectionDrawnMs) > 2000 || now < _nextSelectionMs) return;
_nextSelectionMs = now + 100;
try { _selectionView = BuildSelection(now); }
catch (Exception ex) { Host.Log($"[RynthDefective] selection read failed: {ex.GetType().Name}: {ex.Message}"); }
}
private SelectionView BuildSelection(long now)
{
uint sel = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
bool changed = sel != _selectionId;
_selectionId = sel;
if (changed) _health = null;
if (sel == 0) return new SelectionView(true, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
string name = Host.TryGetObjectName(sel, out string n) && n.Length > 0 ? n : $"0x{sel:X8}";
bool creature = Host.TryGetItemType(sel, out uint type) && (type & CreatureType) != 0;
if (creature && (changed || now >= _nextHealthQueryMs))
{
_nextHealthQueryMs = now + 2000;
Host.QueryHealth(sel);
}
string where = string.Empty;
float relative = float.NaN;
bool carried = false;
foreach (var it in _session.Items()) if (it.Id == sel) { carried = true; break; }
if (carried) where = "in your pack";
else if (Host.TryGetObjectPosition(sel, out uint oc, out float ox, out float oy, out float oz) && oc != 0
&& Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out float qw, out _, out _, out float qz) && pc != 0)
{
double dx = Global(oc, ox, true) - Global(pc, px, true), dy = Global(oc, oy, false) - Global(pc, py, false), dz = oz - pz;
double dist = Math.Sqrt(dx * dx + dy * dy + dz * dz);
double bearing = Math.Atan2(dx, dy) * 180.0 / Math.PI;
if (bearing < 0) bearing += 360.0;
double facing = ((-2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0;
double rel = bearing - facing;
while (rel > 180) rel -= 360;
while (rel < -180) rel += 360;
if (dist >= 0.5) relative = (float)rel;
where = $"{dist.ToString(dist < 10 ? "0.0" : "0", CultureInfo.InvariantCulture)} yd {Compass(bearing)}";
}
HealthSeen? h = _health;
float health = h != null && h.Id == sel ? h.Ratio : -1f;
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0);
}
/// <summary>A landblock coordinate as a world one: 192 units a landblock (the cell's high bytes).</summary>
private static double Global(uint cell, float local, bool x) =>
((x ? cell >> 24 : cell >> 16) & 0xFF) * 192.0 + local;
private static readonly string[] Points = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" };
private static string Compass(double bearing) => Points[(int)Math.Round(bearing / 45.0) % 8];
}

View file

@ -0,0 +1,429 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
using RynthCore.Plugin.RynthDefective.Views;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
/// <summary>
/// RynthDefective: an item bar with one-touch use, and a fast weapon picker.
///
/// A slot holds one item identity (Model/ItemRef.cs: the object id, plus name, wcid and material).
/// Pressing the slot, or the key the engine's hotkeys bind to "/rdef use N", uses the item without
/// anything selected in the game: a kit on yourself, a potion or scroll by itself, a weapon or wand
/// wielded (Use/UseController.cs has the rules, the busy handling and the stance). When the exact
/// object is gone the slot follows another carried item of the same identity.
///
/// The weapon picker window lists the carried weapons and wands by kind, with search, favourites and
/// the recently wielded, and wields one with one click.
///
/// Everything runs on the plugin pump (OnTick and the events the engine drains into it) except
/// OnChatBarEnter, which the engine may call on AC's thread: it only queues the command.
/// </summary>
public sealed partial class RynthDefectivePlugin : RynthPluginBase
{
public const string Version = "0.1.0";
private const long IdentityRetryMs = 1000;
private const long SaveDelayMs = 750;
private const long PassIntervalMs = 400;
private const long InventoryAgeMs = 700;
private readonly DefStore _store = new();
private readonly DefSession _session;
private readonly UiHost _ui = new();
private readonly ConcurrentQueue<string> _commands = new();
private HostDefWorld? _world;
private BarView? _bar;
private PickerView? _picker;
private UiWindow? _barWindow, _pickerWindow;
private bool _inWorld;
private bool _identityKnown;
private long _nextIdentityTryMs;
private string _server = string.Empty;
private string _character = string.Empty;
private long _saveDueMs;
private bool _noUiLogged;
private int _revisionSeen = -1;
public RynthDefectivePlugin()
{
_session = new DefSession(new HotkeyLookup());
}
public override int Initialize()
{
_ui.Log = msg => Host.Log(msg);
// The shortcut bar (plugin API v90) draws with ImGui.NET bound to the engine's cimgui, in its look.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthDefective] " + msg));
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
_world = new HostDefWorld(Host);
_session.Items = () => _world.Snapshot(InventoryAgeMs);
_session.SelectedId = () => Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
_session.RunChat = line => Host.HasInvokeChatParser && Host.InvokeChatParser(line);
_session.Save = RequestSave;
_session.Use.Say = text => { _session.SetStatus(text); Host.Log("[RynthDefective] " + text); };
_session.Use.Warn = text => { _session.SetStatus(text, warning: true); Print(text); };
_session.Use.Log = line => Host.Log(line);
_session.Use.Wielded = OnWielded;
_bar = new BarView(_session);
_picker = new PickerView(_session);
_barWindow = _ui.Add(new UiWindow("RynthDefective/Bar", "Defective") { DefaultWidth = 330f, DefaultHeight = 160f, MinWidth = 220f, MinHeight = 100f });
_pickerWindow = _ui.Add(new UiWindow("RynthDefective/Weapons", "Defective Weapons") { DefaultWidth = 360f, DefaultHeight = 480f, MinWidth = 260f, MinHeight = 160f });
_bar.RequestFit = FitBar;
_bar.ShowPicker = () => ShowPicker(true);
Host.Log($"[RynthDefective] {Version} initialized. /rdef shows or hides the bar; /rdef use <slot or item name>; /rdef help. Files: {_store.Root}");
return 0;
}
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
public override void OnLoginComplete()
{
_inWorld = true;
_identityKnown = false;
_nextIdentityTryMs = Environment.TickCount64;
_session.Use.Reset();
_world?.Reset();
}
public override void OnLogout()
{
SaveNow();
_inWorld = false;
_identityKnown = false;
_session.LoggedIn = false;
_session.Use.Reset();
_world?.Reset();
_barView = RynthCore.Plugin.RynthDefective.ShortcutBar.BarSnapshot.NotReady;
foreach (UiWindow? w in new[] { _barWindow, _pickerWindow })
if (w != null) { w.Visible = false; w.NeedsPass = true; }
_ui.SubmitEmpty(Host);
}
public override void Shutdown()
{
SaveNow();
_session.Use.Reset();
_ui.SubmitEmpty(Host);
}
// ── Chat ────────────────────────────────────────────────────────────────
// May run on AC's thread: classify and queue only.
public override void OnChatBarEnter(string? text, ref int eat)
{
if (string.IsNullOrWhiteSpace(text)) return;
string t = text.Trim();
if (!t.StartsWith("/rdef", StringComparison.OrdinalIgnoreCase) || (t.Length > 5 && !char.IsWhiteSpace(t[5])))
return;
eat = 1;
_commands.Enqueue(t.Length > 5 ? t.Substring(5).Trim() : string.Empty);
}
private void RunCommand(string arg)
{
DefCommand c = DefCommandParser.Parse(arg);
if (c.Verb == DefVerb.Help)
{
PrintHelp();
return;
}
if (c.Verb == DefVerb.Error)
{
Print(c.Error);
return;
}
if (!_identityKnown)
{
Print("Log in first.");
return;
}
switch (c.Verb)
{
case DefVerb.Toggle:
if (UsesShortcutBar)
Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.ShortcutBarWindow.Title, RynthPanelOpen.Toggle);
else if (_barWindow != null) { _barWindow.Visible = !_barWindow.Visible; _barWindow.NeedsPass = true; NoteNoUi(_barWindow.Visible); }
break;
case DefVerb.Selection when c.Text.Length > 0:
if (uint.TryParse(c.Text.Replace("0x", "", StringComparison.OrdinalIgnoreCase), System.Globalization.NumberStyles.HexNumber, null, out uint pick))
Host.SelectItem(pick);
break;
case DefVerb.Selection:
if (UsesShortcutBar) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.SelectionWindow.Title, RynthPanelOpen.Toggle);
else Print("This RynthCore can't show the selection window (it needs plugin API v90).");
break;
case DefVerb.Panels:
if (UsesPanelButtons) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.PanelButtonsWindow.Title, RynthPanelOpen.Toggle);
else Print("This RynthCore can't open the game's panels from buttons (it needs plugin API v90).");
break;
case DefVerb.Weapons:
if (c.Text.Length > 0 && _picker != null) _picker.Search = c.Text;
ShowPicker(c.Text.Length > 0 || _pickerWindow?.Visible != true);
break;
case DefVerb.Use:
if (c.Slot > 0)
{
string? problem = _session.UseSlot(c.Slot);
if (problem != null) { _session.SetStatus(problem, warning: true); Print(problem); }
}
else _session.UseByName(c.Text);
break;
case DefVerb.Set:
Print(c.Text.Length > 0 ? _session.SetFromName(c.Slot, c.Text) : _session.SetFromSelected(c.Slot));
break;
case DefVerb.Clear:
Print(_session.ClearSlot(c.Slot));
break;
case DefVerb.Bind:
Print(_session.BindKey(c.Slot, c.Text, byName: false));
break;
case DefVerb.Unbind:
Print(_session.UnbindKey(c.Slot));
break;
case DefVerb.Favourite:
Print(_session.ToggleSelectedFavourite());
break;
case DefVerb.Slots:
_session.SetSlotCount(c.Slot);
FitBar();
Print($"{_session.Settings.SlotCount} slots.");
break;
case DefVerb.List:
PrintSlots();
break;
case DefVerb.Status:
PrintStatus();
break;
}
MarkAllForPass();
}
private void PrintHelp()
{
Print(DefCommandParser.Usage);
Print("A key for a slot: /rdef bind 1 F9 (or Edit slots in the bar). Any item by name from Settings > Hotkeys: /rc hotkey add F9 /rdef use Stamina Kit.");
}
private void PrintSlots()
{
IReadOnlyList<CarriedItem> items = _session.Items();
var sb = new StringBuilder();
for (int i = 1; i <= _session.Settings.SlotCount; i++)
{
DefSlot slot = _session.Data.Slots[i - 1];
if (slot.Item == null) { Print($"{i}: (empty)"); continue; }
SlotStatus s = ItemMatcher.Status(slot.Item, items);
sb.Clear();
sb.Append(i).Append(": ").Append(slot.Item.FullName);
string count = SlotText.Count(s, out _);
if (count.Length > 0) sb.Append(" (").Append(count).Append(')');
if (_session.KeyOfSlot(i) is { } key) sb.Append(" [").Append(key).Append(']');
Print(sb.ToString());
}
}
private void PrintStatus()
{
int filled = 0;
for (int i = 0; i < _session.Settings.SlotCount; i++) if (!_session.Data.Slots[i].Empty) filled++;
Print($"{_character}: {filled}/{_session.Settings.SlotCount} slots set, {_session.Data.Favourites.Count} favourite weapons; "
+ $"{(_session.Use.InFlight ? "an action is in flight" : _session.Use.HasPending ? "an action is waiting" : "idle")}; file {_store.PathFor(_server, _character)}");
}
private void Print(string text)
{
if (!Host.WriteToChat("[RynthDefective] " + text, 1))
Host.Log("[RynthDefective] " + text);
}
private void NoteNoUi(bool shown)
{
if (shown && !Host.HasUi && !_noUiLogged)
{
_noUiLogged = true;
Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). /rdef use <slot or item name> still works.");
}
}
// ── Windows ─────────────────────────────────────────────────────────────
private void ShowPicker(bool visible)
{
if (_pickerWindow == null) return;
_pickerWindow.Visible = visible;
_pickerWindow.NeedsPass = true;
NoteNoUi(visible);
}
private void FitBar()
{
if (_barWindow == null || _bar == null) return;
(float w, float h) = _bar.WantedSize();
_barWindow.RequestWidth = w;
_barWindow.RequestHeight = h;
_barWindow.NeedsPass = true;
}
private void MarkAllForPass()
{
if (_barWindow != null) _barWindow.NeedsPass = true;
if (_pickerWindow != null) _pickerWindow.NeedsPass = true;
}
/// <summary>A weapon (or shield) went into the hands: first in the picker's recent list.</summary>
private void OnWielded(CarriedItem it)
{
ItemKind kind = ItemKinds.Classify(it);
if (!ItemKinds.IsWeapon(kind) && kind != ItemKind.Shield) return;
_session.Data.NoteRecent(ItemRef.From(it));
RequestSave();
}
// ── Tick ────────────────────────────────────────────────────────────────
public override void OnTick()
{
long now = Environment.TickCount64;
while (_commands.TryDequeue(out string? cmd))
{
try { RunCommand(cmd); }
catch (Exception ex) { Host.Log($"[RynthDefective] /rdef {cmd} failed: {ex.GetType().Name}: {ex.Message}"); }
}
_ui.Poll(Host);
if (_inWorld)
{
if (!_identityKnown && now >= _nextIdentityTryMs) TryStartCharacter(now);
if (_identityKnown && _world != null)
{
try
{
TickInventory();
_session.Use.Tick(_world);
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] tick failed: {ex.GetType().Name}: {ex.Message}");
}
}
}
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
TickBar(now);
TickSelection(now);
// With the shortcut bar the old script-window bar stays shut (the weapon picker is still one).
if (UsesShortcutBar && _barWindow != null && _barWindow.Visible) { _barWindow.Visible = false; _barWindow.NeedsPass = true; }
if (!Host.HasUi || _barWindow == null || _pickerWindow == null || _bar == null || _picker == null) return;
if (_session.Use.HasPending || _session.Use.InFlight) _barWindow.NeedsPass = _pickerWindow.NeedsPass = true;
if (!_session.IconsAvailable) RefreshIconSupport();
Record(_barWindow, now, _bar.Draw);
Record(_pickerWindow, now, _picker.Draw);
_ui.Submit(Host, now);
if (_identityKnown)
{
DefSettings st = _session.Settings;
if (_barWindow.Visible != st.BarOpen || _pickerWindow.Visible != st.PickerOpen)
{
st.BarOpen = _barWindow.Visible;
st.PickerOpen = _pickerWindow.Visible;
RequestSave();
}
}
}
/// <summary>Re-reads the inventory while a window shows or an action waits; slots follow their items.</summary>
private void TickInventory()
{
bool barShown = Environment.TickCount64 - System.Threading.Volatile.Read(ref _barDrawnMs) < 2000;
bool wanted = (_barWindow?.Visible ?? false) || (_pickerWindow?.Visible ?? false) || barShown || _session.Use.HasPending;
if (!wanted || _world == null) return;
List<CarriedItem> items = _world.Snapshot(InventoryAgeMs);
if (_world.Revision == _revisionSeen) return;
_revisionSeen = _world.Revision;
if (_session.Maintain(items)) RequestSave();
MarkAllForPass();
}
private void TryStartCharacter(long now)
{
_nextIdentityTryMs = now + IdentityRetryMs;
uint player = Host.GetPlayerId();
if (player == 0 || !Host.TryGetObjectName(player, out string name) || string.IsNullOrWhiteSpace(name)) return;
string server = Host.TryGetWorldName(out string w) ? w : string.Empty;
_server = server;
_character = name;
DefData data = _store.Load(server, name, out string? problem);
if (problem != null) Host.Log($"[RynthDefective] couldn't read the saved slots ({problem}); using defaults.");
_session.Data = data;
_session.Use.Settings = data.Settings;
_session.Character = name;
_session.LoggedIn = true;
_identityKnown = true;
_revisionSeen = -1;
RefreshIconSupport();
if (_barWindow != null && _bar != null)
{
_barWindow.Visible = data.Settings.BarOpen;
(float bw, float bh) = _bar.WantedSize();
_barWindow.DefaultWidth = bw;
_barWindow.DefaultHeight = bh;
_barWindow.NeedsPass = true;
}
if (_pickerWindow != null) { _pickerWindow.Visible = data.Settings.PickerOpen; _pickerWindow.NeedsPass = true; }
Host.Log($"[RynthDefective] item bar for {name} on {server}: {data.Slots.FindAll(s => !s.Empty).Count} slots set; file {_store.PathFor(server, name)}");
}
private void RefreshIconSupport()
{
_session.IconsAvailable = Host.HasUi && Host.TryGetUiInfo(out UiInfoNative info) && info.OpLevel >= 2;
}
private void RequestSave()
{
MarkAllForPass();
if (_saveDueMs == 0) _saveDueMs = Environment.TickCount64 + SaveDelayMs;
}
private void SaveNow()
{
_saveDueMs = 0;
if (!_identityKnown) return;
_session.Settings.Clamp();
string? error = _store.Save(_server, _character, _session.Data);
if (error != null) Host.Log("[RynthDefective] save failed: " + error);
}
/// <summary>A pass when one is wanted, or on the refresh interval while visible (counts and the status tick on).</summary>
private void Record(UiWindow w, long now, Action<UiWindow> draw)
{
bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs);
if (!due) return;
w.NeedsPass = false;
w.NextPassMs = now + PassIntervalMs;
w.Begin();
try
{
draw(w);
}
catch (Exception ex)
{
w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}");
Host.Log($"[RynthDefective] {w.Key} pass failed: {ex}");
}
w.End();
}
}

View file

@ -0,0 +1,148 @@
// ============================================================================
// RynthDefective - ShortcutBar/BarSnapshot.cs
// What the shortcut bar shows, built on the plugin tick (BarSnapshotBuilder)
// and drawn on the render thread (ShortcutBarWindow): one immutable record per
// slot, swapped whole.
//
// Slots 1-18 are AC's own shortcut slots (RynthCoreHost.GetShortcuts, plugin
// API v90): the items the retail toolbar holds, the keys AC's keymap gives
// UseQuickSlot_1-18. Slots 19 and on are this plugin's own (DefData.Slots),
// their keys the engine's hotkeys (/rdef use N). The player chooses how many
// the bar shows (DefSettings.BarSlots).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Text;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Views;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
/// <summary>How a slot's count line reads: plain, in hand / worn, or nothing carried.</summary>
internal enum CountTone { Plain, InHand, Missing }
/// <summary>One slot as drawn.</summary>
internal sealed record BarSlot(
int Number,
bool Retail,
uint ObjectId,
uint SpellId,
string Name,
string Count,
CountTone Tone,
string Key,
string AllKeys,
string Tooltip)
{
public bool Empty => ObjectId == 0 && SpellId == 0 && Name.Length == 0;
}
internal sealed record BarSnapshot(BarSlot[] Slots, bool Ready, int IconSize)
{
public static readonly BarSnapshot NotReady = new(Array.Empty<BarSlot>(), false, 36);
}
/// <summary>Builds the snapshot on the plugin tick (reads the host and the carried items).</summary>
internal sealed class BarSnapshotBuilder
{
private readonly RynthCoreHost _host;
private readonly uint[] _ids = new uint[DefSettings.RetailSlots], _spells = new uint[DefSettings.RetailSlots];
private readonly string[] _keys = new string[DefSettings.RetailSlots];
private long _keysReadMs = long.MinValue / 2, _fastKeysUntilMs;
public BarSnapshotBuilder(RynthCoreHost host)
{
_host = host;
Array.Fill(_keys, string.Empty);
}
/// <summary>A key was changed from the bar: ask again often for a few seconds (the change is made on the game's tick).</summary>
public void InvalidateKeys()
{
_keysReadMs = long.MinValue / 2;
_fastKeysUntilMs = Environment.TickCount64 + 4000;
}
/// <summary>AC's keys for the 18 retail slots (re-asked every 2 s: the keymap can change, from any client).</summary>
private void RefreshKeys(long now)
{
if (now - _keysReadMs < (now < _fastKeysUntilMs ? 250 : 2000)) return;
_keysReadMs = now;
for (int i = 0; i < _keys.Length; i++) _keys[i] = _host.GetActionKeys("UseQuickSlot_" + (i + 1));
}
public BarSnapshot Build(DefSession session, IReadOnlyList<CarriedItem> items, long now)
{
if (!_host.HasShortcuts || _host.GetShortcuts(_ids, _spells) == 0) return BarSnapshot.NotReady;
RefreshKeys(now);
DefSettings st = session.Settings;
var byId = new Dictionary<uint, CarriedItem>(items.Count);
foreach (CarriedItem it in items) byId[it.Id] = it;
var slots = new BarSlot[st.BarSlots];
for (int n = 1; n <= st.BarSlots; n++)
slots[n - 1] = n <= DefSettings.RetailSlots ? Retail(n, byId) : Own(n, session, items, _host);
return new BarSnapshot(slots, true, st.ButtonSize);
}
private BarSlot Retail(int n, Dictionary<uint, CarriedItem> byId)
{
uint id = _ids[n - 1], spell = _spells[n - 1];
string allKeys = _keys[n - 1];
string key = FirstKey(allKeys);
if (id == 0 && spell == 0)
return new BarSlot(n, true, 0, 0, string.Empty, string.Empty, CountTone.Plain, key, allKeys,
$"Slot {n} (the game's own): empty.{KeysLine(allKeys)}\nRight-click: put the selected item here, or change its keys.");
string name;
string count = string.Empty;
CountTone tone = CountTone.Plain;
if (id != 0 && byId.TryGetValue(id, out CarriedItem? it))
{
name = it.FullName;
count = SlotText.Count(new SlotStatus(it, it.Stack, it.Uses, false), out uint color);
tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain;
}
else if (id != 0)
{
name = _host.TryGetObjectName(id, out string n2) && n2.Length > 0 ? n2 : $"0x{id:X8}";
count = "none";
tone = CountTone.Missing;
}
else name = $"Spell {spell}";
string tip = $"Slot {n} (the game's own): {name}{(count.Length > 0 ? " - " + count : "")}.{KeysLine(allKeys)}\n" +
"Click: use it, as its key does. Right-click: change the slot or its keys.";
return new BarSlot(n, true, id, id == 0 ? spell : 0, name, count, tone, key, allKeys, tip);
}
private static BarSlot Own(int n, DefSession session, IReadOnlyList<CarriedItem> items, RynthCoreHost host)
{
int own = n - DefSettings.RetailSlots;
DefSlot slot = own <= session.Data.Slots.Count ? session.Data.Slots[own - 1] : new DefSlot();
// Every key of "/rdef use N" (the engine's hotkeys), else the one bound to the item by name.
string all = host.HasKeyBinding ? host.GetActionKeys(DefCommandParser.UseCommand(own)) : string.Empty;
string key = all.Length > 0 ? FirstKey(all) : session.KeyOfSlot(own) ?? string.Empty;
if (all.Length == 0) all = key;
if (slot.Item == null)
return new BarSlot(n, false, 0, 0, string.Empty, string.Empty, CountTone.Plain, SlotText.ShortKey(key), all,
$"Slot {n} (RynthCore's: the game holds 18): empty.{KeysLine(all)}\nRight-click: put the selected item here, or change its keys.");
SlotStatus s = ItemMatcher.Status(slot.Item, items);
string count = SlotText.Count(s, out uint color);
CountTone tone = color == SlotText.InHand ? CountTone.InHand : color == SlotText.Missing ? CountTone.Missing : CountTone.Plain;
string tip = SlotText.Tooltip(n, slot.Item, s, slot.Mode, key.Length > 0 ? key : null)
+ "\n(RynthCore's slot: the game's toolbar holds 18.)";
return new BarSlot(n, false, s.Item?.Id ?? 0, 0, s.Item?.FullName ?? slot.Item.FullName, count, tone,
SlotText.ShortKey(key), all, tip);
}
/// <summary>The first of "1, Ctrl+1": what fits on the slot.</summary>
private static string FirstKey(string keys)
{
int comma = keys.IndexOf(',');
return comma < 0 ? keys : keys[..comma];
}
private static string KeysLine(string keys) => keys.Length > 0 ? "\nKeys: " + keys : "\nNo key yet.";
}

View file

@ -0,0 +1,155 @@
// ============================================================================
// RynthDefective - ShortcutBar/PanelButtonsWindow.cs
// Tiny buttons for AC's own panels, in the bottom-right corner (Tom
// 2026-10-22: with the retail toolbar hidden, its panel buttons go with it).
// RynthCore hosts the frameless window (sections manifest "corner":
// "bottomRight", plugin API v90) and opens and closes the panels the way AC's
// toolbar and keys do (RynthCoreHost.AcPanel): one main panel at a time.
//
// grip the dots on the left: drag the strip; Ctrl+wheel: bigger or
// smaller; right-click: hide it (/rdef panels shows it again).
// buttons the pack, attributes & skills, the spellbook, fellowship &
// allegiance, the map, quests, spells on you, character info,
// options. Lit while their panel is open. They fill the window's
// width and wrap: drag it narrow for a column.
//
// AC's render thread; the panel calls are queued by the engine.
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
internal sealed class PanelButtonsWindow
{
public const string Title = "Game Panels";
private readonly RynthCoreHost _host;
private float _k = 1f, _r = 1f;
public PanelButtonsWindow(RynthCoreHost host) => _host = host;
private readonly record struct Button(RynthAcPanel Panel, string Icon, string Tip);
private static readonly Button[] Buttons =
[
new(RynthAcPanel.Inventory, RynthIcons.Backpack, "Pack"),
new(RynthAcPanel.Character, RynthIcons.User, "Attributes and skills"),
new(RynthAcPanel.Spellbook, RynthIcons.MagicWand, "Spellbook"),
new(RynthAcPanel.Social, RynthIcons.UsersThree, "Fellowship, allegiance and friends"),
new(RynthAcPanel.Map, RynthIcons.MapTrifold, "Map"),
new(RynthAcPanel.Quests, RynthIcons.Scroll, "Contracts and journal"),
new(RynthAcPanel.HelpfulSpells, RynthIcons.Sparkle, "Spells on you"),
new(RynthAcPanel.CharacterInfo, RynthIcons.Info, "Character information"),
new(RynthAcPanel.Options, RynthIcons.Gear, "Options"),
];
private const float Pad = 4, Cell = 22, Gap = 2, GripW = 9, Radius = 4;
private float Px(float v) => v * _k;
/// <summary>
/// The layout's scale and the text's against the baked font: the window's own size (Settings > UI >
/// Toolbar, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
/// </summary>
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
private uint _bg, _key, _line, _text, _faint, _accent;
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the strip into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw()
{
Scale();
_bg = Color(RynthUiColor.Background);
_key = Color(RynthUiColor.KeyFace);
_line = Color(RynthUiColor.Hairline);
_text = Color(RynthUiColor.Text);
_faint = Color(RynthUiColor.Faint);
_accent = Color(RynthUiColor.Accent);
Vector2 origin = ImGui.GetCursorScreenPos();
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
if (width < 20) return Px(Cell + 2 * Pad);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float cell = Px(Cell), gap = Px(Gap), pad = Px(Pad), grip = Px(GripW);
float room = width - 2 * pad - grip - gap;
int perRow = Math.Max(1, (int)MathF.Floor((room + gap) / (cell + gap)));
int rows = (Buttons.Length + perRow - 1) / perRow;
float height = MathF.Ceiling(2 * pad + rows * cell + (rows - 1) * gap);
// The frame, as the shortcut bar's.
Vector2 max = origin + new Vector2(width, height);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
// The grip: drag, Ctrl+wheel, right-click to hide.
Vector2 gp = origin + new Vector2(pad, pad);
ImGui.SetCursorScreenPos(gp);
ImGui.InvisibleButton("##gp_grip", new Vector2(grip, height - 2 * pad));
_host.PanelDragWithLastItem();
bool gripHot = ImGui.IsItemHovered();
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
SafeImGui.SetItemTooltip("Drag to move. Ctrl+wheel: bigger or smaller. Right-click: hide (/rdef panels shows it again).\nDrag the window's edge narrower for a column.");
DrawIcon(dl, RynthIcons.DotsSixVertical, gp, new Vector2(grip, height - 2 * pad), Px(11), gripHot ? _text : _faint);
float x0 = gp.X + grip + gap;
for (int i = 0; i < Buttons.Length; i++)
{
int col = i % perRow, row = i / perRow;
Vector2 p = new(MathF.Round(x0 + col * (cell + gap)), MathF.Round(origin.Y + pad + row * (cell + gap)));
DrawButton(dl, Buttons[i], p, cell);
}
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
}
private void DrawButton(ImDrawListPtr dl, in Button b, Vector2 p, float cell)
{
Vector2 size = new(cell, cell);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton("##gp_" + (int)b.Panel, size);
bool hot = ImGui.IsItemHovered();
bool? open = _host.IsAcPanelOpen(b.Panel);
SafeImGui.SetItemTooltip(open == null ? b.Tip + " (not in this client)" : b.Tip + (open == true ? " - open: click to close" : ""));
float r = Px(3);
if (hot || open == true) dl.AddRectFilled(p, p + size, _key, r);
if (open == true) dl.AddLine(new Vector2(p.X + Px(4), p.Y + cell - Px(1.5f)), new Vector2(p.X + cell - Px(4), p.Y + cell - Px(1.5f)), _accent, Px(1.5f));
uint color = open == null ? A(_faint, 0.5f) : open == true ? _accent : hot ? _text : A(_text, 0.72f);
DrawIcon(dl, b.Icon, p, size, Px(14), color);
if (clicked && open != null) _host.AcPanel(b.Panel, RynthAcPanelOp.Toggle);
}
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (from Ui18's bake).</summary>
private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
{
if (string.IsNullOrEmpty(glyph)) return;
ImFontPtr font = Font(RynthUiFont.Ui18);
if (font.NativePtr == null) return;
byte* g = (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]);
if (g == null) return;
float advance = *(float*)(g + 4);
if (advance <= 0) return;
float* box = (float*)(g + 8);
float scale = px / advance;
Vector2 centre = new((box[0] + box[2]) * 0.5f * scale, (box[1] + box[3]) * 0.5f * scale);
Vector2 at = min + size * 0.5f - centre;
dl.AddText(font, font.FontSize * scale, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph);
}
}

View file

@ -0,0 +1,196 @@
// ============================================================================
// RynthDefective - ShortcutBar/SelectionWindow.cs
// What is selected, as the retail toolbar showed it (Tom 2026-10-22: "people
// use it all the time to find things near them: doors, monsters"): its
// picture and name, how far and which way it is (an arrow from where you
// face, and the compass point), and the health bar of a creature or player.
// USE uses it (opens a door, talks to an NPC). AC's own selection keys still
// pick what is selected; this only shows it.
//
// the name row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (Settings > UI > Toolbar, /rdef selection).
//
// AC's render thread; reads the view the tick built (SelectionView).
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
/// <summary>The selected object as drawn (built on the plugin tick).</summary>
internal sealed record SelectionView(
bool Ready,
uint Id,
string Name,
string Where,
float Relative, // degrees from where the player faces (0 ahead, + to the right); NaN = unknown
float Health, // 0-1, or -1 when it has none known
uint Current,
uint Max)
{
public static readonly SelectionView NotReady = new(false, 0, string.Empty, string.Empty, float.NaN, -1f, 0, 0);
}
internal sealed class SelectionWindow
{
public const string Title = "Selection";
private readonly RynthCoreHost _host;
private readonly Action<uint> _use;
private float _k = 1f, _r = 1f;
public SelectionWindow(RynthCoreHost host, Action<uint> use)
{
_host = host;
_use = use;
}
private float Px(float v) => v * _k;
private float Fs(ImFontPtr f) => f.FontSize * _r;
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
private const float Pad = 6, Icon = 30, Gap = 6, Radius = 4, BarH = 6, UseW = 34, UseH = 16;
private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent;
private static readonly uint HealthColor = Argb(0xFFE0564E), HealthHigh = Argb(0xFF73D885), White = Argb(0xFFFFFFFF);
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the selection into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw(SelectionView v)
{
Scale();
_bg = Color(RynthUiColor.Background);
_key = Color(RynthUiColor.KeyFace);
_inset = Color(RynthUiColor.Inset);
_line = Color(RynthUiColor.Hairline);
_text = Color(RynthUiColor.Text);
_dim = Color(RynthUiColor.Muted);
_faint = Color(RynthUiColor.Faint);
_accent = Color(RynthUiColor.Accent);
Vector2 origin = ImGui.GetCursorScreenPos();
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
if (width < 40) return Px(40);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float pad = Px(Pad), icon = Px(Icon);
float height = MathF.Ceiling(2 * pad + icon);
Vector2 max = origin + new Vector2(width, height);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
bool hasUse = v.Ready && v.Id != 0;
float useW = hasUse ? Px(UseW) : 0f;
// The drag surface: everything but USE.
ImGui.SetCursorScreenPos(origin);
ImGui.InvisibleButton("##sel_drag", new Vector2(Math.Max(1, width - useW - (hasUse ? pad : 0)), height));
_host.PanelDragWithLastItem();
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
SafeImGui.SetItemTooltip(v.Id == 0
? "Nothing selected. Select with a click or the game's selection keys (- and = go through what's near you).\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: hide."
: $"{v.Name}{(v.Where.Length > 0 ? " - " + v.Where : "")}\nDrag to move; Ctrl+wheel: bigger or smaller; right-click: hide.");
// The picture.
Vector2 ip = origin + new Vector2(pad, pad);
dl.AddRectFilled(ip, ip + new Vector2(icon, icon), v.Id == 0 ? _inset : _key, Px(3));
IntPtr tex = v.Id != 0 ? _host.GetIconTexture(RynthIconKind.Object, v.Id) : IntPtr.Zero;
if (tex != IntPtr.Zero)
dl.AddImageRounded(tex, ip + new Vector2(Px(2), Px(2)), ip + new Vector2(icon - Px(2), icon - Px(2)), Vector2.Zero, Vector2.One, White, Px(2));
dl.AddRect(ip, ip + new Vector2(icon, icon), _line, Px(3));
float tx = ip.X + icon + Px(Gap);
float right = origin.X + width - pad - (hasUse ? useW + Px(Gap) : 0f);
ImFontPtr nf = Font(RynthUiFont.NarrowBold11), sf = Font(RynthUiFont.Narrow9);
if (!v.Ready || v.Id == 0)
{
Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y + Px(1)), _faint, v.Ready ? "Nothing selected" : "Selection", right - tx);
Clip(dl, sf, Fs(sf), new Vector2(tx, ip.Y + icon - Fs(sf)), _faint, "- and = go through what's near you", right - tx);
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
}
// Name, then the health bar (a creature or player) and where it is.
Clip(dl, nf, Fs(nf), new Vector2(tx, ip.Y), _text, v.Name, right - tx);
float lineY = ip.Y + icon - Fs(sf);
float x = tx;
if (!float.IsNaN(v.Relative))
{
float s = Fs(sf);
Arrow(dl, new Vector2(x + s * 0.5f, lineY + s * 0.5f), s * 0.5f, v.Relative, _accent);
x += s + Px(3);
}
if (v.Health >= 0f)
{
float barY = ip.Y + Fs(nf) + Px(3);
float barW = right - tx, barH = Px(BarH);
Vector2 b0 = new(tx, barY), b1 = new(tx + barW, barY + barH);
dl.AddRectFilled(b0, b1, _inset, Px(2));
float f = Math.Clamp(v.Health, 0f, 1f);
if (f > 0f) dl.AddRectFilled(b0, new Vector2(tx + barW * f, barY + barH), f > 0.6f ? A(HealthHigh, 0.9f) : HealthColor, Px(2));
dl.AddRect(b0, b1, _line, Px(2));
string pct = (v.Max > 0 ? $"{v.Current}/{v.Max} " : "") + MathF.Round(f * 100f).ToString(CultureInfo.InvariantCulture) + "%";
float pw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, pct).X;
dl.AddText(sf, Fs(sf), new Vector2(right - pw, lineY), _dim, pct);
Clip(dl, sf, Fs(sf), new Vector2(x, lineY), _dim, v.Where, right - pw - Px(6) - x);
}
else Clip(dl, sf, Fs(sf), new Vector2(x, lineY), _dim, v.Where, right - x);
// USE.
Vector2 up = new(origin.X + width - pad - useW, origin.Y + (height - Px(UseH)) * 0.5f);
ImGui.SetCursorScreenPos(up);
bool use = ImGui.InvisibleButton("##sel_use", new Vector2(useW, Px(UseH)));
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip("Use it, as a double-click does (open a door, talk, pick up, use an item).");
dl.AddRectFilled(up, up + new Vector2(useW, Px(UseH)), hot ? _key : A(_key, 0.6f), Px(3));
dl.AddRect(up, up + new Vector2(useW, Px(UseH)), hot ? _accent : _line, Px(3));
ImFontPtr uf = Font(RynthUiFont.Dash9);
float uw = uf.CalcTextSizeA(Fs(uf), float.MaxValue, 0f, "USE").X;
dl.AddText(uf, Fs(uf), new Vector2(MathF.Round(up.X + (useW - uw) * 0.5f), MathF.Round(up.Y + (Px(UseH) - Fs(uf)) * 0.5f)), hot ? _text : _dim, "USE");
if (use) _use(v.Id);
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
}
/// <summary>Text cut with "..." to <paramref name="room"/> pixels.</summary>
private static void Clip(ImDrawListPtr dl, ImFontPtr f, float size, Vector2 pos, uint color, string text, float room)
{
if (text.Length == 0 || room <= 4) return;
float w = f.CalcTextSizeA(size, float.MaxValue, 0f, text).X;
if (w > room)
{
int n = text.Length;
while (n > 1 && f.CalcTextSizeA(size, float.MaxValue, 0f, text[..n] + "...").X > room) n--;
text = text[..n] + "...";
}
dl.AddText(f, size, new Vector2(MathF.Round(pos.X), MathF.Round(pos.Y)), color, text);
}
/// <summary>A small arrow pointing <paramref name="degrees"/> from straight up (where the player faces), clockwise.</summary>
private static void Arrow(ImDrawListPtr dl, Vector2 c, float r, float degrees, uint color)
{
float a = degrees * MathF.PI / 180f;
Vector2 Dir(float t) => new(MathF.Sin(t), -MathF.Cos(t));
Vector2 tip = c + Dir(a) * r;
Vector2 left = c + Dir(a + 2.45f) * r * 0.85f, rightP = c + Dir(a - 2.45f) * r * 0.85f;
dl.AddTriangleFilled(tip, left, rightP, color);
}
}

View file

@ -0,0 +1,539 @@
// ============================================================================
// RynthDefective - ShortcutBar/ShortcutBarWindow.cs
// The shortcut bar, drawn by RynthDefective in its own frameless window
// (plugin API v90: RynthCore hosts it, "chrome": "none" + "fitHeight"), in
// the instrument look of RynthAi's dashboard and the player's colour theme.
//
// header SHORTCUTS and the slot count (the drag handle; Ctrl+wheel: the
// size), then Edit, Weapons (the weapon picker) and Hide.
// slots the item's picture, its key in the top-left corner (AC's keymap
// for slots 1-18, the engine's hotkeys after), the count or "in
// hand" under it. They fill the window's width and wrap: drag the
// window wider or narrower for one row or several.
// edit the slot numbers show, and - / + at the end take a slot off or
// add one (the player picks how many; 1-18 are the game's).
// Drag an item from AC's pack onto a slot: it goes there, as on the retail
// toolbar (the item stays in the pack). Click a slot: it is used as its key
// would. Right-click: put the selected item there, or empty it, and its keys: remove one, or add one by pressing
// it. A slot 1-18 key is AC's own (its keymap, so the retail toolbar answers
// to it too, in every client); a key past 18 is an engine hotkey running
// /rdef use N. A key comes off whatever had it, after the player says so.
//
// AC's render thread. Reads the snapshot the tick built; every click is
// queued for the tick (IBarActions).
// ============================================================================
using System;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.ShortcutBar;
/// <summary>What the bar asks of the plugin: everything runs on its tick.</summary>
internal interface IBarActions
{
void Use(int number);
void SetFromSelected(int number);
void Clear(int number);
void ChangeSlotCount(int delta);
/// <summary>An item dragged out of AC's UI was let go over slot <paramref name="number"/>.</summary>
void DropItem(int number, uint objectId);
/// <summary>A key was bound or removed: the bar asks for its keys again.</summary>
void KeysChanged();
void ShowWeapons();
void Hide();
}
internal sealed class ShortcutBarWindow
{
public const string Title = "Shortcuts";
private readonly RynthCoreHost _host;
private readonly IBarActions _act;
private bool _edit;
private float _k = 1f, _r = 1f;
public ShortcutBarWindow(RynthCoreHost host, IBarActions actions)
{
_host = host;
_act = actions;
}
private float Px(float v) => v * _k;
/// <summary>A font's size at this scale (its baked size times the text ratio).</summary>
private float Fs(ImFontPtr f) => f.FontSize * _r;
/// <summary>
/// The layout's scale and the text's against the baked font: the window's own size (Settings > UI >
/// Toolbar, Ctrl+wheel: 30-250%, PanelScale) or, unset, the text size the engine baked for it.
/// </summary>
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
private const float PadX = 7, PadTop = 6, PadBottom = 7, Radius = 4, HeaderH = 18, Gap = 3, ChipSize = 16;
private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent;
private static readonly uint InHandColor = Argb(0xFF73D885), MissingColor = Argb(0xFFF98075),
Black = Argb(0xFF000000), White = Argb(0xFFFFFFFF);
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the bar into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw(BarSnapshot view, bool popped)
{
Scale();
_bg = Color(RynthUiColor.Background);
_key = Color(RynthUiColor.KeyFace);
_inset = Color(RynthUiColor.Inset);
_line = Color(RynthUiColor.Hairline);
_text = Color(RynthUiColor.Text);
_dim = Color(RynthUiColor.Muted);
_faint = Color(RynthUiColor.Faint);
_accent = Color(RynthUiColor.Accent);
Vector2 origin = ImGui.GetCursorScreenPos();
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
if (width < 40) return Px(60);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float height;
dl.ChannelsSplit(2);
bool merged = false;
try
{
dl.ChannelsSetCurrent(1);
float x0 = origin.X + Px(PadX), w = width - 2 * Px(PadX);
float y = origin.Y + Px(PadTop);
y = Header(dl, view, x0, y, w);
y += Px(5);
y = Slots(dl, view, x0, y, w);
y += Px(PadBottom);
height = MathF.Ceiling(y - origin.Y);
dl.ChannelsSetCurrent(0);
Frame(dl, origin, new Vector2(width, height));
dl.ChannelsMerge();
merged = true;
}
finally
{
if (!merged) dl.ChannelsMerge();
}
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
SlotMenu(view);
if (_openKeyPopup)
{
_openKeyPopup = false;
ImGui.OpenPopup(KeyPopupId);
}
KeyPopup();
return height;
}
private void Frame(ImDrawListPtr dl, Vector2 min, Vector2 size)
{
Vector2 max = min + size;
float r = Px(Radius);
dl.AddRectFilled(min, max, A(_bg, 0.94f), r);
dl.AddLine(new Vector2(min.X + r, min.Y + 1.5f), new Vector2(max.X - r, min.Y + 1.5f), A(White, 0.05f));
dl.AddRect(min, max, _line, r);
}
// ── Header ────────────────────────────────────────────────────────────
private float Header(ImDrawListPtr dl, BarSnapshot view, float x0, float y, float w)
{
float h = Px(HeaderH), chip = Px(ChipSize);
const int chips = 3;
float chipsW = chips * chip + (chips - 1) * Px(1);
ImGui.SetCursorScreenPos(new Vector2(x0, y));
ImGui.InvisibleButton("##sb_drag", new Vector2(Math.Max(1, w - chipsW - Px(4)), h));
_host.PanelDragWithLastItem();
SafeImGui.SetItemTooltip("Drag to move the bar. Ctrl+wheel here: bigger or smaller.\nDrag the window's edge to change how many slots fit in a row.");
ImFontPtr tf = Font(RynthUiFont.NarrowBold11);
float size = Fs(tf) * 10f / 11f;
float tx = Tracked(dl, tf, size, new Vector2(x0, MathF.Round(y + (h - size) * 0.5f)), _text, "SHORTCUTS", 0.18f * size);
ImFontPtr nf = Font(RynthUiFont.Dash9);
string count = view.Ready ? view.Slots.Length.ToString(System.Globalization.CultureInfo.InvariantCulture) : "";
dl.AddText(nf, Fs(nf), new Vector2(MathF.Round(tx + Px(6)), MathF.Round(y + (h - Fs(nf)) * 0.5f + Px(1))), _faint, count);
float cx = x0 + w - chipsW, cy = y + (h - chip) * 0.5f;
if (Chip("##sb_edit", RynthIcons.PencilSimple, new Vector2(cx, cy), _edit ? _accent : _faint,
_edit ? "Done editing." : "Edit: the slot numbers, and - / + to take a slot off or add one.", _edit))
_edit = !_edit;
cx += chip + Px(1);
if (Chip("##sb_weapons", RynthIcons.Sword, new Vector2(cx, cy), _faint, "Weapons: every weapon and wand you carry, wield one with a click."))
_act.ShowWeapons();
cx += chip + Px(1);
if (Chip("##sb_hide", RynthIcons.X, new Vector2(cx, cy), _faint, "Hide the bar (/rdef shows it again). Its keys keep working."))
_act.Hide();
return y + h;
}
private bool Chip(string id, string icon, Vector2 pos, uint color, string tip, bool held = false)
{
Vector2 size = new(Px(ChipSize), Px(ChipSize));
ImGui.SetCursorScreenPos(pos);
bool clicked = ImGui.InvisibleButton(id, size);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(tip);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
if (hot || held) dl.AddRectFilled(pos, pos + size, _key, Px(3));
DrawIcon(dl, icon, pos, size, Px(11), hot ? _text : color);
return clicked;
}
// ── Slots ─────────────────────────────────────────────────────────────
private int _menuSlot;
private const string MenuId = "##sb_slot_menu";
private float Slots(ImDrawListPtr dl, BarSnapshot view, float x0, float y, float w)
{
if (!view.Ready)
{
ImFontPtr f = Font(RynthUiFont.Narrow10);
dl.AddText(f, Fs(f), new Vector2(x0, y), _faint, "Your shortcuts show once you're in the world.");
return y + Fs(f) + Px(2);
}
float cell = Px(Math.Clamp(view.IconSize, 20, 64)), gap = Px(Gap);
int cells = view.Slots.Length + (_edit ? 2 : 0);
int perRow = Math.Max(1, (int)MathF.Floor((w + gap) / (cell + gap)));
int rows = (cells + perRow - 1) / perRow;
// Items dragged out of AC's UI: the slots' area takes them (the engine keeps the drop from AC).
Vector2 areaMin = new(x0, y), areaMax = new(x0 + perRow * (cell + gap), y + rows * (cell + gap));
uint dropped = _host.HasDropTargets ? _host.DropTarget(Title, areaMin, areaMax, true, out _dragging) : 0;
int under = SlotAt(ImGui.GetIO().MousePos, x0, y, cell, gap, perRow, view.Slots.Length);
_dropSlot = _dragging ? under : 0;
if (dropped != 0 && under > 0) _act.DropItem(under, dropped);
for (int i = 0; i < cells; i++)
{
int col = i % perRow, row = i / perRow;
Vector2 p = new(MathF.Round(x0 + col * (cell + gap)), MathF.Round(y + row * (cell + gap)));
if (i < view.Slots.Length) Slot(dl, view.Slots[i], p, cell);
else EditButton(dl, i == view.Slots.Length ? -1 : 1, p, cell, view.Slots.Length);
}
return y + rows * (cell + gap) - gap;
}
private bool _dragging;
private int _dropSlot;
/// <summary>The slot number (1-based) under <paramref name="m"/>, or 0.</summary>
private static int SlotAt(Vector2 m, float x0, float y0, float cell, float gap, int perRow, int count)
{
if (m.X < x0 || m.Y < y0) return 0;
int col = (int)((m.X - x0) / (cell + gap)), row = (int)((m.Y - y0) / (cell + gap));
if (col >= perRow || m.X - x0 - col * (cell + gap) > cell || m.Y - y0 - row * (cell + gap) > cell) return 0;
int i = row * perRow + col;
return i < count ? i + 1 : 0;
}
private void Slot(ImDrawListPtr dl, BarSlot s, Vector2 p, float cell)
{
Vector2 size = new(cell, cell);
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(Id("##sb_slot", s.Number), size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight)
&& ImGui.IsMouseReleased(ImGuiMouseButton.Left);
bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(s.Tooltip);
float r = Px(3);
// The well, the picture, a hairline (the accent under the mouse; green while in hand).
dl.AddRectFilled(p, p + size, s.Empty ? _inset : _key, r);
if (!s.Empty)
{
uint id = s.ObjectId != 0 ? s.ObjectId : s.SpellId;
IntPtr tex = id == 0 ? IntPtr.Zero : _host.GetIconTexture(s.ObjectId != 0 ? RynthIconKind.Object : RynthIconKind.Spell, id);
float inset = Px(2);
if (tex != IntPtr.Zero)
dl.AddImageRounded(tex, p + new Vector2(inset, inset), p + size - new Vector2(inset, inset), Vector2.Zero, Vector2.One,
s.Tone == CountTone.Missing ? A(White, 0.35f) : White, Px(2));
else
{
ImFontPtr af = Font(RynthUiFont.Narrow9);
string abbr = Abbrev(s.Name);
float aw = af.CalcTextSizeA(Fs(af), float.MaxValue, 0f, abbr).X;
dl.AddText(af, Fs(af), new Vector2(MathF.Round(p.X + (cell - aw) * 0.5f), MathF.Round(p.Y + (cell - Fs(af)) * 0.5f)), _dim, abbr);
}
}
uint border = hot || _dropSlot == s.Number ? _accent : s.Tone == CountTone.InHand ? A(InHandColor, 0.8f) : _line;
dl.AddRect(p, p + size, border, r, ImDrawFlags.None, _dropSlot == s.Number ? Px(2) : 1f);
// The key, top left (a dark plate under it so it reads over any picture); edit: the slot number.
ImFontPtr kf = Font(RynthUiFont.Dash9);
string label = _edit ? s.Number.ToString(System.Globalization.CultureInfo.InvariantCulture) : s.Key;
if (label.Length > 0)
{
float lw = kf.CalcTextSizeA(Fs(kf), float.MaxValue, 0f, label).X;
Vector2 lp = p + new Vector2(Px(2), Px(1));
dl.AddRectFilled(lp - new Vector2(Px(1), 0), lp + new Vector2(lw + Px(1), Fs(kf)), A(Black, 0.55f), Px(2));
dl.AddText(kf, Fs(kf), lp, _edit ? _accent : s.Retail ? _text : _accent, label);
}
// The count, bottom right.
if (!_edit && s.Count.Length > 0)
{
string c = s.Count == "in hand" ? "hand" : s.Count;
float cw = kf.CalcTextSizeA(Fs(kf), float.MaxValue, 0f, c).X;
Vector2 cp = p + new Vector2(cell - cw - Px(2), cell - Fs(kf) - Px(1));
dl.AddRectFilled(cp - new Vector2(Px(1), 0), cp + new Vector2(cw + Px(1), Fs(kf)), A(Black, 0.55f), Px(2));
uint cc = s.Tone == CountTone.InHand ? InHandColor : s.Tone == CountTone.Missing ? MissingColor : _text;
dl.AddText(kf, Fs(kf), cp, cc, c);
}
if (clicked && !s.Empty) _act.Use(s.Number);
if (right)
{
_menuSlot = s.Number;
ImGui.OpenPopup(MenuId);
}
}
private void EditButton(ImDrawListPtr dl, int delta, Vector2 p, float cell, int count)
{
Vector2 size = new(cell, cell);
bool can = delta < 0 ? count > DefSettings.BarSlotsMin : count < DefSettings.BarSlotsMax;
ImGui.SetCursorScreenPos(p);
bool clicked = ImGui.InvisibleButton(delta < 0 ? "##sb_less" : "##sb_more", size);
bool hot = can && ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(delta < 0
? "One slot fewer (the last one's item stays: add the slot back and it is there)."
: count < DefSettings.RetailSlots ? "One more slot (the game's own, up to 18)."
: "One more slot (RynthCore's: the game's toolbar holds 18).");
float r = Px(3);
dl.AddRect(p, p + size, hot ? _accent : A(_line, can ? 1f : 0.4f), r);
DrawIcon(dl, delta < 0 ? RynthIcons.Minus : RynthIcons.Plus, p, size, Px(12), can ? (hot ? _text : _dim) : A(_faint, 0.5f));
if (clicked && can) _act.ChangeSlotCount(delta);
}
private void SlotMenu(BarSnapshot view)
{
if (!ImGui.IsPopupOpen(MenuId)) return;
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
ImGui.PushStyleColor(ImGuiCol.Border, _line);
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(6), Px(5)));
bool open = ImGui.BeginPopup(MenuId);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
if (!open) return;
try
{
BarSlot? s = _menuSlot >= 1 && _menuSlot <= view.Slots.Length ? view.Slots[_menuSlot - 1] : null;
if (s == null) { ImGui.CloseCurrentPopup(); return; }
ImGui.TextDisabled($"Slot {s.Number}{(s.Retail ? " (the game's own)" : " (RynthCore's)")}");
if (s.Name.Length > 0) SafeImGui.Text(s.Name);
ImGui.Separator();
bool hasSelection = _host.HasGetSelectedItemId && _host.GetSelectedItemId() != 0;
if (ImGui.MenuItem("Put the selected item here", null, false, hasSelection)) _act.SetFromSelected(s.Number);
if (ImGui.MenuItem("Empty this slot", null, false, !s.Empty)) _act.Clear(s.Number);
ImGui.Separator();
if (!_host.HasKeyBinding)
{
ImGui.TextDisabled(s.AllKeys.Length > 0 ? "Keys: " + s.AllKeys
: s.Retail ? "No key: bind UseQuickSlot_" + s.Number + " in Configure Keyboard." : "No key: /rdef bind " + (s.Number - DefSettings.RetailSlots) + " F9");
return;
}
string[] keys = SplitKeys(s.AllKeys);
ImGui.TextDisabled(keys.Length == 0 ? "No key yet" : keys.Length == 1 ? "Key" : "Keys");
foreach (string key in keys)
{
if (!ImGui.MenuItem("Remove " + key)) continue;
if (_host.UnbindActionKey(KeyAction(s.Number), key, out string why)) _act.KeysChanged();
else ShowKeyMessage(s.Number, why);
}
if (ImGui.MenuItem(keys.Length == 0 ? "Add a key..." : "Add another key..."))
StartKeyCapture(s.Number);
SafeImGui.SetItemTooltip(s.Retail
? "Press the key: it becomes this slot's in the game's own keymap, so the retail toolbar and every client use it too."
: "Press the key: a RynthCore hotkey for this slot (the game's toolbar holds 18).");
}
finally { ImGui.EndPopup(); }
}
// ── Keys: "press a key" ───────────────────────────────────────────────
private enum KeyStep { Waiting, Confirm, Message }
private const string KeyPopupId = "##sb_key_popup";
private bool _openKeyPopup;
private int _keySlot;
private KeyStep _keyStep;
private string _keyName = string.Empty, _keyText = string.Empty;
/// <summary>The action a slot's keys run: AC's UseQuickSlot_N for 1-18, the engine command for the rest.</summary>
public static string KeyAction(int number) =>
number <= DefSettings.RetailSlots ? "UseQuickSlot_" + number : DefCommandParser.UseCommand(number - DefSettings.RetailSlots);
private static string[] SplitKeys(string keys) =>
keys.Length == 0 ? Array.Empty<string>() : keys.Split(", ", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
private void StartKeyCapture(int number)
{
_keySlot = number;
_keyStep = KeyStep.Waiting;
_keyName = _keyText = string.Empty;
_host.BeginKeyCapture();
_openKeyPopup = true;
}
private void ShowKeyMessage(int number, string text)
{
_keySlot = number;
_keyStep = KeyStep.Message;
_keyText = text;
_openKeyPopup = true;
}
private void KeyPopup()
{
if (!ImGui.IsPopupOpen(KeyPopupId))
{
if (_keyStep == KeyStep.Waiting && _keySlot != 0) { _host.CancelKeyCapture(); _keySlot = 0; } // clicked away
return;
}
ImGui.PushStyleColor(ImGuiCol.PopupBg, WithAlpha(_bg, 0xFA));
ImGui.PushStyleColor(ImGuiCol.Border, _line);
ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, Px(4));
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(Px(8), Px(7)));
bool open = ImGui.BeginPopup(KeyPopupId);
ImGui.PopStyleVar(2);
ImGui.PopStyleColor(2);
if (!open) return;
try
{
ImGui.PushTextWrapPos(ImGui.GetCursorPosX() + Px(230));
ImGui.TextDisabled($"Slot {_keySlot}{(_keySlot <= DefSettings.RetailSlots ? " (the game's own)" : " (RynthCore's)")}");
switch (_keyStep)
{
case KeyStep.Waiting:
SafeImGui.Text("Press the key for this slot.");
ImGui.TextDisabled("Hold Ctrl, Alt or Shift with it if you like. Esc cancels.");
RynthKeyCapture got = _host.PollKeyCapture(out string text);
if (got == RynthKeyCapture.Waiting)
{
if (text.Length > 0) ImGui.TextColored(new Vector4(0.98f, 0.5f, 0.46f, 1f), text);
break;
}
if (got == RynthKeyCapture.Cancelled) { _keySlot = 0; ImGui.CloseCurrentPopup(); break; }
_keyName = text;
RynthKeyCheck check = _host.CheckActionKey(KeyAction(_keySlot), _keyName, out string msg);
if (check == RynthKeyCheck.Free) Bind();
else
{
_keyStep = check == RynthKeyCheck.Taken ? KeyStep.Confirm : KeyStep.Message;
_keyText = msg;
}
break;
case KeyStep.Confirm:
SafeImGui.Text(_keyText);
ImGui.TextDisabled($"Use it for slot {_keySlot} instead? It comes off those.");
if (ImGui.Button($"Use {_keyName} here")) Bind();
ImGui.SameLine();
if (ImGui.Button("Another key")) StartKeyCapture(_keySlot);
ImGui.SameLine();
if (ImGui.Button("Cancel")) { _keySlot = 0; ImGui.CloseCurrentPopup(); }
break;
case KeyStep.Message:
SafeImGui.Text(_keyText);
if (ImGui.Button("Another key")) StartKeyCapture(_keySlot);
ImGui.SameLine();
if (ImGui.Button("Close")) { _keySlot = 0; ImGui.CloseCurrentPopup(); }
break;
}
ImGui.PopTextWrapPos();
}
finally { ImGui.EndPopup(); }
}
private void Bind()
{
if (_host.BindActionKey(KeyAction(_keySlot), _keyName, out string why))
{
_act.KeysChanged();
_keySlot = 0;
ImGui.CloseCurrentPopup();
return;
}
_keyStep = KeyStep.Message;
_keyText = why;
}
// ── Helpers ───────────────────────────────────────────────────────────
private static readonly System.Collections.Generic.Dictionary<(string, int), string> Ids = new();
private static string Id(string prefix, int n)
{
if (!Ids.TryGetValue((prefix, n), out string? id)) Ids[(prefix, n)] = id = prefix + n;
return id;
}
private static string Abbrev(string name)
{
if (name.Length == 0) return "?";
string[] words = name.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (words.Length >= 2) return string.Concat(char.ToUpperInvariant(words[0][0]), char.ToUpperInvariant(words[^1][0]));
return name.Length <= 3 ? name : name[..3];
}
private static readonly string[] Chars = BuildChars();
private static string[] BuildChars()
{
var a = new string[128];
for (int i = 32; i < 127; i++) a[i] = ((char)i).ToString();
return a;
}
/// <summary>Text with <paramref name="spacing"/> pixels between its letters. Returns the x after it.</summary>
private static float Tracked(ImDrawListPtr dl, ImFontPtr font, float size, Vector2 pos, uint color, string text, float spacing)
{
unsafe { if (font.NativePtr == null || text.Length == 0) return pos.X; }
float scale = size / font.FontSize;
float x = pos.X;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
string s = c < 128 && Chars[c] != null ? Chars[c] : c.ToString();
dl.AddText(font, size, new Vector2(MathF.Round(x), pos.Y), color, s);
x += font.GetCharAdvance(c) * scale;
if (i < text.Length - 1) x += spacing;
}
return x;
}
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (from Ui18's bake).</summary>
private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
{
if (string.IsNullOrEmpty(glyph)) return;
ImFontPtr font = Font(RynthUiFont.Ui18);
if (font.NativePtr == null) return;
byte* g = (byte*)ImGuiNative.ImFont_FindGlyphNoFallback(font.NativePtr, glyph[0]);
if (g == null) return;
float advance = *(float*)(g + 4);
if (advance <= 0) return;
float* box = (float*)(g + 8);
float scale = px / advance;
Vector2 centre = new((box[0] + box[2]) * 0.5f * scale, (box[1] + box[3]) * 0.5f * scale);
Vector2 at = min + size * 0.5f - centre;
dl.AddText(font, font.FontSize * scale, new Vector2(MathF.Round(at.X), MathF.Round(at.Y)), color, glyph);
}
}

View file

@ -0,0 +1,132 @@
using System;
namespace RynthCore.Plugin.RynthDefective.Ui;
/// <summary>
/// Display-list format 1 for the engine's script windows (RynthSuite
/// Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2-4.3; the engine's DisplayListParser.cs is the source of
/// truth). Little-endian. Only the ops RynthDefective draws are listed.
/// </summary>
internal static class UiFormat
{
public const uint Magic = 0x31575352; // 'RSW1'
public const ushort FormatVersion = 1;
public const uint BodyUnchanged = 0xFFFFFFFF;
public const int MaxString = 4096;
public const int MaxStr8 = 128;
public const int MaxOps = 1500; // engine limit per window
public const int MaxBodyBytes = 64 * 1024; // engine limit per window
public const byte OpHasBlock = 1;
// Ops
public const byte OpEnd = 0x00;
public const byte OpText = 0x01;
public const byte OpTextColored = 0x02;
public const byte OpTextWrapped = 0x03;
public const byte OpTextDisabled = 0x04;
public const byte OpBulletText = 0x05;
public const byte OpSeparatorText = 0x06;
public const byte OpSeparator = 0x10;
public const byte OpSameLine = 0x11;
public const byte OpSpacing = 0x13;
public const byte OpDummy = 0x14;
public const byte OpIndent = 0x15;
public const byte OpUnindent = 0x16;
public const byte OpButton = 0x20;
public const byte OpCheckbox = 0x21;
public const byte OpSliderInt = 0x22;
public const byte OpInputText = 0x24;
public const byte OpCombo = 0x25;
public const byte OpSelectable = 0x26;
public const byte OpProgressBar = 0x27;
public const byte OpImage = 0x28; // op level 2 (engines from 2026-09-30)
public const byte OpImageButton = 0x29;
public const byte OpPushID = 0x30;
public const byte OpPopID = 0x31;
public const byte OpPushStyleColor = 0x32;
public const byte OpPopStyleColor = 0x33;
public const byte OpSetItemTooltip = 0x38;
public const byte OpChild = 0x40;
public const byte OpCollapsingHeader = 0x41;
// Window flags
public const uint FlagVisible = 1u << 0;
public const uint FlagShowInBar = 1u << 1;
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
public const uint FlagBarButton = 1u << 11;
public const uint FlagNoScrollbar = 1u << 5;
// Image icon kinds (op level 2)
public const byte IconKindIcon = 0; // a 0x06 texture id
public const byte IconKindObject = 1; // a live object's icon with underlay and overlay
// Selectable flags
public const uint SelectableAllowDoubleClick = 4;
// Event types
public const ushort EvClicked = 1;
public const ushort EvBool = 2;
public const ushort EvInt = 3;
public const ushort EvText = 5;
public const ushort EvOpen = 6;
public const ushort EvVisibility = 8;
public const ushort EvError = 10;
// ImGuiCol ids the engine accepts in PushStyleColor (ImGui.NET 1.91.6.1)
public const int ColText = 0;
public const int ColButton = 21;
public const int ColButtonActive = 23;
public const int ColButtonHovered = 22;
public const int ColHeader = 24;
// InputText flags
public const uint InputAutoSelectAll = 4096;
/// <summary>The text box reports Enter (its event carries submitted = true).</summary>
public const uint InputEnterReturnsTrue = 32;
// CollapsingHeader flags
public const uint TreeDefaultOpen = 32;
public static uint Fnv1a(ReadOnlySpan<byte> bytes, uint hash = 2166136261)
{
foreach (byte b in bytes)
{
hash ^= b;
hash *= 16777619;
}
return hash;
}
/// <summary>The length of <paramref name="s"/> cut to at most <paramref name="max"/> bytes without splitting a character.</summary>
public static int CutUtf8(ReadOnlySpan<byte> s, int max)
{
if (s.Length <= max) return s.Length;
int n = Math.Max(0, max);
while (n > 0 && (s[n] & 0xC0) == 0x80) n--;
return n;
}
/// <summary>An ImGui U32 colour (0xAABBGGRR) from RGB bytes.</summary>
public static uint Rgb(byte r, byte g, byte b, byte a = 255) =>
((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r;
}
/// <summary>Colours RynthDefective uses (0xAABBGGRR).</summary>
internal static class UiColors
{
public static readonly uint Green = UiFormat.Rgb(110, 210, 110);
public static readonly uint Red = UiFormat.Rgb(225, 95, 95);
public static readonly uint Yellow = UiFormat.Rgb(235, 205, 90);
public static readonly uint Grey = UiFormat.Rgb(150, 150, 150);
public static readonly uint Gold = UiFormat.Rgb(230, 180, 60);
/// <summary>Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220).</summary>
public static readonly uint Destruction = UiFormat.Rgb(255, 30, 220);
public static readonly uint TabActive = UiFormat.Rgb(60, 110, 170);
public static readonly uint TabActiveHover = UiFormat.Rgb(75, 130, 195);
public static readonly uint OtherServer = UiFormat.Rgb(150, 185, 235);
public static readonly uint Stale = UiFormat.Rgb(225, 150, 80);
public static readonly uint White = UiFormat.Rgb(255, 255, 255);
/// <summary>The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25.</summary>
public static readonly uint Amber = UiFormat.Rgb(255, 191, 64);
}

View file

@ -0,0 +1,202 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Text;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Ui;
/// <summary>
/// The plugin's side of the engine's script windows (API v71): polls the engine's events into
/// the windows' handlers and submits the window set when something changed. Plugin pump thread
/// only (inside the plugin's own tick), as the engine requires.
/// </summary>
internal sealed class UiHost
{
private readonly List<UiWindow> _windows = new();
private readonly Dictionary<uint, UiWindow> _byHash = new();
private byte[] _events = new byte[8192];
private byte[] _submit = new byte[64 * 1024];
private uint _lastSeq;
private bool _submittedSomething;
private long _retryAtMs;
private long _lastErrorLogMs;
public Action<string>? Log;
public IReadOnlyList<UiWindow> Windows => _windows;
public UiWindow Add(UiWindow w)
{
_windows.Add(w);
_byHash[w.Hash] = w;
return w;
}
/// <summary>Drains the engine's queued events into the windows' handlers.</summary>
public void Poll(RynthCoreHost host)
{
if (!host.HasUi || !_submittedSomething) return;
for (int round = 0; round < 8; round++)
{
int n = host.UiPollEvents(_events, out int remaining);
if (n > 0) Apply(_events.AsSpan(0, n));
if (remaining == 0) break;
if (n == 0) Array.Resize(ref _events, _events.Length * 2); // one event didn't fit
}
}
private void Apply(ReadOnlySpan<byte> data)
{
int pos = 0;
while (data.Length - pos >= 16)
{
ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
if (size < 16 || size > data.Length - pos) break;
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]);
uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]);
uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]);
ReadOnlySpan<byte> p = data.Slice(pos + 16, size - 16);
pos += size;
if (seq > _lastSeq) _lastSeq = seq;
_byHash.TryGetValue(window, out UiWindow? w);
switch (type)
{
case UiFormat.EvClicked when w != null && p.Length >= 2:
int count = BinaryPrimitives.ReadUInt16LittleEndian(p);
for (int i = 0; i < Math.Min(count, 4); i++) w.Dispatch(key, new UiEvent(type));
break;
case UiFormat.EvBool when w != null && p.Length >= 1:
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
break;
case UiFormat.EvInt when w != null && p.Length >= 4:
w.Dispatch(key, new UiEvent(type, i: BinaryPrimitives.ReadInt32LittleEndian(p)));
break;
case UiFormat.EvText when w != null && p.Length >= 3:
{
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3);
w.Dispatch(key, new UiEvent(type, text: Encoding.UTF8.GetString(p.Slice(3, n)), submitted: p[0] != 0));
break;
}
case UiFormat.EvOpen when w != null && p.Length >= 1:
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
break;
case UiFormat.EvVisibility when w != null && p.Length >= 1:
// The player closed it (X) or opened it (bar menu / command): theirs wins.
w.Visible = p[0] != 0;
w.NeedsPass = true;
break;
case UiFormat.EvError when p.Length >= 2:
{
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2);
Log?.Invoke("[RynthDefective] window error: " + Encoding.UTF8.GetString(p.Slice(2, n)));
break;
}
}
}
}
/// <summary>Sends the window set when any window's list or header changed.</summary>
public void Submit(RynthCoreHost host, long nowMs)
{
if (!host.HasUi || nowMs < _retryAtMs) return;
bool changed = !_submittedSomething && _windows.Count > 0;
foreach (UiWindow w in _windows)
if (w.BodyDirty || w.HeaderDirty) { changed = true; break; }
if (!changed) return;
int pos = Write();
int rc = host.UiSubmit(_submit.AsSpan(0, pos));
if (rc == 0)
{
foreach (UiWindow w in _windows) w.MarkSubmitted(w.BodyDirty);
_submittedSomething = true;
}
else
{
// Nothing was applied; the engine keeps the previous lists. Try again in a second.
_retryAtMs = nowMs + 1000;
if (nowMs - _lastErrorLogMs > 10_000)
{
_lastErrorLogMs = nowMs;
Log?.Invoke($"[RynthDefective] the engine refused the window list ({rc}).");
}
}
}
/// <summary>Removes every window from the engine (logout, shutdown). Their placement is kept by the engine.</summary>
public void SubmitEmpty(RynthCoreHost host)
{
if (!host.HasUi || !_submittedSomething) return;
Span<byte> b = stackalloc byte[16];
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], 0);
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], 16);
if (host.UiSubmit(b) == 0)
{
_submittedSomething = false;
foreach (UiWindow w in _windows) w.ForgetSubmitted();
}
}
private int Write()
{
int size = 16;
foreach (UiWindow w in _windows) size += 2 * (1 + UiFormat.MaxStr8) + 4 + 32 + 8 + (w.BodyDirty ? w.Body.Length : 0);
if (_submit.Length < size) _submit = new byte[Math.Max(size, _submit.Length * 2)];
Span<byte> b = _submit;
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], (ushort)_windows.Count);
// Every event polled so far has been applied (handlers run as they arrive).
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
int pos = 16;
foreach (UiWindow w in _windows)
{
pos = Str8(b, pos, w.KeyUtf8);
pos = Str8(b, pos, Encoding.UTF8.GetBytes(w.Title ?? string.Empty));
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.Flags); pos += 4;
pos = F32(b, pos, w.DefaultWidth);
pos = F32(b, pos, w.DefaultHeight);
pos = F32(b, pos, w.MinWidth);
pos = F32(b, pos, w.MinHeight);
pos = F32(b, pos, w.RequestWidth); // RequestSize: a one-shot, else none
pos = F32(b, pos, w.RequestHeight);
pos = F32(b, pos, float.NaN); // RequestPos: none
pos = F32(b, pos, float.NaN);
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.ListSeq); pos += 4;
if (w.BodyDirty)
{
ReadOnlySpan<byte> body = w.Body;
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], (uint)body.Length); pos += 4;
body.CopyTo(b[pos..]);
pos += body.Length;
}
else
{
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], UiFormat.BodyUnchanged); pos += 4;
}
}
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], (uint)pos);
return pos;
}
private static int Str8(Span<byte> b, int pos, ReadOnlySpan<byte> s)
{
int n = UiFormat.CutUtf8(s, UiFormat.MaxStr8);
b[pos] = (byte)n;
s[..n].CopyTo(b[(pos + 1)..]);
return pos + 1 + n;
}
private static int F32(Span<byte> b, int pos, float v)
{
BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v);
return pos + 4;
}
}

View file

@ -0,0 +1,543 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Plugin.RynthDefective.Ui;
/// <summary>One input from the engine for a widget (a click, a new value, an open state).</summary>
internal readonly struct UiEvent
{
public readonly ushort Type;
public readonly bool Bool;
public readonly int Int;
public readonly string Text;
public readonly bool Submitted;
public UiEvent(ushort type, bool b = false, int i = 0, string? text = null, bool submitted = false)
{
Type = type;
Bool = b;
Int = i;
Text = text ?? string.Empty;
Submitted = submitted;
}
}
/// <summary>
/// One script window (engine API v71) and its recorder. A render pass records ImGui-style calls
/// into a display list; every widget's handler (click, value change) is kept by its widget key
/// until the next pass, so an event from the engine runs the code that drew that widget.
///
/// Widget keys are FNV-1a(id, window hash): RynthDefective names every widget itself, so it needs
/// no ID stack. ImGui sees "label###id": its ID comes from the id alone, so labels can change.
/// The engine echoes the key in events and keys its per-widget local values by it.
/// </summary>
internal sealed class UiWindow
{
public readonly string Key;
public readonly byte[] KeyUtf8;
public readonly uint Hash;
public string Title;
public bool Visible;
public bool ShowInBar = true;
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
/// tooltip) rather than a line in the Scripts menu.</summary>
public bool BarButton = true;
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
/// <summary>
/// A one-shot request for the window's size (logical units; NaN = none). Sent with the next
/// submit and then forgotten: the engine re-applies a standing request on every re-recorded
/// list, which would undo the player's own resizing.
/// </summary>
public float RequestWidth = float.NaN, RequestHeight = float.NaN;
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
public bool NeedsPass = true;
public long NextPassMs;
// The list as recorded by the last pass, and what the engine last accepted.
private byte[] _body = new byte[16 * 1024];
private int _len;
private int _ops;
private bool _cut;
private byte[] _sentBody = Array.Empty<byte>();
private int _sentLen = -1;
public uint ListSeq { get; private set; }
internal bool BodyDirty;
// Header as last accepted by the engine.
private string? _sentTitle;
private uint _sentFlags;
private float _sentDw = float.NaN, _sentDh, _sentMw, _sentMh;
private Dictionary<uint, Action<UiEvent>> _handlers = new();
private Dictionary<uint, Action<UiEvent>> _next = new();
private readonly Dictionary<uint, bool> _openStates = new();
// Child blocks: where each open block's u32 length sits, or -1 when the block was dropped.
private readonly int[] _blocks = new int[16];
private int _blockDepth;
private byte[] _tmp = new byte[512];
public UiWindow(string key, string title)
{
Key = key;
KeyUtf8 = Encoding.UTF8.GetBytes(key);
Hash = UiFormat.Fnv1a(KeyUtf8);
Title = title;
}
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
public bool HeaderDirty =>
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
|| _sentMw != MinWidth || _sentMh != MinHeight || !float.IsNaN(RequestWidth);
public ReadOnlySpan<byte> Body => _body.AsSpan(0, _len);
// ── Pass ────────────────────────────────────────────────────────────────
public void Begin()
{
_len = 0;
_ops = 0;
_cut = false;
_blockDepth = 0;
_next.Clear();
}
/// <summary>Ends the pass: closes open blocks, writes End, and notes whether the list changed.</summary>
public void End()
{
while (_blockDepth > 0) EndChild();
if (_cut)
{
// Room was kept for this line (see Room).
int p = BeginOp(UiFormat.OpTextDisabled);
Str("(more than fits in one window; narrow the list)");
EndOp(p);
}
Ensure(4);
_body[_len++] = UiFormat.OpEnd;
_body[_len++] = 0;
_body[_len++] = 0;
_body[_len++] = 0;
(_handlers, _next) = (_next, _handlers);
bool differs = _sentLen != _len || !_body.AsSpan(0, _len).SequenceEqual(_sentBody.AsSpan(0, _sentLen));
if (differs && !BodyDirty) ListSeq++;
BodyDirty = differs;
}
/// <summary>The engine accepted the last submit: remember what it now has.</summary>
internal void MarkSubmitted(bool bodySent)
{
if (bodySent)
{
if (_sentBody.Length < _len) _sentBody = new byte[_body.Length];
_body.AsSpan(0, _len).CopyTo(_sentBody);
_sentLen = _len;
BodyDirty = false;
}
_sentTitle = Title;
_sentFlags = Flags;
_sentDw = DefaultWidth; _sentDh = DefaultHeight; _sentMw = MinWidth; _sentMh = MinHeight;
RequestWidth = RequestHeight = float.NaN; // sent once
}
/// <summary>The engine dropped every window (logout, empty submit): send everything again next time.</summary>
internal void ForgetSubmitted()
{
_sentLen = -1;
_sentTitle = null;
BodyDirty = _len > 0;
}
internal void Dispatch(uint widgetKey, in UiEvent e)
{
if (_handlers.TryGetValue(widgetKey, out Action<UiEvent>? h))
h(e);
NeedsPass = true;
}
// ── Widgets ─────────────────────────────────────────────────────────────
public uint KeyOf(string id)
{
int max = Encoding.UTF8.GetMaxByteCount(id.Length);
if (_tmp.Length < max) _tmp = new byte[Math.Max(max, _tmp.Length * 2)];
int n = Encoding.UTF8.GetBytes(id, _tmp);
return UiFormat.Fnv1a(_tmp.AsSpan(0, n), Hash);
}
public void Text(string text) => WriteText(UiFormat.OpText, text);
public void TextDisabled(string text) => WriteText(UiFormat.OpTextDisabled, text);
public void TextWrapped(string text) => WriteText(UiFormat.OpTextWrapped, text);
public void BulletText(string text) => WriteText(UiFormat.OpBulletText, text);
public void SeparatorText(string text) => WriteText(UiFormat.OpSeparatorText, text);
public void TextColored(uint abgr, string text)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpTextColored);
U32(abgr);
Str(text);
EndOp(p);
}
public void Separator()
{
if (!Room()) return;
EndOp(BeginOp(UiFormat.OpSeparator));
}
public void Spacing()
{
if (!Room()) return;
EndOp(BeginOp(UiFormat.OpSpacing));
}
/// <summary>Next item on the same line, <paramref name="x"/> logical units from the content start (0 = right after).</summary>
public void SameLine(float x = 0f, float spacing = -1f)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpSameLine);
F32(x);
F32(spacing);
EndOp(p);
}
public void Dummy(float w, float h)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpDummy);
F32(w);
F32(h);
EndOp(p);
}
/// <summary>Moves the following items right by <paramref name="w"/> logical units, until <see cref="Unindent"/>.</summary>
public void Indent(float w)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpIndent);
F32(w);
EndOp(p);
}
public void Unindent(float w)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpUnindent);
F32(w);
EndOp(p);
}
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpButton);
U32(key);
Str(label + "###" + id);
F32(w);
F32(h);
U8(small ? (byte)1 : (byte)0);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
}
public void SmallButton(string label, string id, Action onClick) => Button(label, id, onClick, small: true);
/// <summary>A button drawn highlighted when <paramref name="active"/> (tabs, toggles).</summary>
public void ToggleButton(string label, string id, bool active, Action onClick, bool small = false)
{
if (active)
{
PushStyleColor(UiFormat.ColButton, UiColors.TabActive);
PushStyleColor(UiFormat.ColButtonHovered, UiColors.TabActiveHover);
}
Button(label, id, onClick, small: small);
if (active) PopStyleColor(2);
}
public void Checkbox(string label, string id, bool value, Action<bool> set)
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpCheckbox);
U32(key);
Str(label + "###" + id);
U8(value ? (byte)1 : (byte)0);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvBool) set(e.Bool); };
}
/// <summary>An integer slider from <paramref name="min"/> to <paramref name="max"/> (clamped by the engine).</summary>
public void SliderInt(string label, string id, int value, int min, int max, Action<int> set, string format = "%d")
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpSliderInt);
U32(key);
Str(label + "###" + id);
I32(value);
I32(min);
I32(max);
Str(format);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(Math.Clamp(e.Int, min, max)); };
}
/// <summary>A text box; <paramref name="set"/> gets every edit (submitted = Enter was pressed).</summary>
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0) =>
InputText(label, id, value, maxLen, (text, _) => set(text), flags);
/// <summary>A text box; <paramref name="set"/> gets every edit and whether Enter was pressed.</summary>
public void InputText(string label, string id, string value, int maxLen, Action<string, bool> set, uint flags = 0)
{
if (!Room()) return;
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpInputText);
U32(key);
Str(label + "###" + id);
Str(value ?? string.Empty, maxLen);
U16((ushort)maxLen);
U32(flags);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); };
}
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)
{
if (!Room()) return;
uint key = KeyOf(id);
int count = Math.Min(items.Count, 512);
int p = BeginOp(UiFormat.OpCombo);
U32(key);
Str(label + "###" + id);
I32(index);
U16((ushort)count);
for (int i = 0; i < count; i++) Str(items[i]);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(e.Int); };
}
public void Selectable(string label, string id, bool selected, Action onClick, float w = 0f, float h = 0f)
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpSelectable);
U32(key);
Str(label + "###" + id);
U8(selected ? (byte)1 : (byte)0);
U32(0);
F32(w);
F32(h);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
}
public void ProgressBar(float fraction, float w, float h, string overlay)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpProgressBar);
F32(float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f);
F32(w);
F32(h);
Str(overlay ?? string.Empty);
EndOp(p);
}
/// <summary>
/// An icon (op level 2): <paramref name="kind"/> <see cref="UiFormat.IconKindIcon"/> = a 0x06
/// texture id, <see cref="UiFormat.IconKindObject"/> = a live object (its icon with underlay and
/// overlay). Engines without op level 2 skip it (the caller checks first so the layout doesn't shift).
/// </summary>
public void Image(byte kind, uint id, float w, float h, uint tint = 0xFFFFFFFFu)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpImage);
U8(kind);
U32(id);
F32(w);
F32(h);
F32(0f); F32(0f); // uv0
F32(1f); F32(1f); // uv1
U32(tint);
U32(0u); // border: none
EndOp(p);
}
/// <summary>A button with an icon on it (op level 2); <paramref name="tint"/> dims or colours the picture, <paramref name="background"/> fills behind it.</summary>
public void ImageButton(byte kind, uint iconId, string id, Action onClick, float w, float h, uint tint = 0xFFFFFFFFu, uint background = 0u)
{
if (!Room()) return;
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpImageButton);
U32(key);
Str(id);
U8(kind);
U32(iconId);
F32(w);
F32(h);
F32(0f); F32(0f); // uv0
F32(1f); F32(1f); // uv1
U32(background); // background fill behind the picture (0 = none)
U32(tint);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
}
/// <summary>Tooltip for the item just drawn.</summary>
public void Tooltip(string text)
{
if (!Room() || string.IsNullOrEmpty(text)) return;
int p = BeginOp(UiFormat.OpSetItemTooltip);
Str(text);
EndOp(p);
}
public void PushStyleColor(int colId, uint abgr)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpPushStyleColor);
U16((ushort)colId);
U32(abgr);
EndOp(p);
}
/// <summary>Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end.</summary>
public void PopStyleColor(int count = 1)
{
if (!Room()) return;
int p = BeginOp(UiFormat.OpPopStyleColor);
U8((byte)Math.Clamp(count, 1, 255));
EndOp(p);
}
/// <summary>
/// A collapsing header; returns whether to record its contents. The open state is the
/// player's (kept from the engine's Open events), so a header stays as they left it.
/// </summary>
public bool CollapsingHeader(string label, string id, bool defaultOpen = false)
{
uint key = KeyOf(id);
bool open = _openStates.TryGetValue(key, out bool o) ? o : defaultOpen;
if (!Room()) return false;
int p = BeginOp(UiFormat.OpCollapsingHeader);
U32(key);
Str(label + "###" + id);
U32(defaultOpen ? UiFormat.TreeDefaultOpen : 0);
U8(open ? (byte)1 : (byte)0);
EndOp(p);
_next[key] = e => { if (e.Type == UiFormat.EvOpen) _openStates[key] = e.Bool; };
return open;
}
/// <summary>A scrolling region; h 0 = fill the rest of the window. Must be closed with <see cref="EndChild"/>.</summary>
public void BeginChild(string id, float w = 0f, float h = 0f, bool border = true)
{
if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("child regions nested too deep");
if (!Room())
{
_blocks[_blockDepth++] = -1;
return;
}
uint key = KeyOf(id);
int p = BeginOp(UiFormat.OpChild, UiFormat.OpHasBlock);
U32(key);
Str(id);
F32(w);
F32(h);
U8(border ? (byte)1 : (byte)0);
U32(0);
EndOp(p);
_blocks[_blockDepth++] = _len;
U32(0); // BlockLength, patched by EndChild
}
public void EndChild()
{
if (_blockDepth == 0) return;
int at = _blocks[--_blockDepth];
if (at < 0) return;
BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4)));
}
// ── Writing ─────────────────────────────────────────────────────────────
/// <summary>
/// Whether another op fits. Room is kept for the closing "list cut short" line and the End
/// op, so the list never goes over the engine's limits (it refuses an over-limit list whole).
/// </summary>
private bool Room()
{
if (_cut) return false;
if (_ops < UiFormat.MaxOps - 8 && _len < UiFormat.MaxBodyBytes - 4096) return true;
_cut = true;
return false;
}
private void WriteText(byte code, string text)
{
if (!Room()) return;
int p = BeginOp(code);
Str(text);
EndOp(p);
}
private int BeginOp(byte code, byte opFlags = 0)
{
_ops++;
Ensure(4);
_body[_len++] = code;
_body[_len++] = opFlags;
_len += 2; // PayloadLength, patched by EndOp
return _len;
}
private void EndOp(int payloadStart)
{
int length = _len - payloadStart;
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(payloadStart - 2), (ushort)Math.Min(length, ushort.MaxValue));
}
private void Ensure(int extra)
{
if (_len + extra <= _body.Length) return;
int size = _body.Length;
while (size < _len + extra) size *= 2;
Array.Resize(ref _body, size);
}
private void U8(byte v) { Ensure(1); _body[_len++] = v; }
private void U16(ushort v) { Ensure(2); BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), v); _len += 2; }
private void U32(uint v) { Ensure(4); BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
private void I32(int v) { Ensure(4); BinaryPrimitives.WriteInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
private void F32(float v)
{
Ensure(4);
BinaryPrimitives.WriteSingleLittleEndian(_body.AsSpan(_len), float.IsFinite(v) ? v : 0f);
_len += 4;
}
/// <summary>str: u16 length + UTF-8, cut to <paramref name="maxBytes"/> on a character boundary.</summary>
private void Str(string s, int maxBytes = UiFormat.MaxString)
{
s ??= string.Empty;
ReadOnlySpan<char> src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan();
Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length));
int at = _len + 2;
Span<byte> dst = _body.AsSpan(at);
int n = UiFormat.CutUtf8(dst[..Encoding.UTF8.GetBytes(src, dst)], maxBytes);
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), (ushort)n);
_len = at + n;
}
}

View file

@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Use;
/// <summary>
/// The controller's view of the game through the engine host. Plugin pump thread only (the
/// plugin's tick), which is also where RynthAi's interfaces may be called.
/// </summary>
internal sealed unsafe class HostDefWorld : IDefWorld
{
private const long SnapshotMaxAgeMs = 250;
private readonly RynthCoreHost _host;
private readonly HostInventory _reader = new();
private List<CarriedItem> _items = new();
private long _itemsAtMs = long.MinValue / 4;
private int _revision;
public HostDefWorld(RynthCoreHost host) => _host = host;
public long NowMs => Environment.TickCount64;
public bool InWorld => _host.HasGetPlayerId && _host.GetPlayerId() != 0 && !(_host.HasIsPortaling && _host.IsPortaling());
public uint PlayerId => _host.HasGetPlayerId ? _host.GetPlayerId() : 0;
public uint SelectedId => _host.HasGetSelectedItemId ? _host.GetSelectedItemId() : 0;
public bool ClientBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
public bool Animating => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
public int UseDoneSeq => _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
public int CombatMode => _host.GetCurrentCombatMode();
public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null;
public bool? BotMacroRunning => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.MacroRunning) != 0 : null;
public int RefusalSeq => _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
public bool RefusalNamed(uint objectId) =>
_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out _, out _, out _, out uint obj) && obj == objectId;
/// <summary>The inventory, re-read when it is older than a quarter second.</summary>
public IReadOnlyList<CarriedItem> Items() => Snapshot(SnapshotMaxAgeMs);
/// <summary>The inventory, re-read when it is older than <paramref name="maxAgeMs"/>.</summary>
public List<CarriedItem> Snapshot(long maxAgeMs)
{
long now = NowMs;
if (now - _itemsAtMs >= maxAgeMs)
{
_items = _reader.Read(_host, now);
_itemsAtMs = now;
_revision++;
}
return _items;
}
/// <summary>Counts re-reads (the plugin redraws and re-binds slots when it moved).</summary>
public int Revision => _revision;
public CarriedItem? Live(uint id) => _reader.ReadOne(_host, id, NowMs);
public bool UseObject(uint id) => _host.HasUseObject && _host.UseObject(id);
public bool UseObjectOn(uint id, uint target) => _host.HasUseObjectOn && _host.UseObjectOn(id, target);
public bool SetCombatMode(int mode) => _host.HasChangeCombatMode && _host.ChangeCombatMode(mode);
public void Reset()
{
_reader.Reset();
_items = new List<CarriedItem>();
_itemsAtMs = long.MinValue / 4;
}
}
/// <summary>
/// RynthAi's activity bits: its "RynthAi.Activity" interface; on an older RynthAi without it, the
/// macro bit from "RynthAi.Status"; null when RynthAi isn't loaded or not ready. Resolved again every
/// call: a RynthAi reload frees the tables. Read only: nothing here changes what RynthAi does.
/// </summary>
internal static unsafe class BotActivity
{
public static RynthAiActivity? Read(RynthCoreHost host)
{
if (!host.HasGetPluginInterface) return null;
try
{
var act = (RynthAiActivityApiV1*)host.GetPluginInterface("RynthAi", RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion);
if (act != null && act->Version >= 1 && act->StructSize >= (uint)sizeof(RynthAiActivityApiV1) && act->GetActivityFlags != null)
{
uint flags = 0;
return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null;
}
var status = (RynthAiStatusApiV1*)host.GetPluginInterface("RynthAi", RynthAiStatusApiV1.InterfaceName, RynthAiStatusApiV1.InterfaceVersion);
if (status != null && status->Version >= 1 && status->StructSize >= (uint)sizeof(RynthAiStatusApiV1) && status->GetStatusJson != null)
{
byte* r = null;
if (status->GetStatusJson(&r) != 0 && r != null)
return FromStatusJson(Marshal.PtrToStringUTF8((IntPtr)r));
}
}
catch
{
// A RynthAi mid-reload: treat as not there this tick.
}
return null;
}
/// <summary>The macro bit an older RynthAi's status JSON ({macro, action, ...}) gives (no server-wait bit).</summary>
internal static RynthAiActivity? FromStatusJson(string? json)
{
if (string.IsNullOrEmpty(json) || json[0] != '{') return null;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
bool macro = doc.RootElement.TryGetProperty("macro", out JsonElement m) && m.ValueKind == JsonValueKind.True;
return macro ? RynthAiActivity.MacroRunning : RynthAiActivity.None;
}
catch (JsonException)
{
return null;
}
}
}

View file

@ -0,0 +1,382 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
namespace RynthCore.Plugin.RynthDefective.Use;
/// <summary>
/// What the controller needs from the game. The host implements it (HostDefWorld); the tests
/// script it. Plugin pump thread only.
/// </summary>
internal interface IDefWorld
{
long NowMs { get; }
/// <summary>A character is in the world and not in portal space.</summary>
bool InWorld { get; }
uint PlayerId { get; }
uint SelectedId { get; }
/// <summary>The client's busy count is above zero (an item action it sent has not been answered).</summary>
bool ClientBusy { get; }
/// <summary>A cast or use gesture is animating.</summary>
bool Animating { get; }
/// <summary>RynthAi is waiting on the server for an action it sent (null = RynthAi isn't there).</summary>
bool? BotWaitingOnServer { get; }
/// <summary>RynthAi's macro is running (null = RynthAi isn't there).</summary>
bool? BotMacroRunning { get; }
/// <summary>Count of the server's UseDone events; 0 when the engine can't report them.</summary>
int UseDoneSeq { get; }
/// <summary>1 NonCombat, 2 Melee, 4 Missile, 8 Magic.</summary>
int CombatMode { get; }
/// <summary>The server's refusals so far (0x028A / 0x00A0 ... count), to tell a new one.</summary>
int RefusalSeq { get; }
/// <summary>The newest refusal named this object (a refused wield: InventoryServerSaveFailed).</summary>
bool RefusalNamed(uint objectId);
/// <summary>Everything carried and worn, as the client has it now.</summary>
IReadOnlyList<CarriedItem> Items();
/// <summary>The item as the client has it this instant (wielded or not); null if it is gone.</summary>
CarriedItem? Live(uint id);
bool UseObject(uint id);
bool UseObjectOn(uint id, uint target);
bool SetCombatMode(int mode);
}
/// <summary>One thing the player asked to use: an exact item (a slot's) or a name typed in a command.</summary>
internal sealed record UseRequest(ItemRef? Item, string? Name, UseMode Mode, string Source, long AtMs)
{
/// <summary>Same item, same way: pressing the key again must not queue a second one.</summary>
public bool SameAs(UseRequest o) =>
Mode == o.Mode
&& ((Item != null && o.Item != null && Item.SameAs(o.Item))
|| (Name != null && o.Name != null && string.Equals(Name, o.Name, StringComparison.OrdinalIgnoreCase)));
public string Label => Item?.FullName ?? Name ?? "item";
}
/// <summary>The combat stance a weapon swap leaves the character in.</summary>
internal static class Stance
{
public const int NonCombat = 1, Melee = 2, Missile = 4, Magic = 8;
/// <summary>
/// The stance to ask for after <paramref name="weapon"/> was wielded, 0 = leave it alone.
/// A character at peace stays at peace. One in a fighting stance goes to the new weapon's:
/// Melee, Missile (a launcher needs its ammunition in hand: without it the client refuses the
/// stance, so the character goes to peace rather than being left in a stance the weapon can't
/// use), or Magic for a caster. Shields, armor and ammunition keep the stance they are in.
/// </summary>
public static int Wanted(ItemKind kind, bool launcherNeedsAmmo, bool ammoInHand, int modeBefore)
{
if (modeBefore == NonCombat || modeBefore == 0) return 0;
switch (kind)
{
case ItemKind.Melee: return Melee;
case ItemKind.WarWand:
case ItemKind.VoidWand: return Magic;
case ItemKind.Missile: return launcherNeedsAmmo && !ammoInHand ? NonCombat : Missile;
default: return 0;
}
}
public static string Name(int mode) => mode switch
{
NonCombat => "peace",
Melee => "melee",
Missile => "missile",
Magic => "magic",
_ => "mode " + mode,
};
}
/// <summary>
/// One use at a time. A request (a slot pressed, /rdef use, the picker) is held until the
/// character is free, then sent; the next waits for the server's answer. A second request while one
/// is waiting replaces it (the newest wish wins) unless it is the same one (a key held down does
/// not queue twice). Nothing is retried in a loop: a refused or unanswered action is reported once.
///
/// What is sent (the host calls RynthAi's own one-touch heal and weapon swap use):
/// kits UseObjectOn(kit, you) answered by the server's UseDone
/// consumables UseObject(item) answered by UseDone
/// weapons etc. UseObject(item): the client's double-click, which takes what is in the way off;
/// answered when the item reads wielded (a wield sends no UseDone), then the stance
/// is put right (<see cref="Stance.Wanted"/>) once the character is still.
/// Busy: nothing is sent while the client's busy count is up, a gesture animates, RynthAi waits on
/// the server, the last action is unanswered, or for <see cref="MinGapMs"/> after it - the "one item
/// action at a time" rule RynthAi's ActionPacer keeps. Weapon swaps also wait out a running RynthAi
/// macro unless the player allowed them (it would swap straight back).
/// </summary>
internal sealed class UseController
{
/// <summary>How long a request waits for the character to be free before it gives up and says why.</summary>
public const long WaitLimitMs = 6000;
/// <summary>A use with no UseDone by now is let go (RynthAi waits 8 s for a kit's result).</summary>
public const long UseTimeoutMs = 8000;
/// <summary>A use the client no longer holds busy, with no UseDone, is let go after this.</summary>
public const long UseQuietMs = 1500;
public const long WieldTimeoutMs = 3500;
public const long MinGapMs = 250;
public const long StanceSettleMs = 500;
public const long StanceTimeoutMs = 4000;
private enum Stage { Sent, WaitWield, Stance }
private sealed class Flight
{
public UseRequest Request = null!;
public CarriedItem Item = null!;
public UseAction Action;
public ItemKind Kind;
public long SentMs;
public int UseDoneAtSend, RefusalAtSend, ModeBefore;
public Stage Stage;
public long StageMs;
}
private UseRequest? _pending;
private Flight? _flight;
private long _lastDoneMs = long.MinValue / 4;
private string _lastWait = string.Empty;
/// <summary>Plain information ("Using Peerless Healing Kit ..."): the status line, not the chat.</summary>
public Action<string>? Say;
/// <summary>Something went wrong or didn't happen: the status line and the chat.</summary>
public Action<string>? Warn;
public Action<string>? Log;
/// <summary>A weapon was wielded (the picker's recent list).</summary>
public Action<CarriedItem>? Wielded;
public bool HasPending => _pending != null;
public bool InFlight => _flight != null;
public UseRequest? Pending => _pending;
/// <summary>The item a request in flight or waiting is about, for highlighting its slot.</summary>
public bool Involves(ItemRef r) =>
(_pending?.Item != null && _pending.Item.SameAs(r)) || (_flight?.Request.Item != null && _flight.Request.Item.SameAs(r));
public DefSettings Settings = new();
/// <summary>Queues a request. False when it is the one already waiting or in flight (a held key).</summary>
public bool Request(UseRequest r)
{
if (_pending != null && _pending.SameAs(r)) return false;
if (_flight != null && _flight.Action == UseAction.Equip && _flight.Request.SameAs(r)) return false; // already wielding it
_pending = r;
_lastWait = string.Empty;
return true;
}
/// <summary>Drops what is waiting and forgets what is in flight (logout, portal space, shutdown).</summary>
public void Reset()
{
_pending = null;
_flight = null;
_lastWait = string.Empty;
}
public void Tick(IDefWorld w)
{
if (!w.InWorld)
{
if (_pending != null || _flight != null) Reset();
return;
}
long now = w.NowMs;
if (_flight != null && !AdvanceFlight(w, now)) return; // still in flight: nothing new goes out
if (_pending == null) return;
UseRequest req = _pending;
string? wait = WaitReason(w, now);
if (wait != null)
{
_lastWait = wait;
if (now - req.AtMs >= WaitLimitMs)
{
_pending = null;
Warn?.Invoke($"{req.Label}: not used, {wait}.");
}
return;
}
_pending = null;
Send(w, req, now);
}
private string? WaitReason(IDefWorld w, long now)
{
if (now - _lastDoneMs < MinGapMs) return "the last action just finished";
if (w.ClientBusy) return "the character is busy";
if (w.Animating) return "an animation is playing";
if (w.BotWaitingOnServer == true) return "RynthAi is waiting on the server";
return null;
}
// ── Sending ─────────────────────────────────────────────────────────────
private void Send(IDefWorld w, UseRequest req, long now)
{
IReadOnlyList<CarriedItem> items = w.Items();
CarriedItem? item = req.Item != null
? ItemMatcher.Find(req.Item, items, out _)
: ItemMatcher.FindByName(req.Name ?? string.Empty, items);
if (item == null)
{
Warn?.Invoke(req.Item != null
? $"{req.Label}: you aren't carrying one."
: $"No item named '{req.Name}' in your pack.");
return;
}
ItemKind kind = ItemKinds.Classify(item);
UseAction action = UseModes.ActionFor(req.Mode, kind);
string name = item.FullName;
if (action == UseAction.Equip)
{
if (item.Wielded)
{
Say?.Invoke($"{name} is already in your hands.");
return;
}
if (ItemKinds.IsWeapon(kind) && !Settings.SwapWhileBotRuns && w.BotMacroRunning == true)
{
Warn?.Invoke($"{name}: not wielded, RynthAi's macro is running and picks the weapon itself (stop it, or allow swaps in the Defective settings).");
return;
}
}
uint target = 0;
if (action == UseAction.UseOnSelf) target = w.PlayerId;
else if (action == UseAction.UseOnSelected)
{
target = w.SelectedId;
if (target == 0)
{
Warn?.Invoke($"{name}: select a target first.");
return;
}
}
if ((action == UseAction.UseOnSelf || action == UseAction.UseOnSelected) && target == 0)
{
Warn?.Invoke($"{name}: the character isn't ready.");
return;
}
bool sent = target != 0 ? w.UseObjectOn(item.Id, target) : w.UseObject(item.Id);
if (!sent)
{
Warn?.Invoke($"{name}: the client didn't take the request (nothing was sent).");
return;
}
_flight = new Flight
{
Request = req,
Item = item,
Action = action,
Kind = kind,
SentMs = now,
StageMs = now,
UseDoneAtSend = w.UseDoneSeq,
RefusalAtSend = w.RefusalSeq,
ModeBefore = w.CombatMode,
Stage = action == UseAction.Equip ? Stage.WaitWield : Stage.Sent,
};
Log?.Invoke($"[RynthDefective] {req.Source}: {(action == UseAction.Equip ? "wield" : target != 0 ? "use on " + (target == w.PlayerId ? "you" : "0x" + target.ToString("X8")) : "use")} {item} (stack {item.Stack}, mode {Stance.Name(w.CombatMode)})");
Say?.Invoke(action == UseAction.Equip ? $"Wielding {name}..." : $"Using {name}...");
}
// ── In flight ───────────────────────────────────────────────────────────
/// <summary>Steps the action in flight; true when it is finished (a new one may go out this tick).</summary>
private bool AdvanceFlight(IDefWorld w, long now)
{
Flight f = _flight!;
long age = now - f.SentMs;
switch (f.Stage)
{
case Stage.Sent:
{
bool answered = w.UseDoneSeq != f.UseDoneAtSend;
bool quiet = age >= UseQuietMs && !w.ClientBusy && !w.Animating;
if (answered || quiet || age >= UseTimeoutMs)
{
if (!answered && age >= UseTimeoutMs) Log?.Invoke($"[RynthDefective] no UseDone for {f.Item} after {age} ms; carrying on");
Finish(now);
return true;
}
return false;
}
case Stage.WaitWield:
{
CarriedItem? live = w.Live(f.Item.Id);
if (live != null && live.Wielded)
{
Wielded?.Invoke(live);
f.Item = live;
f.Stage = Stage.Stance;
f.StageMs = now;
return AdvanceStance(w, f, now);
}
if (w.RefusalSeq != f.RefusalAtSend && w.RefusalNamed(f.Item.Id))
{
Warn?.Invoke($"{f.Item.FullName}: the server wouldn't let you wield it (a skill, level or slot requirement?).");
Finish(now);
return true;
}
if (age >= WieldTimeoutMs)
{
Warn?.Invoke($"{f.Item.FullName}: not in your hands after {age / 1000.0:0.0} s - something may be in the way, or the character was busy. Try again.");
Finish(now);
return true;
}
return false;
}
default:
return AdvanceStance(w, f, now);
}
}
private bool AdvanceStance(IDefWorld w, Flight f, long now)
{
bool launcher = f.Kind == ItemKind.Missile && ItemKinds.NeedsAmmo(f.Item);
int want = Stance.Wanted(f.Kind, launcher, AmmoInHand(w), f.ModeBefore);
if (want == 0 || w.CombatMode == want)
{
Say?.Invoke($"{f.Item.FullName} is in your hands.");
Finish(now);
return true;
}
long since = now - f.StageMs;
if (since >= StanceTimeoutMs)
{
Warn?.Invoke($"{f.Item.FullName} is wielded but the {Stance.Name(want)} stance wasn't taken ({Stance.Name(w.CombatMode)} now).");
Finish(now);
return true;
}
if (since < StanceSettleMs || w.ClientBusy || w.Animating) return false;
if (w.SetCombatMode(want))
{
Log?.Invoke($"[RynthDefective] stance {Stance.Name(w.CombatMode)} -> {Stance.Name(want)} for {f.Item}");
Say?.Invoke(want == Stance.NonCombat && f.ModeBefore != Stance.NonCombat
? $"{f.Item.FullName} is in your hands; no ammunition in hand, so you are back at peace."
: $"{f.Item.FullName} is in your hands, {Stance.Name(want)} stance.");
Finish(now);
return true;
}
return false; // the engine turned the request away this tick (a teleport, a pending action): ask again
}
private static bool AmmoInHand(IDefWorld w)
{
foreach (CarriedItem it in w.Items())
if (it.Wielded && ItemKinds.Classify(it) == ItemKind.Ammo) return true;
return false;
}
private void Finish(long now)
{
_flight = null;
_lastDoneMs = now;
}
}

View file

@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>
/// The item bar window: a grid of slot buttons (the item's picture, its count or uses left, its key
/// under it), a row with Edit, Settings and Weapons, and the status line. Edit opens the slot editor
/// below (set a slot from the item selected in the game, pick one from the pack, how it is used,
/// its key); Settings the sizes and switches. Recorded on the pump thread, replayed by the engine.
/// </summary>
internal sealed class BarView
{
/// <summary>Logical units a button needs besides its picture: the frame padding and the gap to the next.</summary>
public const float CellExtra = 16f;
private readonly DefSession _s;
private readonly SlotEditor _editor;
private readonly SettingsPanel _settings;
public bool EditOpen, SettingsOpen;
/// <summary>The window should be sized to its content (a setting changed, a section opened).</summary>
public Action RequestFit = () => { };
/// <summary>Show the weapon picker window.</summary>
public Action ShowPicker = () => { };
public BarView(DefSession session)
{
_s = session;
_editor = new SlotEditor(session);
_settings = new SettingsPanel(session, () => RequestFit());
}
public SlotEditor Editor => _editor;
/// <summary>The window size that fits the grid (and the sections that are open), in logical units.</summary>
public (float W, float H) WantedSize()
{
DefSettings st = _s.Settings;
int perRow = Math.Min(st.SlotsPerRow, st.SlotCount);
int rows = (st.SlotCount + st.SlotsPerRow - 1) / st.SlotsPerRow;
float cell = st.ButtonSize + CellExtra;
float w = Math.Max(250f, perRow * cell + 28f);
float h = rows * (st.ButtonSize + (st.ShowCounts ? 50f : 14f)) + 70f;
if (EditOpen) { h += 330f; w = Math.Max(w, 330f); }
if (SettingsOpen) h += 230f;
return (w, h);
}
public void Draw(UiWindow w)
{
if (!_s.LoggedIn)
{
w.TextDisabled("Log in to use the item bar.");
return;
}
IReadOnlyList<CarriedItem> items = _s.Items();
DrawGrid(w, items);
DrawToolbar(w);
DrawStatus(w);
if (EditOpen)
{
w.Separator();
_editor.Draw(w, items);
}
if (SettingsOpen)
{
w.Separator();
_settings.Draw(w);
}
}
// ── The grid ────────────────────────────────────────────────────────────
private void DrawGrid(UiWindow w, IReadOnlyList<CarriedItem> items)
{
DefSettings st = _s.Settings;
float size = st.ButtonSize;
float pitch = size + CellExtra;
var labels = new List<(string Text, uint Color)>();
var keys = new List<string>();
for (int rowStart = 0; rowStart < st.SlotCount; rowStart += st.SlotsPerRow)
{
int end = Math.Min(st.SlotCount, rowStart + st.SlotsPerRow);
labels.Clear();
keys.Clear();
for (int i = rowStart; i < end; i++)
{
if (i > rowStart) w.SameLine();
DrawSlotButton(w, i + 1, items, size, out string text, out uint color, out string key);
labels.Add((text, color));
keys.Add(key);
}
if (!st.ShowCounts) continue;
for (int j = 0; j < labels.Count; j++)
{
if (j > 0) w.SameLine(j * pitch);
w.TextColored(labels[j].Color, labels[j].Text.Length > 0 ? labels[j].Text : " ");
}
for (int j = 0; j < keys.Count; j++)
{
if (j > 0) w.SameLine(j * pitch);
w.TextColored(SlotText.KeyColor, keys[j].Length > 0 ? keys[j] : " ");
}
}
}
private void DrawSlotButton(UiWindow w, int number, IReadOnlyList<CarriedItem> items, float size,
out string text, out uint color, out string key)
{
DefSlot slot = _s.Data.Slots[number - 1];
string id = "slot" + number;
string? keyFull = _s.KeyOfSlot(number);
key = SlotText.ShortKey(keyFull);
text = string.Empty;
color = SlotText.Plain;
bool icons = _s.Settings.ShowIcons && _s.IconsAvailable;
if (slot.Item == null)
{
w.Button("+", id, () => Choose(number), size + 8f, size + 8f);
w.Tooltip(SlotText.Tooltip(number, null, default, slot.Mode, keyFull));
return;
}
SlotStatus s = ItemMatcher.Status(slot.Item, items);
text = SlotText.Count(s, out color);
string tip = SlotText.Tooltip(number, slot.Item, s, slot.Mode, keyFull);
bool busy = _s.Use.Involves(slot.Item);
bool inHand = s.Item is { Wielded: true };
uint? fill = busy ? SlotText.Waiting : inHand ? UiFormat.Rgb(40, 110, 40) : null;
if (icons && s.Item != null)
{
w.ImageButton(UiFormat.IconKindObject, s.Item.Id, id, () => Press(number), size, size, 0xFFFFFFFFu, fill ?? 0u);
}
else if (icons && slot.Item.Icon != 0)
{
// Not carried: the last picture seen, dimmed.
w.ImageButton(UiFormat.IconKindIcon, slot.Item.Icon, id, () => Press(number), size, size, UiFormat.Rgb(255, 255, 255, 90));
}
else
{
if (fill != null) w.PushStyleColor(UiFormat.ColButton, fill.Value);
else if (s.Item == null) w.PushStyleColor(UiFormat.ColText, SlotText.Missing);
w.Button(SlotText.Abbreviation(slot.Item.FullName), id, () => Press(number), size + 8f, size + 8f);
if (fill != null) w.PopStyleColor();
else if (s.Item == null) w.PopStyleColor();
}
w.Tooltip(tip);
}
private void Press(int number)
{
string? problem = _s.UseSlot(number);
if (problem != null) _s.SetStatus(problem, warning: true);
}
/// <summary>An empty slot's button: open the editor on it.</summary>
private void Choose(int number)
{
if (!EditOpen) { EditOpen = true; RequestFit(); }
_editor.Select(number);
}
// ── Toolbar and status ──────────────────────────────────────────────────
private void DrawToolbar(UiWindow w)
{
w.ToggleButton("Edit slots", "tb.edit", EditOpen, () => { EditOpen = !EditOpen; RequestFit(); }, small: true);
w.SameLine();
w.ToggleButton("Settings", "tb.settings", SettingsOpen, () => { SettingsOpen = !SettingsOpen; RequestFit(); }, small: true);
w.SameLine();
w.SmallButton("Weapons", "tb.weapons", () => ShowPicker());
w.Tooltip("The weapon picker: every weapon and wand you carry, one click to wield (/rdef weapons)");
}
private void DrawStatus(UiWindow w)
{
UseRequest? pending = _s.Use.Pending;
if (pending != null)
{
w.TextColored(SlotText.Waiting, $"Waiting to use {pending.Label}...");
return;
}
string status = _s.Status(out bool warning);
if (status.Length > 0) w.TextColored(warning ? SlotText.Missing : SlotText.Plain, status);
else w.TextDisabled("Click a slot, or press its key.");
}
}

View file

@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>
/// The weapon picker window, for picking among dozens of weapons while playing by hand: a search
/// box, a row of kind buttons (All, Melee, Missile, War, Void - the kind the player prefers is kept),
/// then the carried weapons and wands as big rows with their picture. Favourites and the recently
/// wielded come first; below them every kind, A-Z. One click on a row wields it; the weapon in hand
/// is highlighted. The "+" / "-" in front of a row adds or takes out a favourite.
/// </summary>
internal sealed class PickerView
{
private static readonly uint InHandColor = UiFormat.Rgb(110, 210, 110);
private static readonly uint ElementColor = UiFormat.Rgb(150, 185, 235);
private readonly DefSession _s;
public string Search = string.Empty;
public PickerView(DefSession session) => _s = session;
public void Draw(UiWindow w)
{
if (!_s.LoggedIn)
{
w.TextDisabled("Log in to pick a weapon.");
return;
}
DefSettings st = _s.Settings;
IReadOnlyList<CarriedItem> items = _s.Items();
PickerModel m = WeaponPicker.Build(items, _s.Data.Favourites, _s.Data.Recent, Search, st.PreferredKind);
w.InputText("Search", "pk.search", Search, 48, v => Search = v);
w.Tooltip("Words in the name, the element or the kind: \"fire wand\", \"axe\", \"void\".");
foreach (KindFilter f in Enum.GetValues<KindFilter>())
{
KindFilter kind = f;
w.ToggleButton(WeaponPicker.KindLabel(f), "pk.kind" + (int)f, st.PreferredKind == f, () =>
{
st.PreferredKind = kind;
_s.Save();
}, small: true);
w.SameLine();
}
w.SmallButton("Clear", "pk.clear", () => Search = string.Empty);
w.Tooltip("Clears the search. The kind button you leave pressed is remembered.");
DrawHand(w, items);
if (st.PreferredKind != KindFilter.All || Search.Length > 0)
w.TextDisabled($"{m.Shown} of {m.Total} shown");
w.BeginChild("pk.list", 0f, 0f, true);
float icon = st.PickerIconSize;
bool icons = st.ShowIcons && _s.IconsAvailable;
if (m.Favourites.Count > 0)
{
w.SeparatorText("Favourites");
foreach (PickerRow r in m.Favourites) DrawRow(w, r, "f", icon, icons, showElement: true);
}
if (m.Recent.Count > 0)
{
w.SeparatorText("Recent");
foreach (PickerRow r in m.Recent) DrawRow(w, r, "r", icon, icons, showElement: true);
}
foreach (PickerGroup g in m.Groups)
{
w.SeparatorText($"{ItemKinds.Label(g.Group)} ({g.Rows.Count})");
foreach (PickerRow r in g.Rows) DrawRow(w, r, "g", icon, icons, showElement: g.Group is WeaponGroup.WarMagic or WeaponGroup.VoidMagic);
}
if (m.Groups.Count == 0)
w.TextDisabled(m.Total == 0 ? "No weapons or wands in your pack." : "Nothing matches. Clear the search or pick All.");
w.EndChild();
}
/// <summary>What is in the hands now, and the item's name for the title line.</summary>
private void DrawHand(UiWindow w, IReadOnlyList<CarriedItem> items)
{
string hand = string.Empty;
foreach (CarriedItem it in items)
{
if (!it.Wielded) continue;
ItemKind k = ItemKinds.Classify(it);
if (!ItemKinds.IsWeapon(k) && k != ItemKind.Shield) continue;
hand += (hand.Length > 0 ? ", " : string.Empty) + it.FullName;
}
UseRequest? pending = _s.Use.Pending;
if (pending != null) w.TextColored(SlotText.Waiting, $"Waiting to wield {pending.Label}...");
else w.TextColored(hand.Length > 0 ? InHandColor : SlotText.Plain, "In hand: " + (hand.Length > 0 ? hand : "nothing"));
}
private void DrawRow(UiWindow w, PickerRow r, string section, float icon, bool icons, bool showElement)
{
CarriedItem it = r.Item;
string idKey = section + it.Id;
ItemRef reference = ItemRef.From(it);
w.SmallButton(r.Favourite ? "-" : "+", "fav" + idKey, () => _s.SetStatus(_s.ToggleFavourite(reference)));
w.Tooltip(r.Favourite ? "Take out of the favourites" : "Add to the favourites (listed first)");
w.SameLine();
if (icons)
{
w.Image(UiFormat.IconKindObject, it.Id, icon, icon);
w.SameLine();
}
string label = it.FullName;
if (showElement && r.Element.Length > 0) label += $" ({r.Element})";
if (r.InHand) label += " [in hand]";
if (r.InHand) w.PushStyleColor(UiFormat.ColText, InHandColor);
w.Selectable(label, "pk" + idKey, r.InHand, () => _s.Wield(reference), 0f, icons ? icon : 0f);
if (r.InHand) w.PopStyleColor();
}
}

View file

@ -0,0 +1,49 @@
using System;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>The settings under the bar: how many slots and how big, what is shown, and the credit.</summary>
internal sealed class SettingsPanel
{
/// <summary>The credit line, in the plugin's about text and the README.</summary>
public const string Credit =
"RynthDefective is an independent implementation of the ideas of Defective, the Decal item-bar plugin written by "
+ "Hazridi and modified by Aun (github.com/aunrela/Defective). It contains no code from it.";
private readonly DefSession _s;
private readonly Action _fit;
public SettingsPanel(DefSession session, Action fit)
{
_s = session;
_fit = fit;
}
public void Draw(UiWindow w)
{
DefSettings st = _s.Settings;
void Changed(bool fit)
{
st.Clamp();
_s.Save();
if (fit) _fit();
}
w.SeparatorText("Settings");
w.SliderInt("Slots", "set.slots", st.SlotCount, DefSettings.SlotsMin, DefSettings.SlotsMax, v => { st.SlotCount = v; Changed(true); });
w.SliderInt("Slots per row", "set.perrow", st.SlotsPerRow, DefSettings.PerRowMin, DefSettings.PerRowMax, v => { st.SlotsPerRow = v; Changed(true); });
w.SliderInt("Button size", "set.button", st.ButtonSize, DefSettings.ButtonMin, DefSettings.ButtonMax, v => { st.ButtonSize = v; Changed(true); });
w.SliderInt("Picker row icon", "set.picker", st.PickerIconSize, DefSettings.PickerIconMin, DefSettings.PickerIconMax, v => { st.PickerIconSize = v; Changed(false); });
w.Checkbox("Show item icons", "set.icons", st.ShowIcons, v => { st.ShowIcons = v; Changed(false); });
w.Tooltip(_s.IconsAvailable ? "Off: the slots are text buttons." : "This engine can't draw item pictures (it needs script window op level 2): the slots are text buttons.");
w.Checkbox("Show counts and keys under the slots", "set.counts", st.ShowCounts, v => { st.ShowCounts = v; Changed(true); });
w.Checkbox("Allow weapon swaps while RynthAi's macro runs", "set.swap", st.SwapWhileBotRuns, v => { st.SwapWhileBotRuns = v; Changed(false); });
w.Tooltip("Off (the default): a weapon, wand or shield is not wielded while the RynthAi macro runs - it picks the weapon itself and would swap back. Kits, potions and other items always work.");
w.SeparatorText("About");
w.TextWrapped(Credit);
w.TextDisabled("Commands: /rdef (show or hide), /rdef use <slot or name>, /rdef weapons, /rdef help.");
}
}

View file

@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>
/// The slot editor under the bar: every slot as a row (picture, name, key), and for the one picked
/// its buttons - Set from selected (the item selected in the game goes in the slot), Pick from pack
/// (a searchable list of what is carried), Clear, move up and down - how pressing it uses the item,
/// and its key (typed here, bound through the engine's hotkeys as "/rdef use N" or by the item's name).
/// </summary>
internal sealed class SlotEditor
{
private const float RowIcon = 22f;
private const int PackRows = 40;
private readonly DefSession _s;
private int _selected = 1;
private bool _picking;
private string _packSearch = string.Empty;
private string _keyDraft = string.Empty;
private string _note = string.Empty;
public SlotEditor(DefSession session) => _s = session;
public int SelectedSlot => _selected;
public bool Picking => _picking;
public string Note => _note;
public void Select(int number)
{
_selected = Math.Clamp(number, 1, DefSettings.SlotsMax);
_picking = false;
_keyDraft = string.Empty;
_note = string.Empty;
}
private void Say(string text)
{
_note = text;
_s.SetStatus(text);
}
public void Draw(UiWindow w, IReadOnlyList<CarriedItem> items)
{
DefSettings st = _s.Settings;
if (_selected > st.SlotCount) _selected = st.SlotCount;
bool icons = st.ShowIcons && _s.IconsAvailable;
w.TextDisabled("Pick a slot, then set it from the item selected in the game or from your pack.");
w.BeginChild("slotlist", 0f, Math.Min(st.SlotCount, 6) * (RowIcon + 6f) + 8f, true);
for (int n = 1; n <= st.SlotCount; n++)
{
DefSlot slot = _s.Data.Slots[n - 1];
int number = n;
string? key = _s.KeyOfSlot(n);
string name = slot.Item == null ? "(empty)" : slot.Item.FullName;
if (icons)
{
CarriedItem? have = slot.Item == null ? null : ItemMatcher.Find(slot.Item, items, out _);
if (have != null) w.Image(UiFormat.IconKindObject, have.Id, RowIcon, RowIcon);
else if (slot.Item != null && slot.Item.Icon != 0) w.Image(UiFormat.IconKindIcon, slot.Item.Icon, RowIcon, RowIcon, UiFormat.Rgb(255, 255, 255, 90));
else w.Dummy(RowIcon, RowIcon);
w.SameLine();
}
string label = $"{n}. {name}" + (key != null ? $" [{key}]" : string.Empty);
w.Selectable(label, "row" + n, _selected == n, () => Select(number), 0f, icons ? RowIcon : 0f);
}
w.EndChild();
DrawSlot(w, items);
}
private void DrawSlot(UiWindow w, IReadOnlyList<CarriedItem> items)
{
int n = _selected;
DefSlot slot = _s.Data.Slots[n - 1];
w.TextColored(UiColors.Gold, $"Slot {n}: " + (slot.Item == null ? "(empty)" : slot.Item.FullName));
w.Button("Set from selected", "ed.set", () => Say(_s.SetFromSelected(n)));
w.Tooltip("Select an item in the game (click it in your pack), then press this: it goes in this slot.");
w.SameLine();
w.ToggleButton("Pick from pack", "ed.pick", _picking, () => { _picking = !_picking; _packSearch = string.Empty; });
w.Tooltip("Choose from a list of what you carry.");
w.SameLine();
w.Button("Clear", "ed.clear", () => Say(_s.ClearSlot(n)));
w.SmallButton("Move up", "ed.up", () => { if (_s.SwapSlots(n, n - 1)) _selected = n - 1; });
w.SameLine();
w.SmallButton("Move down", "ed.down", () => { if (_s.SwapSlots(n, n + 1)) _selected = n + 1; });
uint sel = _s.SelectedId();
CarriedItem? selItem = sel == 0 ? null : _s.FindById(sel);
w.TextDisabled("Selected in the game: " + (sel == 0 ? "nothing" : selItem != null ? selItem.FullName : "(not in your pack)"));
if (_note.Length > 0) w.TextWrapped(_note);
if (_picking) DrawPackPicker(w, items, n);
if (slot.Item == null) return;
int mode = (int)slot.Mode;
w.Combo("Pressing it", "ed.mode", mode, UseModes.Labels, i => _s.SetSlotMode(n, (UseMode)Math.Clamp(i, 0, (int)UseMode.Equip)));
SlotStatus status = ItemMatcher.Status(slot.Item, items);
if (status.Item != null)
{
ItemKind kind = ItemKinds.Classify(status.Item);
UseAction action = UseModes.ActionFor(slot.Mode, kind);
w.TextDisabled($"It is {Describe(kind)}: pressing the slot has it {UseModes.Describe(action)}.");
}
else
{
w.TextColored(SlotText.Missing, "Not in your pack right now. The slot keeps the name and fills itself when you carry another.");
}
DrawKey(w, n, slot);
}
private void DrawKey(UiWindow w, int n, DefSlot slot)
{
string? key = _s.KeyOfSlot(n);
w.Text("Key: " + (key ?? "none"));
w.InputText("Key to bind", "ed.key", _keyDraft, 24, v => _keyDraft = v, UiFormat.InputEnterReturnsTrue);
w.Tooltip("A key with Ctrl, Alt or Shift if you like: F9, Ctrl+1, Alt+Shift+Num3.");
w.Button("Bind to this slot", "ed.bind", () => Say(_s.BindKey(n, _keyDraft, byName: false)));
w.Tooltip($"Runs {DefCommandParser.UseCommand(n)}. If you move or re-set the slot, the key follows the slot.");
w.SameLine();
w.Button("Bind to this item", "ed.bindname", () => Say(_s.BindKey(n, _keyDraft, byName: true)));
w.Tooltip("Runs /rdef use <the item's name>, whichever slot (or none) holds it. Works for every character on this PC.");
w.SameLine();
w.Button("Unbind", "ed.unbind", () => Say(_s.UnbindKey(n)));
w.TextDisabled("Any item can be bound by name from Settings > Hotkeys too: /rdef use <name>.");
}
private void DrawPackPicker(UiWindow w, IReadOnlyList<CarriedItem> items, int n)
{
bool icons = _s.Settings.ShowIcons && _s.IconsAvailable;
w.InputText("Search your pack", "ed.packsearch", _packSearch, 48, v => _packSearch = v);
List<PackChoice> choices = PackList.Build(items, _packSearch, PackRows, out int total);
w.BeginChild("packlist", 0f, 150f, true);
foreach (PackChoice c in choices)
{
CarriedItem it = c.Item;
if (icons) { w.Image(UiFormat.IconKindObject, it.Id, RowIcon, RowIcon); w.SameLine(); }
string label = it.FullName + (c.Count > 1 ? $" x{c.Count}" : string.Empty);
w.Selectable(label, "pk" + it.Id, false, () =>
{
Say(_s.SetSlot(n, it));
_picking = false;
}, 0f, icons ? RowIcon : 0f);
}
if (choices.Count == 0) w.TextDisabled("Nothing matches.");
if (total > choices.Count) w.TextDisabled($"{total - choices.Count} more - type to narrow the list.");
w.EndChild();
}
private static string Describe(ItemKind k) => k switch
{
ItemKind.Kit => "a healing or stamina kit",
ItemKind.Melee => "a melee weapon",
ItemKind.Missile => "a missile weapon",
ItemKind.WarWand => "a war magic wand",
ItemKind.VoidWand => "a void magic wand",
ItemKind.Shield => "a shield",
ItemKind.Armor => "armor or clothing",
ItemKind.Jewelry => "jewelry",
ItemKind.Ammo => "ammunition",
_ => "an item",
};
}

View file

@ -0,0 +1,80 @@
using System;
using System.Text;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
namespace RynthCore.Plugin.RynthDefective.Views;
/// <summary>The words a slot shows: the count under its button, its key, and its tooltip. Pure.</summary>
internal static class SlotText
{
public static readonly uint Missing = UiFormat.Rgb(225, 95, 95);
public static readonly uint InHand = UiFormat.Rgb(110, 210, 110);
public static readonly uint Plain = UiFormat.Rgb(220, 220, 220);
public static readonly uint KeyColor = UiFormat.Rgb(150, 185, 235);
public static readonly uint Waiting = UiFormat.Rgb(255, 191, 64);
/// <summary>The line under a slot button: uses left (kits), the count (stacks, several of a kind), "in hand", or "none".</summary>
public static string Count(SlotStatus s, out uint color)
{
color = Plain;
if (s.Item == null)
{
color = Missing;
return "none";
}
CarriedItem it = s.Item;
if (it.Wielded)
{
color = InHand;
return ItemKinds.IsWeapon(ItemKinds.Classify(it)) ? "in hand" : "worn";
}
if (it.MaxUses > 0) return s.Uses.ToString();
if (it.MaxStack > 1 || s.Count > 1) return "x" + s.Count;
return string.Empty;
}
/// <summary>A key as the cell under a slot has room for: "Ctrl+F9" is "C+F9".</summary>
public static string ShortKey(string? key)
{
if (string.IsNullOrEmpty(key)) return string.Empty;
string k = key.EndsWith(" (off)", StringComparison.Ordinal) ? key[..^6] : key;
return k.Replace("Ctrl+", "C+").Replace("Alt+", "A+").Replace("Shift+", "S+");
}
/// <summary>Up to <paramref name="max"/> letters for a slot drawn as text (icons off): "Peerless Healing Kit" is "PHK".</summary>
public static string Abbreviation(string name, int max = 4)
{
var sb = new StringBuilder();
foreach (string word in (name ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (word.Length == 0 || !char.IsLetterOrDigit(word[0])) continue;
sb.Append(char.ToUpperInvariant(word[0]));
if (sb.Length >= max) break;
}
return sb.Length == 0 ? "?" : sb.ToString();
}
public static string Tooltip(int number, ItemRef? item, SlotStatus s, UseMode mode, string? key)
{
if (item == null) return $"Slot {number}: empty. Click to set it up.";
var sb = new StringBuilder();
sb.Append("Slot ").Append(number).Append(": ").Append(s.Item?.FullName ?? item.FullName);
if (s.Item == null)
{
sb.Append("\nNot in your pack - nothing to use. It comes back by itself when you carry one of the same name.");
}
else
{
ItemKind kind = ItemKinds.Classify(s.Item);
UseAction action = UseModes.ActionFor(mode, kind);
sb.Append("\nClick or press the key: ").Append(UseModes.Describe(action).Replace("used", "use it").Replace("wielded", "wield it"));
if (s.Item.MaxUses > 0) sb.Append("\n").Append(s.Uses).Append(" uses left");
if (s.Count > 1 || s.Item.MaxStack > 1) sb.Append(s.Item.MaxUses > 0 ? ", " : "\n").Append(s.Count).Append(" carried");
if (s.Item.Wielded) sb.Append("\nIn your hands now.");
}
sb.Append(key != null ? "\nKey: " + key : "\nNo key yet (Edit slots).");
return sb.ToString();
}
}

View file

@ -99,6 +99,7 @@ internal static class RynthIcons
public const string Ruler = "\uE6B8";
public const string Scales = "\uE750";
public const string Scissors = "\uEAE0";
public const string Scroll = "\uEB7A";
public const string Shield = "\uE40A";
public const string ShieldSlash = "\uE410";
public const string ShieldWarning = "\uE412";

View file

@ -100,6 +100,12 @@ internal static unsafe class RynthUi
RynthUiColor.Red => 0xFFE05A5A,
RynthUiColor.TitleBar => 0xFF1A1A28,
RynthUiColor.WindowBorder => 0xFF008080,
// v90: the default theme's muted text and instrument shades (ThemePalette.DeriveInstrument).
RynthUiColor.Muted => 0xFFB8C8D8,
RynthUiColor.KeyFace => 0xFF111E2B,
RynthUiColor.Hairline => 0xFF1D3042,
RynthUiColor.Inset => 0xFF06080B,
RynthUiColor.Faint => 0xFF8794A1,
_ => 0xFFFFFFFF,
});

View file

@ -192,6 +192,10 @@ internal static unsafe class FakeHost
/// <summary>Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The
/// host then reports API version 73, so only tests that ask for it see the newer calls.</summary>
public static bool WieldCalls;
/// <summary>Opt-in (set before Create): v80 PutItemInContainer (the raw move packet), recorded in <see cref="Puts"/>.</summary>
public static bool PutCalls;
/// <summary>Every PutItemInContainer (item, container, placement), in order (opt-in with <see cref="PutCalls"/>).</summary>
public static readonly List<(uint Id, uint Container, int Placement)> Puts = new();
/// <summary>Every WieldItem (item, EquipMask slot), in order (opt-in with <see cref="WieldCalls"/>).</summary>
public static readonly List<(uint Id, uint Mask)> Wields = new();
/// <summary>Opt-in (set before Create): UseObject, MoveItemExternal, the salvage panel
@ -310,7 +314,7 @@ internal static unsafe class FakeHost
// the PC doesn't change results; the mana reserve tests set their own costs.
RynthCore.Plugin.RynthAi.BuffManager.ManaCostOverride = _ => 0;
#endif
WieldCalls = false; Wields.Clear();
WieldCalls = false; Wields.Clear(); PutCalls = false; Puts.Clear();
SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear();
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
SalvageDirectCalls = false; SalvageDirects.Clear(); SalvageDirectAnswer = null; OnSalvageDirect = null;
@ -459,6 +463,11 @@ internal static unsafe class FakeHost
api.Version = 73;
api.WieldItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&WieldItem;
}
if (PutCalls)
{
api.Version = Math.Max(api.Version, 80u);
api.PutItemInContainerFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&PutItemInContainer;
}
api.GetObjectWcidFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectWcid;
api.GetSelectedItemIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetSelectedItemId;
api.ReadKnownSpellsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, int>)&ReadKnownSpells;
@ -973,6 +982,9 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int WieldItem(uint id, uint mask) { Wields.Add((id, mask)); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int PutItemInContainer(uint id, uint container, int placement) { Puts.Add((id, container, placement)); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CloseContainer(uint id) { Closes.Add(id); return 1; }

View file

@ -72,6 +72,7 @@ internal static class Program
AmmoTests.Register(runner);
VTankYieldTests.Register(runner);
OffhandTests.Register(runner);
HandSwapTests.Register(runner);
FloodPerfTests.Register(runner);
LootSalvageTests.Register(runner);
LootCorpseTests.Register(runner);

View file

@ -727,21 +727,22 @@ internal static class ActionPacingTests
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "set-up: the first request is accepted and starts the stuck clock");
Check.True((DateTime)since.GetValue(r.B)! != DateTime.MinValue, "set-up: the clock is running");
// The request was dropped by a teleport; the engine now refuses. The backoff gate (real clock) is opened by back-dating.
lastTry.SetValue(r.B, DateTime.Now.AddSeconds(-3));
// The request was dropped by a teleport; the engine now refuses. The backoff gate (BuffManager's clock) is opened by back-dating.
lastTry.SetValue(r.B, r.T0.AddSeconds(-1));
FakeHost.CombatModeRefuse = true;
r.At(2); r.B.OnHeartbeat();
Check.True(FakeHost.CombatModeRefusals >= 1, "set-up: a later request was refused");
// 9 s of that: back-date the clock as if the real time had passed (the re-equip rule reads the real clock).
since.SetValue(r.B, DateTime.Now.AddSeconds(-9));
// 9 s of that: back-date the stuck clock 9 s.
since.SetValue(r.B, r.T0);
r.At(9); r.B.OnHeartbeat();
r.At(9.3); r.B.OnHeartbeat();
Check.Eq((int)reEquips.GetValue(r.B)!, 0, "a refusal newer than the clock's start restarted it: _buffStanceReEquips stays 0");
Check.False(FakeHost.Uses.Contains(Wand), "and no UseObject(wand) - a MOVE on a wielded wand - went out");
Check.True((DateTime.Now - (DateTime)since.GetValue(r.B)!).TotalSeconds < 3, "the clock was restarted at now");
Check.True((r.NowAt - (DateTime)since.GetValue(r.B)!).TotalSeconds < 3, "the clock was restarted at now");
FakeHost.CombatModeRefuse = false;
lastTry.SetValue(r.B, r.T0.AddSeconds(7)); // the backoff after the restarted clock's request is over
r.At(9.6); r.B.OnHeartbeat();
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8,8", "accepted again");
Check.Eq((int)reEquips.GetValue(r.B)!, 0, "still no re-equip");

View file

@ -0,0 +1,893 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
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;
// The wand swap as fast as the server allows (2026-10-22, HandSwapSequence). Drakkon on DreamWeave,
// 21:25: Acid + Frost Hand Wraps -> Sceptre took 7.2 s to the first cast, 4.7 s of it our own waits
// (the swap gate's flat 3 s after each pack move). The simulated server below answers the way ACE
// did in that log: the first weapon out of a hand in a combat mode waits for a forced stance change
// (1.25 s), a later one is answered at once, a wield in 60 ms, and a caster wielded in a combat mode
// switches the stance to Magic by itself.
internal static class HandSwapTests
{
private const uint Player = 0x50000D01;
private const uint STypeLife = 33;
private const uint Acid = 0x80000601, Frost = 0x80000602, Sceptre = 0x80000603, Shield = 0x80000604,
Bow = 0x80000605, Arrows = 0x80000606, Great = 0x80000607, OtherWand = 0x80000608;
private static int I(uint id) => unchecked((int)id);
private const int Melee = HandSwapSequence.MeleeSlot, Off = HandSwapSequence.ShieldSlot, Missile = HandSwapSequence.MissileSlot,
Ammo = HandSwapSequence.AmmoSlot, Held = HandSwapSequence.HeldSlot, Two = HandSwapSequence.TwoHandedSlot;
public static void Register(Runner r)
{
r.Add("hand swap: dual wield -> wand: the off hand, then the main hand, then the wand, each once the last landed", DualWieldOrder);
r.Add("hand swap: sword + shield, two-hander, bow (arrows stay on), empty hands, a wand already in hand", Loadouts);
r.Add("hand swap: peace first from a combat mode, then the hands (answered at once in peace), then the wand", PeaceFirst);
r.Add("hand swap: an unanswered step is sent again once, then the swap fails (bounded)", Bounded);
r.Add("hand swap: an item that must stay on (Offhand None) fails the swap instead of stripping the main hand", KeepFails);
r.Add("hand swap: the swap gate is held for the whole swap and freed at its end", GateHeld);
r.Add("wand swap (Drakkon 10-22): two Hand Wraps -> Sceptre -> first heal in under 2 s (was 7.2 s)", DrakkonHealFast);
r.Add("wand swap: a restam (no emergency) casts once the 1 s stance floor is up, about 2.4 s in", RestamFloor);
r.Add("wand swap: in a combat mode RynthAi leaves the Magic switch to the server; from peace it asks itself", ServerSwitchesMagic);
r.Add("wand swap: a swap nothing needs any more stops without counting as a failure", Abandoned);
r.Add("wand swap: a wand the server never wields: retried once, then the kit / potion path gets its turn", WandNeverWields);
r.Add("weapons back (Drakkon 10-22): Sceptre -> two Hand Wraps through peace, then the fight's stance, gate held throughout", RearmThroughPeace);
r.Add("weapons back: a target arriving mid-swap: it goes on for the same weapons; a fight with the wand ends it", RearmAbandoned);
r.Add("a monster with the wand in hand: peace, the Sceptre out, both Hand Wraps on, then Melee (no client use)", FightFromWand);
r.Add("a monster with the wand in hand, burst: the Sceptre out and both Hand Wraps on in one tick", FightFromWandBurst);
r.Add("a monster with the wand in hand: a fight swap that fails leaves that weapon to the client's own swap", FightSwapFallsBack);
r.Add("weapons back burst: peace, the Sceptre out and both Hand Wraps on in one tick, then Melee", RearmBurst);
r.Add("weapons back burst: the quiet check reads BuffManager's mode change, not combat's late one (Drakkon 23:06-23:21)", RearmBurstQuietFromBuff);
r.Add("Fast Weapon Swap: on by default, an old saved off (the opt-in name) loads on, an untick since stays off", OnByDefault);
r.Add("hand swap: a burst waits for every step it sent, then finishes one step at a time if some didn't land", BurstSequence);
r.Add("wand swap burst: peace, both hands and the wand in one tick; the wand in hand one round trip later", BurstFast);
r.Add("wand swap burst: not right after a stance change (the server could defer peace): the step route", BurstWaitsQuiet);
}
// ── The pure sequence ─────────────────────────────────────────────────────
private static readonly DateTime T0 = new(2026, 10, 22, 21, 25, 0);
private static DateTime At(double ms) => T0.AddMilliseconds(ms);
private static void DualWieldOrder()
{
var s = new HandSwapSequence();
var hands = new Dictionary<int, int> { [I(Acid)] = Melee, [I(Frost)] = Off };
s.Start("wand", At(0), new[] { (I(Sceptre), Held) });
var st = s.Next(hands, HandSwapSequence.Melee, At(0));
Check.Eq(st.Act, HandSwapSequence.Act.MoveToPack, "first: a pack move");
Check.Eq(unchecked((uint)st.Id), Frost, "the off hand first (taking the main hand first costs the off hand a second stance change)");
s.Sent(st, At(0));
Check.Eq(s.Next(hands, HandSwapSequence.Melee, At(500)).Act, HandSwapSequence.Act.Wait, "the off hand's move unanswered: wait");
Check.Eq(s.Next(hands, HandSwapSequence.Melee, At(1200)).Act, HandSwapSequence.Act.Wait, "still inside the forced stance change: wait, nothing sent twice");
hands.Remove(I(Frost)); // the server moved it at 1.25 s
st = s.Next(hands, HandSwapSequence.Melee, At(1250));
Check.Eq(st.Act, HandSwapSequence.Act.MoveToPack, "the moment it landed: the main hand, same tick");
Check.Eq(unchecked((uint)st.Id), Acid, "the main hand");
s.Sent(st, At(1250));
hands.Remove(I(Acid));
st = s.Next(hands, HandSwapSequence.Melee, At(1310));
Check.Eq(st.Act, HandSwapSequence.Act.Wield, "hands empty: the wand");
Check.Eq(unchecked((uint)st.Id), Sceptre, "the Sceptre");
Check.Eq(st.Slot, Held, "into the Held slot");
s.Sent(st, At(1310));
hands[I(Sceptre)] = Held;
Check.Eq(s.Next(hands, HandSwapSequence.Melee, At(1370)).Act, HandSwapSequence.Act.Done, "the wand in hand: done");
Check.False(s.Active, "no longer running");
Check.True(s.Trail.Contains("off 0x80000602 1.25 s") && s.Trail.Contains("off 0x80000601 0.06 s") && s.Trail.Contains("on 0x80000603 0.06 s"),
"the trail has each step's answer time: " + s.Trail);
}
private static void PeaceFirst()
{
var s = new HandSwapSequence();
var hands = new Dictionary<int, int> { [I(Acid)] = Melee, [I(Frost)] = Off };
s.Start("wand", At(0), new[] { (I(Sceptre), Held) }, peaceFirst: true);
var st = s.Next(hands, HandSwapSequence.Melee, At(0));
Check.True(st.Act == HandSwapSequence.Act.Stance && st.Slot == HandSwapSequence.NonCombat, "in Melee: peace first, before anything leaves a hand");
s.Sent(st, At(0));
Check.Eq(s.Next(hands, HandSwapSequence.Melee, At(30)).Act, HandSwapSequence.Act.Wait, "until the mode reads peace");
st = s.Next(hands, HandSwapSequence.NonCombat, At(45));
Check.True(st.Act == HandSwapSequence.Act.MoveToPack && unchecked((uint)st.Id) == Frost, "peace read: the off hand, the same tick");
s.Sent(st, At(45));
hands.Remove(I(Frost));
st = s.Next(hands, HandSwapSequence.NonCombat, At(105));
Check.True(st.Act == HandSwapSequence.Act.MoveToPack && unchecked((uint)st.Id) == Acid, "then the main hand");
s.Sent(st, At(105));
hands.Remove(I(Acid));
st = s.Next(hands, HandSwapSequence.NonCombat, At(165));
Check.True(st.Act == HandSwapSequence.Act.Wield && unchecked((uint)st.Id) == Sceptre, "then the wand");
s.Sent(st, At(165));
hands[I(Sceptre)] = Held;
Check.Eq(s.Next(hands, HandSwapSequence.NonCombat, At(225)).Act, HandSwapSequence.Act.Done, "done (Magic is the caller's next step)");
Check.True(s.WentThroughPeace, "it went through peace");
Check.True(s.Trail.StartsWith("peace 0.0"), "the trail starts with the peace step: " + s.Trail);
// Already in peace, or nothing to take off: no stance step.
s.Start("wand", At(0), new[] { (I(Sceptre), Held) }, peaceFirst: true);
Check.Eq(s.Next(new Dictionary<int, int> { [I(Acid)] = Melee }, HandSwapSequence.NonCombat, At(0)).Act, HandSwapSequence.Act.MoveToPack, "in peace already: straight to the move");
s.Start("wand", At(0), new[] { (I(Sceptre), Held) }, peaceFirst: true);
Check.Eq(s.Next(new Dictionary<int, int>(), HandSwapSequence.Melee, At(0)).Act, HandSwapSequence.Act.Wield, "hands empty: no peace detour, just the wield");
// Peace never read: after PeaceResolveMs the swap goes on without it.
s.Start("wand", At(0), new[] { (I(Sceptre), Held) }, peaceFirst: true);
var h2 = new Dictionary<int, int> { [I(Acid)] = Melee };
s.Sent(s.Next(h2, HandSwapSequence.Melee, At(0)), At(0));
Check.Eq(s.Next(h2, HandSwapSequence.Melee, At(1499)).Act, HandSwapSequence.Act.Wait, "waits up to 1.5 s for peace");
Check.Eq(s.Next(h2, HandSwapSequence.Melee, At(1500)).Act, HandSwapSequence.Act.MoveToPack, "then moves anyway");
Check.True(s.Trail.Contains("peace not read"), "and says so: " + s.Trail);
}
private static void Loadouts()
{
// Sword + shield: the shield, the sword, the wand.
Check.Eq(Order(new() { [I(Acid)] = Melee, [I(Shield)] = Off }), "move 80000604, move 80000601, wield 80000603", "sword + shield");
// A two-hander: it, then the wand.
Check.Eq(Order(new() { [I(Great)] = Two }), "move 80000607, wield 80000603", "two-hander");
// Bow and arrows: the bow only; arrows stay in the ammo slot (the server allows them beside a caster).
Check.Eq(Order(new() { [I(Bow)] = Missile, [I(Arrows)] = Ammo }), "move 80000605, wield 80000603", "bow, arrows stay");
// Empty hands: just the wield.
Check.Eq(Order(new()), "wield 80000603", "hands empty");
// Another caster in hand: it comes off first.
Check.Eq(Order(new() { [I(OtherWand)] = Held }), "move 80000608, wield 80000603", "another wand in hand");
// The wand already in hand: done at once, nothing sent.
var s = new HandSwapSequence();
s.Start("wand", At(0), new[] { (I(Sceptre), Held) });
Check.Eq(s.Next(new Dictionary<int, int> { [I(Sceptre)] = Held }, HandSwapSequence.Melee, At(0)).Act, HandSwapSequence.Act.Done, "already in hand: done");
// Wanted in hand but something else beside it (a shield): the shield still comes off.
s.Start("wand", At(0), new[] { (I(Sceptre), Held) });
var st = s.Next(new Dictionary<int, int> { [I(Sceptre)] = Held, [I(Shield)] = Off }, HandSwapSequence.Melee, At(0));
Check.True(st.Act == HandSwapSequence.Act.MoveToPack && unchecked((uint)st.Id) == Shield, "a wand beside a shield: the shield off");
}
/// <summary>Runs a swap to the Sceptre against an instant server and lists what was sent.</summary>
private static string Order(Dictionary<int, int> hands)
{
var s = new HandSwapSequence();
s.Start("wand", At(0), new[] { (I(Sceptre), Held) });
var sent = new List<string>();
for (int i = 0; i < 10; i++)
{
var st = s.Next(hands, HandSwapSequence.Melee, At(i * 100));
if (st.Act == HandSwapSequence.Act.Done || st.Act == HandSwapSequence.Act.Failed) break;
if (st.Act == HandSwapSequence.Act.Wait) continue;
s.Sent(st, At(i * 100));
if (st.Act == HandSwapSequence.Act.MoveToPack) { hands.Remove(st.Id); sent.Add($"move {(uint)st.Id:X8}"); }
else { hands[st.Id] = st.Slot; sent.Add($"wield {(uint)st.Id:X8}"); }
}
return string.Join(", ", sent);
}
private static void Bounded()
{
var s = new HandSwapSequence();
var hands = new Dictionary<int, int> { [I(Acid)] = Melee };
s.Start("wand", At(0), new[] { (I(Sceptre), Held) });
var st = s.Next(hands, HandSwapSequence.Melee, At(0));
s.Sent(st, At(0));
Check.Eq(s.Next(hands, HandSwapSequence.Melee, At(3999)).Act, HandSwapSequence.Act.Wait, "inside StepResolveMs: wait");
st = s.Next(hands, HandSwapSequence.Melee, At(4000));
Check.True(st.Act == HandSwapSequence.Act.MoveToPack && unchecked((uint)st.Id) == Acid, "unanswered for 4 s: sent again");
s.Sent(st, At(4000));
st = s.Next(hands, HandSwapSequence.Melee, At(8000));
Check.Eq(st.Act, HandSwapSequence.Act.Failed, "the second send unanswered too: the swap fails");
Check.Eq(unchecked((uint)s.FailedId), Acid, "and says which item went unanswered");
Check.False(s.Active, "stopped");
Check.True(s.Trail.Contains("no answer"), "the trail says so: " + s.Trail);
// The whole swap has a ceiling too.
var g = new HandSwapSequence { StepResolveMs = 100_000 };
g.Start("wand", At(0), new[] { (I(Sceptre), Held) });
g.Sent(g.Next(hands, HandSwapSequence.Melee, At(0)), At(0));
Check.Eq(g.Next(hands, HandSwapSequence.Melee, At(12_001)).Act, HandSwapSequence.Act.Wait, "a step still inside its own wait...");
hands.Clear();
Check.Eq(g.Next(hands, HandSwapSequence.Melee, At(12_002)).Act, HandSwapSequence.Act.Failed, "...lands after GiveUpMs: the swap fails, not another step");
}
private static void KeepFails()
{
var s = new HandSwapSequence();
var hands = new Dictionary<int, int> { [I(Acid)] = Melee, [I(Shield)] = Off };
s.Start("wand", At(0), new[] { (I(Sceptre), Held) }, keep: new[] { I(Shield) });
var st = s.Next(hands, HandSwapSequence.Melee, At(0));
Check.Eq(st.Act, HandSwapSequence.Act.Failed, "the shield may not come off: fail at once");
Check.True(hands.ContainsKey(I(Acid)), "nothing was taken off for nothing");
}
private static void GateHeld()
{
long t = 0;
var g = new WeaponSwapGate { NowMs = () => t, ServerIdle = () => true, IsWielded = _ => false };
Check.True(g.TryBeginSwap("buff-wand"), "the swap claims the gate");
g.Hold("buff-wand", 13_000);
t = 4000;
Check.False(g.TryBeginSwap("rearm-after-vitals"), "held: no other swap, even after the old 3 s");
Check.Eq(g.HeldBy, "buff-wand", "who holds it");
g.Release("someone-else", 0);
Check.False(g.TryBeginSwap("combat"), "only the holder releases it");
g.Release("buff-wand", I(Sceptre));
Check.Eq(g.HeldBy, "", "released");
t = 6999;
Check.False(g.TryBeginSwap("combat"), "after its last wield, the next swap still waits the full 3 s");
t = 7000;
Check.True(g.TryBeginSwap("combat"), "then it goes");
// A hold nobody releases runs out.
g.Hold("buff-wand", 1000);
t = 8001;
Check.True(g.TryBeginSwap("combat"), "a forgotten hold ends at its backstop");
}
// ── Through BuffManager, against a simulated server ───────────────────────
/// <summary>
/// Plays ACE for the rig: pack moves and wields the plugin sent are answered with the timings
/// of Drakkon's 21:25 log, and a caster wielded in a combat mode switches the stance to Magic.
/// </summary>
private sealed class Server
{
public double ForcedStanceMs = 1250, AnswerMs = 60;
public bool SwitchesMagic = true;
public bool IgnoresStance; // stance requests change nothing, on the server or the client
public int RefusedWields;
public bool WieldsWand = true;
private readonly List<(double At, Action Do)> _due = new();
private int _moves, _wields, _modes, _puts;
private int? _serverMode; // the server's own mode (the client's read follows it by EchoMs)
private bool _stanced; // the forced stance change to bare hands has been played this swap
private double _nextUse = -1000; // ACE's NextUseTime: a stance change waits for the last one's animation
public double PeaceLegMs = 545, MagicLegMs = 521, EchoMs = 40;
public void Observe(double now)
{
_serverMode ??= FakeHost.CombatModeValue;
while (FakeHost.CombatModeRequests.Count > _modes)
{
int mode = FakeHost.CombatModeRequests[_modes++];
if (IgnoresStance) continue;
double runAt = Math.Max(now + EchoMs, _nextUse + 50);
if (now >= _nextUse + 50) _serverMode = mode; // run at once on the server (NextUseTime passed)
else _due.Add((runAt - EchoMs, () => _serverMode = mode));
double leg = mode == CombatMode.NonCombat ? PeaceLegMs : MagicLegMs + (FakeHost.CombatModeValue == CombatMode.NonCombat ? 0 : PeaceLegMs);
_nextUse = runAt + leg;
_due.Add((runAt, () => FakeHost.CombatModeValue = mode));
}
var moved = new List<uint>();
while (FakeHost.Moves.Count > _moves) moved.Add(FakeHost.Moves[_moves++].Id);
while (FakeHost.Puts.Count > _puts) moved.Add(FakeHost.Puts[_puts++].Id);
foreach (uint id in moved)
{
if (!FakeHost.Equipped.ContainsKey(id)) continue;
bool combat = _serverMode != CombatMode.NonCombat;
double after = combat && !_stanced ? ForcedStanceMs : AnswerMs;
if (combat) _stanced = true;
_due.Add((now + after, () => FakeHost.Equipped.Remove(id)));
}
while (FakeHost.Wields.Count > _wields)
{
var w = FakeHost.Wields[_wields++];
if (!WieldsWand) continue;
_due.Add((now + AnswerMs, () =>
{
// ACE refuses a Held caster with anything still in a hand (CheckWeaponCollision).
if (w.Mask == (uint)Held && FakeHost.Equipped.Any(kv => kv.Key != w.Id && (kv.Value & (uint)(Melee | Off | Missile | Two)) != 0))
{ RefusedWields++; return; }
FakeHost.Equipped[w.Id] = w.Mask;
if (SwitchesMagic && w.Mask == (uint)Held && FakeHost.CombatModeValue != CombatMode.NonCombat)
FakeHost.CombatModeValue = CombatMode.Magic;
}));
}
}
public void Answer(double now)
{
foreach (var d in _due.Where(d => d.At <= now).ToList()) { d.Do(); _due.Remove(d); }
}
}
private sealed class Rig
{
public readonly BuffManager B;
public readonly LegacyUiSettings S;
public readonly PlayerVitalsCache V;
public readonly WeaponSwapGate Gate;
public readonly Server Sv = new();
public DateTime NowAt = T0;
public double FirstCastMs = -1;
private bool _inCombat = true;
public Rig(int healthPct = 50, int staminaPct = 100, int mode = CombatMode.Melee, bool dualWield = true, bool putCalls = false)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.WieldCalls = true;
FakeHost.EquippedCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.StopCalls = true;
FakeHost.PutCalls = putCalls;
FakeHost.CombatModeValue = mode;
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
Item(Acid, "Acid Hand Wraps", 0x1, Melee);
Item(Frost, "Frost Hand Wraps", 0x1, Melee);
Item(Sceptre, "Sceptre", 0x8000, Held);
FakeHost.Appraised.Add(Sceptre);
FakeHost.Equipped[Acid] = (uint)Melee;
if (dualWield) FakeHost.Equipped[Frost] = (uint)Off;
var host = FakeHost.Create(Player);
S = new LegacyUiSettings
{
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 30, StaminaToHealthAt = 0,
GetManaAt = 0, TopOffMana = 0, RestamAt = 35, RestamTo = 0, TopOffStam = 35, UsePotions = false,
EnableBuffing = false, SpellCastIntervalMs = 400, FastWeaponSwap = true,
};
S.ItemRules = new List<ItemRule>
{
new() { Id = unchecked(I(Acid)), Name = "Acid Hand Wraps", Element = "", ElementSource = "", Action = "Weapon" },
new() { Id = unchecked(I(Frost)), Name = "Frost Hand Wraps", Element = "", ElementSource = "", Action = "Weapon" },
new() { Id = unchecked(I(Sceptre)), Name = "Sceptre", Element = "", ElementSource = "", Action = "Weapon" },
};
var skills = new CharacterSkills(host);
skills.SetPlayerId(Player);
var sm = new SpellManager(host, S);
sm.InitializeNatively();
sm.SetCharacterSkills(skills);
V = new PlayerVitalsCache
{
MaxHealth = 100, CurrentHealth = (uint)healthPct, MaxStamina = 100, CurrentStamina = (uint)staminaPct,
MaxMana = 100, CurrentMana = 100,
};
B = new BuffManager(host, S, sm, V) { InCombatOverride = () => _inCombat };
B.SetCharacterSkills(skills);
B.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { Acid, Frost, Sceptre }));
Gate = new WeaponSwapGate { NowMs = () => (long)(NowAt - T0).TotalMilliseconds + 100_000, ServerIdle = () => true, IsWielded = _ => false };
B.SetWeaponSwapGate(Gate);
B.Clock = () => NowAt;
B.MarkLiveBuffsReadyForTests();
EquippedState.Clock = () => (long)(NowAt - T0).TotalMilliseconds + 100_000;
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.NowMs = () => 50_000_000 + (long)(NowAt - T0).TotalMilliseconds;
MoveAudit.Reset();
MoveAudit.NowMs = ActionPacer.NowMs;
FakeHost.UseDone(0);
}
public bool InCombat { set => _inCombat = value; }
private static void Item(uint id, string name, uint itemType, int slots)
{
FakeHost.Names[id] = name;
FakeHost.ItemTypes[id] = itemType;
FakeHost.Ints[(id, 9)] = slots;
}
/// <summary>Heartbeats every 25 ms (the plugin's tick) from <paramref name="fromMs"/> to <paramref name="toMs"/>, the server answering between them.</summary>
public void Run(double fromMs, double toMs)
{
for (double ms = fromMs; ms <= toMs; ms += 25)
{
NowAt = At(ms);
Sv.Answer(ms);
int casts = FakeHost.Casts.Count;
B.OnHeartbeat();
Sv.Observe(ms);
if (FirstCastMs < 0 && FakeHost.Casts.Count > casts) FirstCastMs = ms;
string hold = (string)(typeof(BuffManager).GetField("_healHold", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(B) ?? "");
string why = hold + " | " + B.LastBuffSkipReason;
if (why != _lastWhy) { Trace.Add($"{ms:0} mode={FakeHost.CombatModeValue} {why}"); _lastWhy = why; }
}
}
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
public readonly List<string> Trace = new();
private string _lastWhy = "";
}
private static void Done()
{
ActionPacer.Enabled = false;
ActionPacer.Reset();
ActionPacer.NowMs = () => Environment.TickCount64;
MoveAudit.Reset();
MoveAudit.NowMs = () => Environment.TickCount64;
EquippedState.Clock = null;
EquippedState.Invalidate();
}
private static void DrakkonHealFast()
{
try
{
var rig = new Rig(healthPct: 50); // under Heal At, a monster in range: an urgent heal
rig.Run(0, 4000);
Check.True(FakeHost.Moves.Count == 2 && FakeHost.Moves[0].Id == Frost && FakeHost.Moves[1].Id == Acid,
"the off hand (Frost), then the main hand (Acid): " + string.Join(", ", FakeHost.Moves.Select(m => $"{m.Id:X8}")));
Check.True(FakeHost.Wields.Count == 1 && FakeHost.Wields[0] == (Sceptre, (uint)Held), "one wield: the Sceptre into the Held slot");
Check.False(FakeHost.Uses.Contains(Sceptre), "no use of the wand (the client's own swap takes the main hand first)");
Check.True(rig.FirstCastMs > 0, "the heal went out" + Environment.NewLine + string.Join(Environment.NewLine, FakeHost.Logs.TakeLast(60)) + Environment.NewLine + "mode=" + FakeHost.CombatModeValue + " requests=" + string.Join(",", FakeHost.CombatModeRequests) + Environment.NewLine + string.Join(Environment.NewLine, rig.Trace));
Check.True(rig.FirstCastMs <= 1500, $"first heal {rig.FirstCastMs:0} ms after the swap began (was 7.2 s)" + Environment.NewLine + string.Join(Environment.NewLine, rig.Trace) + Environment.NewLine +
string.Join(Environment.NewLine, FakeHost.Logs.Where(l => l.Contains("[WieldGate]") || l.Contains("[BuffStance]") || l.Contains("[Pace]"))));
Check.True(rig.Logged("[WieldGate] wand in hand"), "the swap's time and steps are logged");
Console.WriteLine($" (simulated: first cast {rig.FirstCastMs:0} ms after the swap began; " + FakeHost.Logs.FirstOrDefault(l => l.Contains("wand in hand")) + ")");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free again");
}
finally { Done(); }
}
private static void RestamFloor()
{
try
{
var rig = new Rig(healthPct: 100, staminaPct: 20); // Re-stam At 35: Revitalize, not an emergency
rig.Run(0, 5000);
Check.True(rig.FirstCastMs > 0, "the restam went out");
Console.WriteLine($" (simulated: first cast {rig.FirstCastMs:0} ms after the swap began; " + FakeHost.Logs.FirstOrDefault(l => l.Contains("wand in hand")) + ")");
// Peace, both hands and the wand go in about 0.3 s; Magic is asked for the moment the wand is
// in hand (the server starts it when the peace animation ends), and the first non-emergency
// cast waits the 1 s stance floor from that request (BuffManager.StanceMinAfterRequestMs).
Check.True(rig.FirstCastMs >= 1100 && rig.FirstCastMs <= 1500, $"first cast {rig.FirstCastMs:0} ms in" + Environment.NewLine +
string.Join(Environment.NewLine, FakeHost.Logs.Where(l => l.Contains("[WieldGate]") || l.Contains("[BuffStance]") || l.Contains("[Pace]"))));
}
finally { Done(); }
}
private static void ServerSwitchesMagic()
{
try
{
// The peace route: peace, the hands, the wand, then our own Magic request (the server
// doesn't switch a caster wielded in peace).
var rig = new Rig(healthPct: 50);
rig.Run(0, 3000);
Check.True(FakeHost.CombatModeRequests.Count >= 2 && FakeHost.CombatModeRequests[0] == CombatMode.NonCombat
&& FakeHost.CombatModeRequests.Contains(CombatMode.Magic), "peace, then Magic: " + string.Join(",", FakeHost.CombatModeRequests));
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.NonCombat), 1, "one peace request");
// Peace never comes (the server ignores it): the hands come off in Melee after 1.5 s, the
// wand goes on in Melee, and the server's own switch to Magic is waited for, not doubled.
var slow = new Rig(healthPct: 50);
slow.Sv.IgnoresStance = true;
slow.Run(0, 1400);
Check.Eq(FakeHost.Moves.Count, 0, "nothing leaves a hand while peace is awaited");
slow.Sv.IgnoresStance = false; // later stance changes are answered again
slow.Run(1425, 4500);
Check.Eq(FakeHost.Wields.Count, 1, "the wand went on in Melee");
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, "no Magic request of ours: the server switched by itself");
Check.True(slow.Logged("peace not read"), "the trail says peace never came");
// Already in peace: no stance change to wait out; both hands at once, then Magic.
var peace = new Rig(healthPct: 50, mode: CombatMode.NonCombat);
peace.Run(0, 600);
Check.True(FakeHost.Moves.Count == 2, "in peace both hands come off at once (no forced stance change)");
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.NonCombat), 0, "no peace request in peace");
Check.True(FakeHost.CombatModeRequests.Contains(CombatMode.Magic), "and our Magic request follows the wield");
}
finally { Done(); }
}
private static void Abandoned()
{
try
{
var rig = new Rig(healthPct: 50);
rig.Sv.IgnoresStance = true; // peace never comes...
rig.Sv.ForcedStanceMs = 3000; // ...and the melee-mode move is slow
rig.Run(0, 300);
rig.V.CurrentHealth = 100; // healed some other way: nothing needs the wand
rig.Run(325, 5000);
Check.True(rig.Logged("nothing needs the wand now"), "the swap stops");
Check.Eq(FakeHost.Wields.Count, 0, "no wand wield");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
Check.False(rig.Logged("didn't wield"), "not counted against the wand");
}
finally { Done(); }
}
private static void WandNeverWields()
{
try
{
var rig = new Rig(healthPct: 50);
rig.Sv.WieldsWand = false;
rig.Run(0, 10_500);
Check.Eq(FakeHost.Wields.Count, 2, "the wield is sent twice, then the swap stops");
Check.True(rig.Logged("the switch to the wand stopped"), "logged with its steps");
Check.Eq(FakeHost.Casts.Count, 0, "no cast without the wand");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
}
finally { Done(); }
}
// ── Weapons back after heals (CombatManager.RearmAfterVitalsStep) ────────
private sealed class CombatRig
{
public readonly CombatManager C;
public readonly LegacyUiSettings S = new() { IsMacroRunning = true, RearmAfterVitals = true, PeaceModeWhenIdle = false, FastWeaponSwap = true };
public readonly WeaponSwapGate Gate;
public readonly Server Sv = new() { ForcedStanceMs = 1127 };
private readonly System.Reflection.MethodInfo _step = typeof(CombatManager).GetMethod("RearmAfterVitalsStep",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
public double SimMs;
public CombatRig(bool putCalls = false)
{
FakeHost.Reset();
FakeHost.PutCalls = putCalls;
FakeHost.WeaponCalls = true;
FakeHost.WieldCalls = true;
FakeHost.EquippedCalls = true;
FakeHost.CombatModeCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
foreach (var (id, name, type, slots) in new[] { (Acid, "Acid Hand Wraps", 0x1u, Melee), (Frost, "Frost Hand Wraps", 0x1u, Melee), (Sceptre, "Sceptre", 0x8000u, Held) })
{
FakeHost.Names[id] = name; FakeHost.ItemTypes[id] = type; FakeHost.Ints[(id, 9)] = slots;
}
FakeHost.Equipped[Sceptre] = (uint)Held;
var host = FakeHost.Create(Player);
S.ItemRules = new List<ItemRule>
{
new() { Id = I(Acid), Name = "Acid Hand Wraps", Element = "", ElementSource = "", Action = "Weapon" },
new() { Id = I(Frost), Name = "Frost Hand Wraps", Element = "", ElementSource = "", Action = "Weapon" },
new() { Id = I(Sceptre), Name = "Sceptre", Element = "", ElementSource = "", Action = "Weapon" },
};
var cache = FakeHost.MakeCache(host, Player, new[] { Acid, Frost, Sceptre });
C = new CombatManager(host, S, cache);
C.SetPlayerId(Player);
C.OpenPackOverride = () => I(Player);
const System.Reflection.BindingFlags F = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
typeof(CombatManager).GetField("_fightMainId", F)!.SetValue(C, I(Acid));
typeof(CombatManager).GetField("_fightOffId", F)!.SetValue(C, I(Frost));
DateTime vital = RynthClock.Now.AddSeconds(-2); // a heal went out 2 s ago
C.LastVitalCastAt = () => vital;
C.BuffingWantsTick = () => false;
Gate = new WeaponSwapGate { MinIntervalMs = 0 };
C.SetWeaponSwapGate(Gate);
ActionPacer.Enabled = false; // the pacer's rules have their own tests; this is the order
EquippedState.Clock = () => (long)SimMs + 100_000;
}
/// <summary>RearmAfterVitalsStep every 25 ms (sim time), the server answering between ticks; true when it reported done.</summary>
public bool Run(double toMs)
{
for (; SimMs <= toMs; SimMs += 25)
{
Sv.Answer(SimMs);
bool busy = (bool)_step.Invoke(C, null)!;
Sv.Observe(SimMs);
if (!busy && FakeHost.Logs.Any(l => l.Contains("in hand") && l.Contains("weapons back after heals: 0x"))) return true;
}
return false;
}
// ── A fight (combat's own equip) ──
public readonly WorldObject Target = new(unchecked((int)0x80009999), "Test Dummy", AcObjectClass.Monster);
private const System.Reflection.BindingFlags NP = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
private readonly System.Reflection.MethodInfo _equip = typeof(CombatManager).GetMethod("EquipWeaponAndSetStance", NP)!;
private readonly System.Reflection.MethodInfo _tick = typeof(CombatManager).GetMethod("TickRearmSwap", NP)!;
/// <summary>A monster to fight: dual wield trained, Frost the Default rule's off-hand pick (Drakkon's setup).</summary>
public void Fighting()
{
typeof(CombatManager).GetField("_activeTargetId", NP)!.SetValue(C, unchecked((int)0x80009999));
}
/// <summary>The heartbeat's hands-swap tick, then combat's equip, every 25 ms (sim time); the sim time combat was ready to attack (-1 = not by <paramref name="toMs"/>).</summary>
public double Fight(double toMs)
{
for (; SimMs <= toMs; SimMs += 25)
{
Sv.Answer(SimMs);
_tick.Invoke(C, null);
bool ready = (bool)_equip.Invoke(C, new object[] { Target, "Auto" })!;
Sv.Observe(SimMs);
if (ready) return SimMs;
}
return -1;
}
public bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
}
/// <summary>The rig for a fight that starts with the wand in hand (a monster came while healing).</summary>
private static CombatRig FightRig(bool putCalls = false)
{
var rig = new CombatRig(putCalls);
Fightable(rig);
rig.C.LastVitalCastAt = () => DateTime.MinValue; // no weapons back pending
rig.Fighting();
return rig;
}
/// <summary>Drakkon's fight setup: Dual Wield trained, Frost the Default rule's off-hand pick, no war magic.</summary>
private static void Fightable(CombatRig rig)
{
FakeHost.Skills[(Player, 49)] = (220, 2);
var skills = new CharacterSkills(FakeHost.Create(Player));
skills.SetPlayerId(Player);
rig.C.SetCharacterSkills(skills);
rig.C.CanCastOverride = _ => false;
rig.S.MonsterRules = new List<MonsterRule> { new() { Name = "Default", OffhandId = I(Frost) } };
}
private static void FightFromWand()
{
try
{
var rig = FightRig();
rig.C.SwapBurstEnabled = () => false;
double ready = rig.Fight(3000);
string log = string.Join(Environment.NewLine, FakeHost.Logs.Where(l => l.Contains("[EquipDiag]")).TakeLast(30));
Check.True(ready > 0, "ready to attack within 3 s: " + log);
Check.False(FakeHost.Uses.Any(), "no use (the client's own swap pays a forced stance change in Magic): " + string.Join(",", FakeHost.Uses.Select(u => $"{u:X8}")));
Check.Eq(FakeHost.CombatModeRequests.FirstOrDefault(), CombatMode.NonCombat, "peace first: " + string.Join(",", FakeHost.CombatModeRequests));
Check.True(FakeHost.CombatModeRequests.Contains(CombatMode.Melee), "then Melee");
Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Sceptre, "the Sceptre into the pack");
Check.True(FakeHost.Wields.Count == 2 && FakeHost.Wields[1].Mask == (uint)Off
&& FakeHost.Wields.Select(w => w.Id).OrderBy(i => i).SequenceEqual(new[] { Acid, Frost }),
"a Hand Wraps in each hand: " + string.Join(", ", FakeHost.Wields.Select(w => $"{w.Id:X8}@{w.Mask:X}")));
Check.True(rig.Logged("weapons for the fight in hand"), "the swap's time and steps are logged: " + log);
Check.True(ready <= 900, $"ready {ready:0} ms in (the client's own swap: weapons at 1.4-1.7 s)");
Console.WriteLine($" (simulated: ready to attack {ready:0} ms in; " + FakeHost.Logs.FirstOrDefault(l => l.Contains("weapons for the fight in hand")) + ")");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void FightFromWandBurst()
{
try
{
var rig = FightRig(putCalls: true);
rig.C.SwapBurstEnabled = () => true;
double ready = rig.Fight(3000);
Check.True(ready > 0, "ready to attack: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("weapons for the fight"))));
Check.True(FakeHost.Puts.Count == 1 && FakeHost.Puts[0].Id == Sceptre, "the Sceptre out with the raw move");
Check.Eq(FakeHost.Moves.Count, 0, "no client-gated move");
Check.Eq(FakeHost.Wields.Count, 2, "both Hand Wraps");
Check.True(rig.Logged("weapons for the fight burst"), "logged");
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1,2", "peace, then Melee");
Check.True(ready <= 700, $"ready {ready:0} ms in (Melee waits for the peace leg on the server)");
Console.WriteLine($" (simulated burst: ready to attack {ready:0} ms in; " + FakeHost.Logs.FirstOrDefault(l => l.Contains("weapons for the fight in hand")) + ")");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void FightSwapFallsBack()
{
try
{
var rig = FightRig();
rig.C.SwapBurstEnabled = () => false;
rig.Sv.WieldsWand = false; // the server answers no wield
var seq = (HandSwapSequence)typeof(CombatManager).GetField("_rearmSwap", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(rig.C)!;
seq.StepResolveMs = 0; // (real time) an unanswered step is sent again at once
rig.Fight(1000);
Check.True(rig.Logged("weapons for the fight stopped"), "the swap stops: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("weapons for the fight"))));
Check.True(rig.Logged("the client's own swap for 0x80000601") || rig.Logged("the client's own swap for 0x80000602"), "and leaves that weapon to the client's own swap for a while");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void RearmThroughPeace()
{
try
{
var rig = new CombatRig();
Check.True(rig.Run(3000), "the weapons are back within 3 s of sim time: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("weapons back"))));
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1,2", "peace, then Melee (the fight's stance) once the weapons are on");
Check.True(FakeHost.Moves.Count == 1 && FakeHost.Moves[0].Id == Sceptre, "the Sceptre into the pack");
Check.True(FakeHost.Wields.Count == 2 && FakeHost.Wields[0] == (Acid, (uint)Melee) && FakeHost.Wields[1] == (Frost, (uint)Off),
"the main hand, then the off hand: " + string.Join(", ", FakeHost.Wields.Select(w => $"{w.Id:X8}@{w.Mask:X}")));
Check.False(FakeHost.Uses.Any(), "no use (the client's own swap pays a forced stance change in Magic)");
Check.True(rig.SimMs <= 1200, $"done {rig.SimMs:0} ms in (was 2.3 s)");
Console.WriteLine($" (simulated: weapons back {rig.SimMs:0} ms after the swap began; " + FakeHost.Logs.FirstOrDefault(l => l.Contains("weapons back in hand")) + ")");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
rig.Sv.Answer(rig.SimMs + 2000); // the server's deferred stance change runs
Check.Eq(FakeHost.CombatModeValue, CombatMode.Melee, "in Melee mode");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void RearmAbandoned()
{
try
{
var rig = new CombatRig();
rig.Sv.EchoMs = 60_000; // peace never comes: the swap is waiting
rig.Run(200);
Check.Eq(rig.Gate.HeldBy, "rearm-after-vitals", "the swap holds the gate");
// A target appears: the swap goes on (2026-10-23; ending it freed the gate only after 3 s), and
// combat's equip, wanting the same weapons, waits for it.
Fightable(rig);
rig.Fighting();
rig.C.OnHeartbeat();
Check.Eq(rig.Gate.HeldBy, "rearm-after-vitals", "still held: the swap goes on with a target");
Check.Eq(rig.Fight(225), -1.0, "combat waits for the swap");
Check.True(rig.Logged("the same weapons for 'Test Dummy', going on"), "logged");
Check.False(rig.Logged("weapons back stopped"), "not stopped");
// The fight wants the wand instead: the swap ends and the gate is free for combat's wand.
var cache = (WorldObjectCache)typeof(CombatManager).GetField("_worldFilter", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(rig.C)!;
var sceptre = cache[I(Sceptre)]!;
bool wait = (bool)typeof(CombatManager).GetMethod("FightJoinsHandsSwap", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.Invoke(rig.C, new object?[] { rig.Target, null, I(Sceptre), sceptre })!;
Check.False(wait, "combat's own equip goes on");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
Check.True(rig.Logged("is fought with the wand"), "logged");
// While no target: the heartbeat itself moves the swap on (the combat tick's gates can hold the step call).
var rig2 = new CombatRig();
rig2.C.SwapBurstEnabled = () => false;
rig2.Run(0);
Check.Eq(FakeHost.CombatModeRequests.FirstOrDefault(), CombatMode.NonCombat, "tick 0: peace first");
rig2.Sv.Observe(0);
rig2.Sv.Answer(100);
int movesBefore = FakeHost.Moves.Count;
rig2.C.OnHeartbeat(); // no RearmAfterVitalsStep call: the heartbeat goes on with it
Check.True(FakeHost.Moves.Count > movesBefore, "the Sceptre's move went from the heartbeat");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
// ── The setting ───────────────────────────────────────────────────────────
private static void OnByDefault()
{
Check.True(new LegacyUiSettings().FastWeaponSwap, "a new settings object has Fast Weapon Swap on");
var ctx = RynthAiJsonContext.Default.LegacyUiSettings;
var node = System.Text.Json.Nodes.JsonNode.Parse(System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings(), ctx))!.AsObject();
Check.True(node.ContainsKey("FastWeaponSwapOn"), "saved under its 10-23 name");
Check.False(node.ContainsKey("FastWeaponSwap"), "the opt-in build's name is no longer written");
// The opt-in build (10-22) saved "FastWeaponSwap": false into every profile it touched: on now.
node.Remove("FastWeaponSwapOn");
node["FastWeaponSwap"] = false;
var old = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!;
var live = new LegacyUiSettings { FastWeaponSwap = false };
CopySettings(old, live);
Check.True(live.FastWeaponSwap, "an old saved false (the opt-in name) loads on");
// Unticked since (saved under the new name): stays off, the swap as before.
node.Remove("FastWeaponSwap");
node["FastWeaponSwapOn"] = false;
var off = System.Text.Json.JsonSerializer.Deserialize(node.ToJsonString(), ctx)!;
var live2 = new LegacyUiSettings();
CopySettings(off, live2);
Check.False(live2.FastWeaponSwap, "unticked since 10-23: stays off");
}
private static void CopySettings(LegacyUiSettings src, LegacyUiSettings dst) =>
typeof(RynthCore.Plugin.RynthAi.LegacyUi.LegacyDashboardRenderer).GetMethod("CopySettings",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)!
.Invoke(null, new object[] { src, dst });
// ── The burst ─────────────────────────────────────────────────────────────
private static void BurstSequence()
{
var s = new HandSwapSequence();
var hands = new Dictionary<int, int> { [I(Acid)] = Melee, [I(Frost)] = Off };
s.Start("wand", At(0), new[] { (I(Sceptre), Held) }, peaceFirst: true);
Check.Eq(string.Join(",", s.Blockers(hands).Select(i => $"{(uint)i:X8}")), "80000602,80000601", "the burst's moves: the off hand first");
s.SentBurst(s.Blockers(hands), At(0));
Check.Eq(s.Next(hands, HandSwapSequence.Melee, At(30)).Act, HandSwapSequence.Act.Wait, "nothing landed yet: wait");
hands.Remove(I(Frost)); hands.Remove(I(Acid));
Check.Eq(s.Next(hands, HandSwapSequence.NonCombat, At(90)).Act, HandSwapSequence.Act.Wait, "both off, the wand not yet: wait");
hands[I(Sceptre)] = Held;
Check.Eq(s.Next(hands, HandSwapSequence.NonCombat, At(120)).Act, HandSwapSequence.Act.Done, "all landed: done");
Check.True(s.WentThroughPeace, "peace was read during the burst");
Check.True(s.Trail.StartsWith("burst, off 0x80000602 0.09 s"), "the trail: " + s.Trail);
// The wield was refused (a hand still full when it arrived): after BurstResolveMs, one step at a time.
s.Start("wand", At(0), new[] { (I(Sceptre), Held) }, peaceFirst: true);
var h2 = new Dictionary<int, int> { [I(Acid)] = Melee };
s.SentBurst(s.Blockers(h2), At(0));
h2.Remove(I(Acid));
Check.Eq(s.Next(h2, HandSwapSequence.NonCombat, At(2499)).Act, HandSwapSequence.Act.Wait, "inside the burst's wait");
var st = s.Next(h2, HandSwapSequence.NonCombat, At(2500));
Check.True(st.Act == HandSwapSequence.Act.Wield && unchecked((uint)st.Id) == Sceptre, "then the wield again, alone");
Check.True(s.Trail.Contains("burst incomplete"), "and the trail says so: " + s.Trail);
}
private static void BurstFast()
{
try
{
var rig = new Rig(healthPct: 50, putCalls: true);
rig.B.SwapBurst = true;
rig.Run(0, 3000);
Check.Eq(FakeHost.Moves.Count, 0, "no client-gated moves");
Check.True(FakeHost.Puts.Count == 2 && FakeHost.Puts[0].Id == Frost && FakeHost.Puts[1].Id == Acid,
"two raw moves, the off hand first: " + string.Join(", ", FakeHost.Puts.Select(m => $"{m.Id:X8}")));
Check.Eq(FakeHost.Wields.Count, 1, "one wield");
Check.Eq(rig.Sv.RefusedWields, 0, "the wield wasn't refused (the server took peace and both moves first)");
Check.True(rig.Logged("burst 0 ms into the switch"), "logged");
string inHand = FakeHost.Logs.FirstOrDefault(l => l.Contains("wand in hand")) ?? "";
Console.WriteLine($" (simulated burst: {inHand}; first heal {rig.FirstCastMs:0} ms)");
var m = System.Text.RegularExpressions.Regex.Match(inHand, @"in hand (\d+) ms");
Check.True(m.Success && int.Parse(m.Groups[1].Value) <= 150, "the wand in hand within about one round trip: " + inHand);
Check.True(rig.FirstCastMs > 0 && rig.FirstCastMs <= 1000, $"the heal at {rig.FirstCastMs:0} ms");
}
finally { Done(); }
}
private static void BurstWaitsQuiet()
{
try
{
var rig = new Rig(healthPct: 100, putCalls: true);
rig.B.SwapBurst = true;
rig.Run(0, 200); // the plugin has seen the mode (Melee) since 0
FakeHost.CombatModeValue = CombatMode.Missile; // a stance change just happened
rig.Run(225, 400);
rig.V.CurrentHealth = 50; // now a heal is needed, 0.2 s after the change
rig.Run(425, 3000);
Check.Eq(FakeHost.Puts.Count, 0, "no burst inside 1.3 s of a stance change");
Check.True(FakeHost.Moves.Count == 2, "the step route instead");
}
finally { Done(); }
}
private static void RearmBurst()
{
try
{
var rig = new CombatRig(putCalls: true);
rig.C.SwapBurstEnabled = () => true;
Check.True(rig.Run(2000), "the weapons are back: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("weapons back"))));
Check.True(FakeHost.Puts.Count == 1 && FakeHost.Puts[0].Id == Sceptre, "the Sceptre out with the raw move");
Check.Eq(FakeHost.Moves.Count, 0, "no client-gated move");
Check.True(FakeHost.Wields.Count == 2 && FakeHost.Wields[0] == (Acid, (uint)Melee) && FakeHost.Wields[1] == (Frost, (uint)Off),
"both Hand Wraps in the same tick: " + string.Join(", ", FakeHost.Wields.Select(w => $"{w.Id:X8}@{w.Mask:X}")));
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1,2", "peace, then Melee");
Check.True(FakeHost.Logs.Any(l => l.Contains("weapons back burst")), "logged");
Check.True(rig.SimMs <= 200, $"done {rig.SimMs:0} ms in");
Console.WriteLine($" (simulated weapons-back burst: done {rig.SimMs:0} ms in; " + FakeHost.Logs.FirstOrDefault(l => l.Contains("weapons back in hand")) + ")");
Check.Eq(rig.Gate.HeldBy, "", "the gate is free");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
private static void RearmBurstQuietFromBuff()
{
try
{
// Combat's tick didn't run while buffing had it, so its own read of the mode saw the switch to
// Magic only now, at the weapons-back tick. BuffManager's read (every heartbeat) says 5 s ago.
var rig = new CombatRig(putCalls: true);
rig.C.SwapBurstEnabled = () => true;
typeof(CombatManager).GetField("_cmModeChangedAt", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.SetValue(rig.C, RynthClock.Now);
DateTime changed = RynthClock.Now.AddSeconds(-5);
rig.C.LastModeChangeAt = () => changed;
rig.Run(2000);
Check.True(FakeHost.Puts.Count == 1, "the burst went (the mode last changed 5 s ago)");
// Without BuffManager's read, combat's own (late) read holds it: the step route.
var old = new CombatRig(putCalls: true);
old.C.SwapBurstEnabled = () => true;
typeof(CombatManager).GetField("_cmModeChangedAt", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.SetValue(old.C, RynthClock.Now);
old.Run(2000);
Check.Eq(FakeHost.Puts.Count, 0, "no BuffManager read, a change just now: no burst");
Check.Eq(FakeHost.Moves.Count, 1, "the step route instead");
}
finally { ActionPacer.Enabled = false; EquippedState.Clock = null; EquippedState.Invalidate(); }
}
}

View file

@ -47,6 +47,7 @@ internal static class OffhandTests
r.Add("tracker (v87): the main hand and the off hand come from the server's slots", TrackerHands);
r.Add("tracker (v87): not ready yet (-1): the old reads answer", TrackerNotReadyFallsBack);
r.Add("weapons: a two-hander needing untrained Two Handed Combat is never chosen, so the off hand stays", UnmetRequirementNotChosen);
r.Add("weapons: vitae doesn't leave out a weapon whose requirement is the base skill (the Shashqa at 40% vitae)", VitaeAndBaseSkillRequirement);
r.Add("offhand: no Dual Wield skill -> the shield", NoSkillShield);
r.Add("offhand: None -> hands off (a worn shield is never taken off)", NoneHandsOff);
r.Add("offhand: an unlisted shield is never wielded", UnlistedNeverUsed);
@ -601,6 +602,34 @@ internal static class OffhandTests
Check.True(rig.C.ListedCandidates().Any(c => c.Id == unchecked((int)Great)), "after training it: a candidate again, nothing to re-list");
}
// 2026-10-23: at 40% vitae, "Shashqa can't be wielded (needs Two Handed Combat 420, you have 371)",
// though it wields fine. Its requirement is RawSkill (the base skill: no buffs, no vitae), and the
// check read the buffed skill, which vitae lowers.
private static void VitaeAndBaseSkillRequirement()
{
var rig = new Rig();
rig.List(Sword, Great);
FakeHost.Ints[(Great, 158)] = 2; // WieldRequirements: RawSkill
FakeHost.Ints[(Great, 159)] = 41; // Two Handed Combat
FakeHost.Ints[(Great, 160)] = 420;
FakeHost.Skills[(Player, 41)] = (371, 2); // buffed read, with the vitae penalty
FakeHost.SkillLevels[(Player, 41, 1)] = 430; // base
var skills = new CharacterSkills(FakeHost.Create(Player));
skills.SetPlayerId(Player);
Check.Eq(WieldRequirements.Unmet(FakeHost.Create(Player), skills, Great), null, "base 430 meets base 420, whatever vitae does to the buffed 371");
Check.True(rig.C.ListedCandidates().Any(c => c.Id == unchecked((int)Great)), "a candidate");
Check.False(FakeHost.Chat.Any(c => c.Contains("can't be wielded")), "no 'can't be wielded' message: " + string.Join(" | ", FakeHost.Chat));
FakeHost.SkillLevels[(Player, 41, 1)] = 400;
Check.Eq(WieldRequirements.Unmet(FakeHost.Create(Player), skills, Great), "needs base Two Handed Combat 420, you have 400", "a base under the requirement is unmet");
FakeHost.SkillLevels.Remove((Player, 41, 1));
Check.Eq(WieldRequirements.Unmet(FakeHost.Create(Player), skills, Great), null, "the base can't be read: not known (the server's answer decides)");
// A Skill requirement (the buffed skill) is lowered by vitae on the server too: unmet.
FakeHost.Ints[(Great, 158)] = 1;
Check.Eq(WieldRequirements.Unmet(FakeHost.Create(Player), skills, Great), "needs Two Handed Combat 420, you have 371", "a buffed-skill requirement reads the buffed skill");
}
private static void TrackerNotReadyFallsBack()
{
var rig = new Rig(tracker: true);

View file

@ -54,6 +54,7 @@ internal static class WeaponTests
r.Add("slayer: read through the host (int 166, float 138, monster int 2), cached by wcid", SlayerFromHost);
r.Add("refusal: a refused stance change in combat's equip pass sets no backoff and starts no stuck clock", StanceRefusedKeepsBackoff);
r.Add("weapon choice: an unlisted wand is never picked (Damage tab, learned, pack, name)", UnlistedNeverPicked);
r.Add("weapon choice: the Monsters rule's weapon is used (R-20261022-193411-fb72), below this monster's Damage tab pick; the Default row's like the Damage tab default", MonsterRuleWeapon);
r.Add("Items list: a listed item no longer carried is reported missing (pack, hand, unknown)", MissingFromPack);
r.Add("weapon choice: a listed weapon someone else now has (sold) is skipped, even as this monster's Damage tab pick", SoldWeaponSkipped);
r.Add("weapon swap: one in flight, confirmed, retry cap, then what's in hand", SwapOneInFlight);
@ -880,6 +881,110 @@ internal static class WeaponTests
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), CombatMode.Magic.ToString(), "accepted: the request goes out");
Check.True((DateTime)last.GetValue(rig.C)! != DateTime.MinValue, "and only now lastStanceAttempt is stamped");
}
/// <summary>
/// Problem report R-20261022-193411-fb72 (2026-10-22): "ignoring monster rules, specifically
/// which weapon is set for the mob type". The rule's WeaponId was imported and shown but never
/// read; the weakness picked the weapon ("src=weak to Cold"). Ethereal Wisp's weakness picks the
/// Lightning wand; the rule says the fire wand. Each step uses a new rule object, so PlanFor's
/// cache (keyed on the rule by reference) doesn't hand back the previous answer.
/// </summary>
private static void MonsterRuleWeapon()
{
var rig = new Rig(1535, "Ethereal Wisp");
rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" });
rig.S.EnsureDefaultRule();
var defRow = rig.S.MonsterRules[0];
MonsterRule Own(uint weapon) => new() { Name = "Ethereal", WeaponId = unchecked((int)weapon) };
var auto = rig.C.PlanFor(rig.Target, Own(0));
Check.Eq(unchecked((uint)auto.WeaponId), ListedWand, "no weapon on the rule: the weakness picks the Lightning wand");
var p = rig.C.PlanFor(rig.Target, Own(FireWand));
Check.Eq(unchecked((uint)p.WeaponId), FireWand, "the rule's weapon, not the weakness pick");
Check.Eq(p.Source, "Monsters rule weapon", "source");
Check.Eq(p.Element, "Fire", "it casts its own element");
// This monster's own Damage tab pick beats the rule's weapon.
rig.Store.SetManualWeapon(1535, ListedWand);
p = rig.C.PlanFor(rig.Target, Own(FireWand));
Check.Eq(unchecked((uint)p.WeaponId), ListedWand, "the Damage tab pick for this monster wins over the rule's");
Check.Eq(p.Source, "Damage tab", "source");
rig.Store.SetManualWeapon(1535, 0);
// The rule's weapon beats the Damage tab DEFAULT row's.
rig.Store.SetDefaultWeapon(ListedWand);
p = rig.C.PlanFor(rig.Target, Own(FireWand));
Check.Eq(unchecked((uint)p.WeaponId), FireWand, "the rule's weapon wins over the Damage tab default");
p = rig.C.PlanFor(rig.Target, Own(0));
Check.Eq(p.Source, "Damage tab default", "no weapon on the rule: the Damage tab default");
// The Monsters Default row's weapon comes after the Damage tab default.
defRow.WeaponId = unchecked((int)FireWand);
p = rig.C.PlanFor(rig.Target, defRow);
Check.Eq(unchecked((uint)p.WeaponId), ListedWand, "Default row matched: the Damage tab default beats its weapon");
Check.Eq(p.Source, "Damage tab default", "source");
rig.Store.SetDefaultWeapon(0);
p = rig.C.PlanFor(rig.Target, Own(0));
Check.Eq(unchecked((uint)p.WeaponId), FireWand, "no Damage tab weapons: the Monsters Default row's weapon");
Check.Eq(p.Source, "Monsters Default weapon", "source");
// A slayer beats the Default row's weapon (a DEFAULT pick, step 3), not the rule's own (step 1).
FakeHost.Ints[(ListedWand, 166)] = Olthoi;
var olthoi = new WorldObject(unchecked((int)Monster) + 7, "Ethereal Wisp", AcObjectClass.Monster);
FakeHost.Wcids[Monster + 7] = 990007;
FakeHost.Ints[(Monster + 7, 2)] = Olthoi;
p = rig.C.PlanFor(olthoi, defRow);
Check.Eq(unchecked((uint)p.WeaponId), ListedWand, "the Default row's fire wand loses to an Olthoi slayer");
Check.True(p.Source.StartsWith("slayer"), "source: " + p.Source);
p = rig.C.PlanFor(olthoi, Own(FireWand));
Check.Eq(unchecked((uint)p.WeaponId), FireWand, "the rule's own fire wand beats the slayer, like a Damage tab pick");
FakeHost.Ints.Remove((ListedWand, 166));
defRow.WeaponId = 0;
// The monster's wcid isn't known: the rule's weapon still applies.
var noWcid = new WorldObject(unchecked((int)Monster) + 9, "Ethereal Wisp", AcObjectClass.Monster);
p = rig.C.PlanFor(noWcid, Own(FireWand));
Check.Eq(unchecked((uint)p.WeaponId), FireWand, "wcid unknown: the rule's weapon");
// Not in the Items list: still used, the Monsters tab pick is the player's (owner, 2026-10-22).
rig.S.ItemRules.RemoveAll(r => r.Id == unchecked((int)FireWand));
p = rig.C.PlanFor(rig.Target, Own(FireWand));
Check.Eq(unchecked((uint)p.WeaponId), FireWand, "an unlisted rule weapon is still used");
Check.Eq(p.Source, "Monsters rule weapon", "source");
Check.Eq(p.Element, "Fire", "it casts its own element (read from the weapon, not the list)");
Check.True(FakeHost.Logs.Any(l => l.Contains("Monsters rule 'Ethereal' weapon") && l.Contains("isn't in the Items list") && l.Contains("using it")),
"logged once: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("EquipDiag")).Take(6)));
defRow.WeaponId = unchecked((int)FireWand);
p = rig.C.PlanFor(rig.Target, Own(0));
Check.Eq(unchecked((uint)p.WeaponId), FireWand, "the Default row's unlisted weapon too");
defRow.WeaponId = 0;
// ...but a Damage tab pick still must be listed.
rig.Store.SetManualWeapon(1535, FireWand);
p = rig.C.PlanFor(rig.Target, Own(0));
Check.Eq(unchecked((uint)p.WeaponId), ListedWand, "an unlisted Damage tab pick is still skipped");
rig.Store.SetManualWeapon(1535, 0);
// A rule weapon the client doesn't know (not carried, never seen): skipped, the weakness pick.
const uint Unknown = 0x6000006F;
p = rig.C.PlanFor(rig.Target, Own(Unknown));
Check.Eq(unchecked((uint)p.WeaponId), ListedWand, "an unknown rule weapon is skipped: the weakness pick");
rig.S.ItemRules.Add(new() { Id = unchecked((int)FireWand), Name = "Fire Wand", Element = "Fire", ElementSource = "icon" });
// Through combat's equip pass: the rule matched by name drives the wield.
rig.S.MonsterRules.Add(Own(FireWand));
rig.C.InHandOverride = () => unchecked((int)ListedWand); // the weakness pick is in hand
var equip = typeof(CombatManager).GetMethod("EquipWeaponAndSetStance", BindingFlags.Instance | BindingFlags.NonPublic)!;
equip.Invoke(rig.C, new object[] { rig.Target, "Auto" });
Check.Eq(FakeHost.Uses.FirstOrDefault(), FireWand, "combat wields the rule's fire wand");
// The same with the fire wand not in the Items list (a fresh rig: the first wield is in flight).
var bare = new Rig(1535, "Ethereal Wisp");
bare.S.EnsureDefaultRule();
bare.S.MonsterRules.Add(Own(FireWand));
bare.C.InHandOverride = () => unchecked((int)ListedWand);
equip.Invoke(bare.C, new object[] { bare.Target, "Auto" });
Check.Eq(FakeHost.Uses.FirstOrDefault(), FireWand, "combat wields the rule's unlisted fire wand");
}
private static void UnlistedNeverPicked()
{
var rig = new Rig(1535, "Ethereal Wisp");

View file

@ -0,0 +1,603 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using RynthCore.Plugin.RynthDefective;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthDefective.Tests
{
internal static partial class Program
{
// ── Kinds ───────────────────────────────────────────────────────────
private static void KindsClassify()
{
Eq(ItemKinds.Classify(Kit(1)), ItemKind.Kit, "a healer bit is a kit");
var noBits = Item(2, "Excellent Stamina Kit");
Eq(ItemKinds.Classify(noBits), ItemKind.Kit, "no bitfield read: a name ending in Kit");
var kitNamedThing = Item(3, "Kit Bag"); kitNamedThing.Bitfield = 0x8000;
Eq(ItemKinds.Classify(kitNamedThing), ItemKind.Other, "a bitfield without the healer bit is not a kit");
Eq(ItemKinds.Classify(Potion(4)), ItemKind.Other, "a potion");
Eq(ItemKinds.Classify(Item(5, "Scroll of Creature Enchantment Mastery")), ItemKind.Other, "a scroll");
Eq(ItemKinds.Classify(Melee(10, "Sword")), ItemKind.Melee, "melee");
Eq(ItemKinds.Classify(Bow(11)), ItemKind.Missile, "missile");
Eq(ItemKinds.Classify(Arrows(12)), ItemKind.Ammo, "arrows are ammunition, not a missile weapon");
Eq(ItemKinds.Classify(Wand(13, "Wand", 0x10)), ItemKind.WarWand, "a fire wand is war magic");
Eq(ItemKinds.Classify(Wand(14, "Wand", 0x400)), ItemKind.VoidWand, "a nether damage type is void magic");
var glowing = Wand(15, "Staff", 0); glowing.UiEffects = 0x1000;
Eq(ItemKinds.Classify(glowing), ItemKind.VoidWand, "no damage type read: the icon's nether glow");
var fireGlow = Wand(16, "Staff of Flame", 0); fireGlow.UiEffects = 0x0020;
Eq(ItemKinds.Classify(fireGlow), ItemKind.WarWand, "no damage type: a fire glow is war");
var named = Wand(17, "Nether Orb", 0);
Eq(ItemKinds.Classify(named), ItemKind.VoidWand, "nothing known but the name: Nether");
var plain = Wand(18, "Wand", 0);
Eq(ItemKinds.Classify(plain), ItemKind.WarWand, "an unknown caster is war magic");
var nameOnly = Item(19, "Crystal Scepter"); nameOnly.ValidLocations = 0x01000000;
Eq(ItemKinds.Classify(nameOnly), ItemKind.WarWand, "no item type read: the name says wand");
Eq(ItemKinds.Classify(Shield(20)), ItemKind.Shield, "shield by combat use");
var oldShield = Item(21, "Buckler"); oldShield.ItemType = ItemKinds.TypeArmor; oldShield.ValidLocations = ItemKinds.ShieldSlot;
Eq(ItemKinds.Classify(oldShield), ItemKind.Shield, "shield by slot when it is not a weapon");
var helm = Item(22, "Helm"); helm.ItemType = ItemKinds.TypeArmor; helm.ValidLocations = 0x1;
Eq(ItemKinds.Classify(helm), ItemKind.Armor, "armor");
var ring = Item(23, "Ring"); ring.ItemType = ItemKinds.TypeJewelry; ring.ValidLocations = 0x30000;
Eq(ItemKinds.Classify(ring), ItemKind.Jewelry, "jewelry");
var clothes = Item(24, "Shirt"); clothes.ItemType = ItemKinds.TypeClothing; clothes.ValidLocations = 0x2;
Eq(ItemKinds.Classify(clothes), ItemKind.Armor, "clothing is worn like armor");
Eq(ItemKinds.Element(Wand(30, "Wand", 0x08)), "Cold", "damage type cold");
Eq(ItemKinds.Element(Wand(31, "Wand", 0x20)), "Acid", "damage type acid");
Eq(ItemKinds.Element(plain), "", "no element known");
Eq(ItemNames.Full("Wand", 63), "Silver Wand", "material in front");
Eq(ItemNames.Full("Silver Wand", 63), "Silver Wand", "not twice");
Eq(ItemNames.Full("Wand", 0), "Wand", "no material");
Eq(ItemNames.Full("Wand", 999), "Wand", "an unknown material id");
}
private static void KindsActions()
{
Eq(ItemKinds.DefaultAction(ItemKind.Kit), UseAction.UseOnSelf, "kits go on yourself");
Eq(ItemKinds.DefaultAction(ItemKind.Other), UseAction.Use, "potions are used");
Eq(ItemKinds.DefaultAction(ItemKind.Melee), UseAction.Equip, "weapons are wielded");
Eq(ItemKinds.DefaultAction(ItemKind.Armor), UseAction.Equip, "armor is worn");
Eq(UseModes.ActionFor(UseMode.OnSelected, ItemKind.Other), UseAction.UseOnSelected, "a slot can override");
Eq(UseModes.ActionFor(UseMode.Use, ItemKind.Kit), UseAction.Use, "a kit used by itself if asked");
Eq(UseModes.ActionFor(UseMode.Auto, ItemKind.Kit), UseAction.UseOnSelf, "automatic follows the kind");
Eq(ItemKinds.GroupOf(ItemKind.WarWand), WeaponGroup.WarMagic, "war group");
Check(ItemKinds.GroupOf(ItemKind.Kit) == null && ItemKinds.GroupOf(ItemKind.Armor) == null, "kits and armor are not in the picker");
Check(ItemKinds.NeedsAmmo(Bow(1)) && !ItemKinds.NeedsAmmo(Item(2, "Dart", 50, 250)), "a launcher needs ammunition, a thrown stack does not");
}
// ── Matching ────────────────────────────────────────────────────────
private static void MatchRebind()
{
var r = ItemRef.From(Kit(100));
var items = new List<CarriedItem> { Kit(100), Kit(101) };
CarriedItem? f = ItemMatcher.Find(r, items, out bool rebound);
Check(f?.Id == 100 && !rebound, "the exact object while it is carried");
items.RemoveAt(0);
f = ItemMatcher.Find(r, items, out rebound);
Check(f?.Id == 101 && rebound, "gone: another kit of the same name, and it says so");
items = new List<CarriedItem> { Kit(102, "Gifted Healing Kit") };
Check(ItemMatcher.Find(r, items, out _) == null, "a different name is a different item");
Check(ItemMatcher.Find(new ItemRef(), items, out _) == null, "a blank reference finds nothing");
// Name case, wcid and material.
items = new List<CarriedItem> { Kit(103, "PEERLESS HEALING KIT") };
Check(ItemMatcher.Find(r, items, out _)?.Id == 103, "the name matches in any case");
items = new List<CarriedItem> { Kit(104, wcid: 999) };
Check(ItemMatcher.Find(r, items, out _) == null, "the same name with another wcid is not the same item");
var wandRef = ItemRef.From(Wand(200, "Wand", 0x10, material: 63)); // Silver Wand
items = new List<CarriedItem> { Wand(201, "Wand", 0x10, material: 60), Wand(202, "Wand", 0x10, material: 63) };
Check(ItemMatcher.Find(wandRef, items, out _)?.Id == 202, "another material is another wand: the silver one");
var unknownMaterial = new ItemRef { Name = "Wand" };
Check(ItemMatcher.Find(unknownMaterial, items, out _)?.Id == 201, "no material known: any wand of that name (the first)");
// An id reused by a different item must not count as the same item.
items = new List<CarriedItem> { Item(100, "Health Potion") };
Check(ItemMatcher.Find(r, items, out _) == null, "an object id reused for something else is not the kit");
// Not wielded before wielded, the smaller stack first, then the lower id.
var potRef = ItemRef.From(Potion(1));
items = new List<CarriedItem> { Potion(7, stack: 20), Potion(8, stack: 3), Potion(9, stack: 3) };
Check(ItemMatcher.Find(potRef, items, out _)?.Id == 8, "the smaller stack, then the lower id");
var swordRef = ItemRef.From(Melee(50, "Sword"));
items = new List<CarriedItem> { Melee(51, "Sword", wielded: true), Melee(52, "Sword") };
Check(ItemMatcher.Find(swordRef, items, out _)?.Id == 52, "not the one already in hand");
}
private static void MatchCounts()
{
var potRef = ItemRef.From(Potion(1));
var items = new List<CarriedItem> { Potion(7, stack: 20), Potion(8, stack: 3), Kit(9) };
SlotStatus s = ItemMatcher.Status(potRef, items);
Check(s.Item?.Id == 8 && s.Count == 23 && s.Uses == 0, "stacks added up");
Eq(RynthCore.Plugin.RynthDefective.Views.SlotText.Count(s, out _), "x23", "a stack's label");
var kitRef = ItemRef.From(Kit(9));
items = new List<CarriedItem> { Kit(9, uses: 10), Kit(10, uses: 28) };
s = ItemMatcher.Status(kitRef, items);
Check(s.Item?.Id == 9 && s.Count == 2 && s.Uses == 38, "kits: uses added up over both");
Eq(RynthCore.Plugin.RynthDefective.Views.SlotText.Count(s, out _), "38", "uses left are the label");
s = ItemMatcher.Status(kitRef, new List<CarriedItem> { Potion(2) });
Check(s.Missing && s.Count == 0, "nothing carried: missing");
Eq(RynthCore.Plugin.RynthDefective.Views.SlotText.Count(s, out uint color), "none", "missing says none");
Check(color == RynthCore.Plugin.RynthDefective.Views.SlotText.Missing, "in red");
var sword = Melee(60, "Sword");
s = ItemMatcher.Status(ItemRef.From(sword), new List<CarriedItem> { sword });
Eq(RynthCore.Plugin.RynthDefective.Views.SlotText.Count(s, out _), "", "one weapon: no label");
sword.WieldedLocation = 0x00100000;
s = ItemMatcher.Status(ItemRef.From(sword), new List<CarriedItem> { sword });
Eq(RynthCore.Plugin.RynthDefective.Views.SlotText.Count(s, out color), "in hand", "a wielded weapon");
Check(color == RynthCore.Plugin.RynthDefective.Views.SlotText.InHand, "in green");
var dart = Item(61, "Dart", 1, 250);
s = ItemMatcher.Status(ItemRef.From(dart), new List<CarriedItem> { dart });
Eq(RynthCore.Plugin.RynthDefective.Views.SlotText.Count(s, out _), "x1", "the last of a stackable kind shows x1");
}
private static void MatchMaintain()
{
var slotItem = ItemRef.From(Kit(100));
Check(!ItemMatcher.Maintain(slotItem, new List<CarriedItem> { Kit(100) }), "nothing changed: no save");
// The kit is used up; another is carried.
var other = Kit(101); other.Icon = 0x06009999;
Check(ItemMatcher.Maintain(slotItem, new List<CarriedItem> { other }), "followed to the other kit: a save is due");
Check(slotItem.Id == 101 && slotItem.Icon == 0x06009999, "id and picture follow");
Eq(slotItem.Name, "Peerless Healing Kit", "the name stays");
// Missing: nothing is touched.
Check(!ItemMatcher.Maintain(slotItem, new List<CarriedItem> { Potion(5) }) && slotItem.Id == 101, "nothing carried: the slot keeps its identity");
// Through the session: an inventory that is not loaded yet (empty) changes nothing.
var session = new DefSession(new HotkeyLookup(() => Path.Combine(_temp, "none.txt")));
session.Data.Slots[0].Item = ItemRef.From(Kit(100));
session.Data.Favourites.Add(ItemRef.From(Wand(300, "Wand", 0x10, 63)));
session.Data.Recent.Add(ItemRef.From(Melee(301, "Sword")));
Check(!session.Maintain(new List<CarriedItem>()), "an empty inventory is not trusted");
var inv = new List<CarriedItem> { Kit(110), Wand(310, "Wand", 0x10, 63), Melee(311, "Sword") };
Check(session.Maintain(inv), "slots, favourites and recent all follow");
Check(session.Data.Slots[0].Item!.Id == 110 && session.Data.Favourites[0].Id == 310 && session.Data.Recent[0].Id == 311, "their new ids");
}
private static void MatchByName()
{
var items = new List<CarriedItem>
{
Kit(1, "Peerless Healing Kit"), Kit(2, "Gifted Healing Kit"), Kit(3, "Lesser Stamina Kit"), Kit(4, "Greater Stamina Kit"),
Wand(5, "Wand", 0x10, 63), Wand(6, "Wand", 0x10, 60), Potion(7),
};
Eq(ItemMatcher.FindByName("Peerless Healing Kit", items)?.Id, 1u, "the full name");
Eq(ItemMatcher.FindByName("gifted healing kit", items)?.Id, 2u, "any case");
Eq(ItemMatcher.FindByName("Silver Wand", items)?.Id, 5u, "with the material");
Eq(ItemMatcher.FindByName("Wand", items)?.Id, 5u, "the plain name: the first of them (the lower id)");
Eq(ItemMatcher.FindByName("Stamina Kit", items)?.Id, 3u, "words that are in several: the first");
Eq(ItemMatcher.FindByName("greater stamina", items)?.Id, 4u, "words in any part of the name");
Eq(ItemMatcher.FindByName("Health", items)?.Id, 7u, "a start of a name");
Check(ItemMatcher.FindByName("Elixir", items) == null, "nothing by that name");
Check(ItemMatcher.FindByName(" ", items) == null, "blank finds nothing");
}
// ── Picker ──────────────────────────────────────────────────────────
private static List<CarriedItem> Armory()
{
return new List<CarriedItem>
{
Melee(1, "Sword"), Melee(2, "Axe", material: 62), Melee(3, "Mace", wielded: true),
Bow(4, "Yumi"), Bow(5, "Shouyumi"), Arrows(6),
Wand(7, "Wand", 0x10, material: 63), Wand(8, "Staff", 0x08), Wand(9, "Orb", 0x400), Wand(10, "Wand", 0x400, material: 60),
Shield(11), Kit(12), Potion(13),
};
}
private static void PickerGroups()
{
var items = Armory();
PickerModel m = WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "", KindFilter.All);
Eq(m.Total, 11, "weapons, wands, shields and ammunition counted; kits and potions not");
Eq(m.Shown, 11, "all shown");
Eq(string.Join(",", m.Groups.Select(g => g.Group)), "Melee,Missile,WarMagic,VoidMagic,Shield,Ammo", "groups in order");
Eq(string.Join(",", m.Groups[0].Rows.Select(r => r.Item.FullName)), "Mace,Pyreal Axe,Sword", "A-Z by full name");
Check(m.Groups[0].Rows.First(r => r.Item.Name == "Mace").InHand, "the weapon in hand is marked");
Eq(string.Join(",", m.Groups[2].Rows.Select(r => r.Element)), "Fire,Cold", "war wands with their elements (Silver Wand = fire, Staff = cold)");
Eq(string.Join(",", m.Groups[3].Rows.Select(r => r.Item.FullName)), "Gold Wand,Orb", "void wands");
Check(m.Favourites.Count == 0 && m.Recent.Count == 0, "no shortcuts yet");
m = WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "wand", KindFilter.All);
Check(m.Shown == 2 && m.Groups.Count == 2, "search: 'wand' finds the silver and the gold wand, in two groups");
m = WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "silver wand", KindFilter.All);
Check(m.Shown == 1 && m.Groups[0].Rows[0].Item.Id == 7, "every word must match: 'silver wand'");
m = WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "fire", KindFilter.All);
Check(m.Shown == 1 && m.Groups[0].Rows[0].Item.Id == 7, "search finds the element");
m = WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "void", KindFilter.All);
Check(m.Shown == 2, "search finds the kind's label");
m = WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "zzz", KindFilter.All);
Check(m.Shown == 0 && m.Groups.Count == 0 && m.Total == 11, "nothing matches");
Eq(WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "", KindFilter.Melee).Shown, 3, "filter: melee");
m = WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "", KindFilter.Missile);
Eq(string.Join(",", m.Groups.Select(g => g.Group)), "Missile,Ammo", "filter: missile keeps the arrows");
Eq(WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "", KindFilter.War).Shown, 2, "filter: war");
Eq(WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "", KindFilter.Void).Shown, 2, "filter: void");
Eq(WeaponPicker.Build(items, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "axe", KindFilter.Void).Shown, 0, "search and filter together");
// 60 weapons: still one list, sorted.
var many = new List<CarriedItem>();
for (uint i = 0; i < 60; i++) many.Add(Melee(1000 + i, "Blade " + (59 - i).ToString("00")));
m = WeaponPicker.Build(many, Array.Empty<ItemRef>(), Array.Empty<ItemRef>(), "", KindFilter.All);
Check(m.Groups.Count == 1 && m.Groups[0].Rows.Count == 60 && m.Groups[0].Rows[0].Item.Name == "Blade 00" && m.Groups[0].Rows[59].Item.Name == "Blade 59", "60 weapons sorted");
}
private static void PickerShortcuts()
{
var items = Armory();
var favs = new List<ItemRef> { ItemRef.From(items[9]), ItemRef.From(items[0]) }; // Gold Wand (void), Sword
var recent = new List<ItemRef> { ItemRef.From(items[3]), ItemRef.From(items[0]), new ItemRef { Id = 77, Name = "Sold Sword" } };
PickerModel m = WeaponPicker.Build(items, favs, recent, "", KindFilter.All);
Eq(string.Join(",", m.Favourites.Select(r => r.Item.FullName)), "Gold Wand,Sword", "favourites in the order the player made them");
Eq(string.Join(",", m.Recent.Select(r => r.Item.FullName)), "Yumi,Sword", "recent newest first; one that is gone is left out");
Check(m.Favourites[0].Favourite && m.Groups.SelectMany(g => g.Rows).First(r => r.Item.Name == "Sword").Favourite, "favourites are marked in their group too");
Check(m.Groups.SelectMany(g => g.Rows).Count() == 11, "the groups still list everything");
// A favourite follows its identity when the object changed.
var swapped = new List<CarriedItem> { Melee(900, "Sword") };
m = WeaponPicker.Build(swapped, favs, Array.Empty<ItemRef>(), "", KindFilter.All);
Check(m.Favourites.Count == 1 && m.Favourites[0].Item.Id == 900, "a favourite finds its replacement by name");
// The search narrows the shortcuts too.
m = WeaponPicker.Build(items, favs, recent, "yumi", KindFilter.All);
Check(m.Favourites.Count == 0 && m.Recent.Count == 1, "search narrows favourites and recent");
// Data: favourites toggle, recent order and limit.
var d = new DefData();
ItemRef a = ItemRef.From(items[0]);
Check(d.ToggleFavourite(a) && d.Favourites.Count == 1, "added");
Check(!d.ToggleFavourite(ItemRef.From(items[0])) && d.Favourites.Count == 0, "the same weapon again takes it out");
for (uint i = 0; i < 12; i++) d.NoteRecent(new ItemRef { Id = i + 1, Name = "W" + i });
Check(d.Recent.Count == DefData.MaxRecent && d.Recent[0].Name == "W11", "recent is capped, newest first");
d.NoteRecent(new ItemRef { Id = 10, Name = "W9" });
Check(d.Recent.Count == DefData.MaxRecent && d.Recent[0].Name == "W9" && d.Recent.Count(r => r.Name == "W9") == 1, "wielding it again moves it up");
}
private static void PackLists()
{
var items = new List<CarriedItem>
{
Potion(1, "Health Potion", 5), Potion(2, "Health Potion", 3), Potion(3, "Mana Potion", 10),
Kit(4), Kit(5), Melee(6, "Sword", wielded: true), Melee(7, "Sword"),
};
List<PackChoice> list = PackList.Build(items, "", 40, out int total);
Eq(total, 4, "kinds: health potion, mana potion, kit, sword");
Eq(string.Join(",", list.Select(c => c.Item.Name + "x" + c.Count)), "Health Potionx8,Mana Potionx10,Peerless Healing Kitx2,Swordx2", "A-Z with the stacks added");
Check(list.First(c => c.Item.Name == "Sword").Item.Id == 7, "the representative is the one not in hand");
Check(list.First(c => c.Item.Name == "Health Potion").Item.Id == 2, "and the smaller stack");
list = PackList.Build(items, "potion", 40, out total);
Check(total == 2 && list.Count == 2, "search");
list = PackList.Build(items, "", 2, out total);
Check(list.Count == 2 && total == 4, "capped, with the real total");
}
// ── Commands ────────────────────────────────────────────────────────
private static void Commands()
{
Eq(DefCommandParser.Parse("").Verb, DefVerb.Toggle, "blank toggles the bar");
Eq(DefCommandParser.Parse("help").Verb, DefVerb.Help, "help");
DefCommand c = DefCommandParser.Parse("use 3");
Check(c.Verb == DefVerb.Use && c.Slot == 3 && c.Text == "", "use 3");
c = DefCommandParser.Parse("USE Peerless Healing Kit");
Check(c.Verb == DefVerb.Use && c.Slot == 0 && c.Text == "Peerless Healing Kit", "use by name (case of the verb ignored, the name kept)");
c = DefCommandParser.Parse("wield Silver Wand ");
Check(c.Verb == DefVerb.Use && c.Text == "Silver Wand", "wield is use");
c = DefCommandParser.Parse("use 99");
Check(c.Verb == DefVerb.Use && c.Slot == 0 && c.Text == "99", "a number past the slots is a name (nothing will match)");
Eq(DefCommandParser.Parse("use").Verb, DefVerb.Error, "use needs something");
c = DefCommandParser.Parse("Stamina Kit");
Check(c.Verb == DefVerb.Use && c.Text == "Stamina Kit", "/rdef <name> is use");
c = DefCommandParser.Parse("set 2");
Check(c.Verb == DefVerb.Set && c.Slot == 2 && c.Text == "", "set 2: from the selected item");
c = DefCommandParser.Parse("set 2 Health Potion");
Check(c.Verb == DefVerb.Set && c.Slot == 2 && c.Text == "Health Potion", "set 2 by name");
Eq(DefCommandParser.Parse("set").Verb, DefVerb.Error, "set needs a slot");
Eq(DefCommandParser.Parse("set x").Verb, DefVerb.Error, "set needs a number");
Eq(DefCommandParser.Parse("set 0").Verb, DefVerb.Error, "slots start at 1");
c = DefCommandParser.Parse("clear 4");
Check(c.Verb == DefVerb.Clear && c.Slot == 4, "clear");
Eq(DefCommandParser.Parse("clear").Verb, DefVerb.Error, "clear needs a slot");
c = DefCommandParser.Parse("bind 3 Ctrl+F9");
Check(c.Verb == DefVerb.Bind && c.Slot == 3 && c.Text == "Ctrl+F9", "bind");
Eq(DefCommandParser.Parse("bind 3").Verb, DefVerb.Error, "bind needs a key");
c = DefCommandParser.Parse("unbind 3");
Check(c.Verb == DefVerb.Unbind && c.Slot == 3, "unbind");
c = DefCommandParser.Parse("weapons fire wand");
Check(c.Verb == DefVerb.Weapons && c.Text == "fire wand", "weapons with a search");
Eq(DefCommandParser.Parse("weapons").Verb, DefVerb.Weapons, "weapons");
Eq(DefCommandParser.Parse("fav").Verb, DefVerb.Favourite, "fav");
c = DefCommandParser.Parse("slots 12");
Check(c.Verb == DefVerb.Slots && c.Slot == 12, "slots");
Eq(DefCommandParser.Parse("slots 99").Verb, DefVerb.Error, "slots in range");
Eq(DefCommandParser.Parse("list").Verb, DefVerb.List, "list");
Eq(DefCommandParser.Parse("status").Verb, DefVerb.Status, "status");
Eq(DefCommandParser.UseCommand(3), "/rdef use 3", "the command a hotkey runs for slot 3");
}
// ── Store ───────────────────────────────────────────────────────────
private static void StoreRoundTrip()
{
var st = new DefStore(Path.Combine(_temp, "store"));
var d = new DefData();
d.Settings.SlotCount = 12;
d.Settings.SlotsPerRow = 6;
d.Settings.ButtonSize = 44;
d.Settings.PickerIconSize = 28;
d.Settings.ShowIcons = false;
d.Settings.ShowCounts = false;
d.Settings.PreferredKind = KindFilter.War;
d.Settings.SwapWhileBotRuns = true;
d.Settings.BarOpen = true;
d.Settings.PickerOpen = true;
var kit = Kit(0x7000_0001u);
kit.Underlay = 0x06000FFF; kit.Overlay = 0x06000EEE;
d.Slots[0].Item = ItemRef.From(kit);
d.Slots[0].Mode = UseMode.OnSelf;
d.Slots[5].Item = ItemRef.From(Wand(0x7000_0002u, "Wand", 0x10, 63));
d.Slots[23].Item = ItemRef.From(Potion(0x7000_0003u));
d.Favourites.Add(ItemRef.From(Melee(5, "Sword")));
d.Recent.Add(ItemRef.From(Bow(6)));
Check(st.Save("Aelrynth", "Drak/kon", d) == null, "saved");
string path = st.PathFor("Aelrynth", "Drak/kon");
Check(File.Exists(path) && Path.GetFileName(path) == "Aelrynth_Drak_kon.json", "the file name is safe: " + path);
DefData r = st.Load("Aelrynth", "Drak/kon", out string? problem);
Check(problem == null, "no problem");
DefSettings s = r.Settings;
Check(s.SlotCount == 12 && s.SlotsPerRow == 6 && s.ButtonSize == 44 && s.PickerIconSize == 28, "sizes");
Check(!s.ShowIcons && !s.ShowCounts && s.SwapWhileBotRuns && s.BarOpen && s.PickerOpen && s.PreferredKind == KindFilter.War, "switches");
Check(r.Slots.Count == DefSettings.SlotsMax, "all 24 slots");
ItemRef a = r.Slots[0].Item!;
Check(a.Id == 0x7000_0001u && a.Name == "Peerless Healing Kit" && a.Wcid == 628 && a.Icon == 0x06001234 && a.Underlay == 0x06000FFF && a.Overlay == 0x06000EEE, "a slot's item with its identity and picture");
Check(r.Slots[0].Mode == UseMode.OnSelf && r.Slots[1].Item == null && r.Slots[1].Mode == UseMode.Auto, "modes and empty slots");
Check(r.Slots[5].Item!.Material == 63 && r.Slots[5].Item!.FullName == "Silver Wand", "material kept");
Check(r.Slots[23].Item!.Name == "Health Potion", "the last slot");
Check(r.Favourites.Count == 1 && r.Favourites[0].Name == "Sword" && r.Recent.Count == 1 && r.Recent[0].Name == "Yumi", "favourites and recent");
Check(!Directory.GetFiles(Path.GetDirectoryName(path)!, "*.tmp").Any(), "no temp file left");
string again = DefStore.ToJson(r);
Eq(again, DefStore.ToJson(d), "writing what was read gives the same file");
DefData fresh = st.Load("Aelrynth", "Nobody", out problem);
Check(problem == null && fresh.Slots.All(x => x.Empty) && fresh.Settings.SlotCount == 8, "a new character gets defaults");
}
private static void StoreOddFiles()
{
var st = new DefStore(Path.Combine(_temp, "odd"));
string own = st.PathFor("S", "A");
Directory.CreateDirectory(Path.GetDirectoryName(own)!);
File.WriteAllText(own, "not json at all");
DefData d = st.Load("S", "A", out string? problem);
Check(problem != null && d.Slots.All(x => x.Empty), "a broken file reads as defaults and says so");
File.WriteAllText(own, "[1,2,3]");
st.Load("S", "A", out problem);
Check(problem != null, "not an object");
File.WriteAllText(own, "{}");
d = st.Load("S", "A", out problem);
Check(problem == null && d.Settings.SlotCount == 8 && d.Slots.Count == 24, "{} = defaults");
File.WriteAllText(own, "{\"settings\":{\"slotCount\":99,\"slotsPerRow\":0,\"buttonSize\":1000,\"pickerIconSize\":-5,\"preferredKind\":42,\"showIcons\":\"yes\"},"
+ "\"slots\":[7,{\"item\":{\"id\":5.0,\"name\":\"Kit\"},\"mode\":9},{\"item\":{\"id\":1}},{\"item\":{\"name\":\" \"}},{\"item\":\"x\"},null],"
+ "\"favourites\":[\"x\",{\"name\":\"Sword\"},{\"id\":3}],\"recent\":5}");
d = st.Load("S", "A", out problem);
Check(problem == null, "odd values are not a problem");
Check(d.Settings.SlotCount == DefSettings.SlotsMax && d.Settings.SlotsPerRow == DefSettings.PerRowMin && d.Settings.ButtonSize == DefSettings.ButtonMax
&& d.Settings.PickerIconSize == DefSettings.PickerIconMin && d.Settings.PreferredKind == KindFilter.All && d.Settings.ShowIcons, "clamped, a string is not a bool");
Check(d.Slots[0].Empty, "a non-object slot is empty");
Check(d.Slots[1].Item?.Name == "Kit" && d.Slots[1].Item!.Id == 5 && d.Slots[1].Mode == UseMode.Auto, "2.0 is 2; an unknown mode is automatic");
Check(d.Slots[2].Empty && d.Slots[3].Empty && d.Slots[4].Empty, "an item with no name can't be found again: empty");
Check(d.Favourites.Count == 1 && d.Favourites[0].Name == "Sword" && d.Recent.Count == 0, "bad favourites are skipped; recent that isn't a list is none");
Eq(d.Slots.Count, DefSettings.SlotsMax, "still 24 slots");
// More slots than the maximum in a file are cut.
var sb = new StringBuilder("{\"slots\":[");
for (int i = 0; i < 40; i++) sb.Append(i > 0 ? "," : "").Append("{\"item\":{\"id\":").Append(i + 1).Append(",\"name\":\"N").Append(i).Append("\"}}");
sb.Append("]}");
File.WriteAllText(own, sb.ToString());
d = st.Load("S", "A", out _);
Check(d.Slots.Count == 24 && d.Slots[23].Item!.Name == "N23", "slots past the 24th are dropped");
Eq(DefStore.SafeFileName("CON"), "_CON", "reserved names");
Eq(DefStore.FileStem("Dream Weave", "Ana:Lee"), "Dream Weave_Ana_Lee", "illegal characters become underscores");
}
// ── Hotkey file ─────────────────────────────────────────────────────
private static void HotkeyFile()
{
string file = Path.Combine(_temp, "hotkeys.txt");
File.WriteAllText(file,
"# RynthCore hotkeys\nenabled=1\ndefaults=1\n"
+ "on\tF6\theal\t\n"
+ "on\tF9\tcommand\t/rdef use 3\n"
+ "off\tF10\tcommand\t/rdef use 4\n"
+ "on\tCtrl+1\tcommand\t/RDEF USE Stamina Kit\n"
+ "on\tF11\tcommand\t/ra start\n"
+ "junk line\n");
var lookup = new HotkeyLookup(() => file);
long t = 0;
Eq(lookup.KeyFor("/rdef use 3", t), "F9", "a slot's key");
Eq(lookup.KeyFor("/rdef use 4", t), "F10 (off)", "a switched-off binding says so");
Eq(lookup.KeyFor("/rdef use stamina kit", t), "Ctrl+1", "a name binding, any case");
Check(lookup.KeyFor("/rdef use 5", t) == null, "no key");
Check(lookup.KeyFor("/ra start", t) == "F11", "any chat command");
Check(lookup.KeyFor("heal", t) == null, "built-in actions are not chat commands");
// A change in the file is seen after the check interval.
File.WriteAllText(file, "on\tF8\tcommand\t/rdef use 5\n");
File.SetLastWriteTimeUtc(file, DateTime.UtcNow.AddMinutes(1));
Eq(lookup.KeyFor("/rdef use 5", t + 100), null, "not looked at again within a second");
Eq(lookup.KeyFor("/rdef use 5", t + 1500), "F8", "the new binding");
Check(lookup.KeyFor("/rdef use 3", t + 1500) == null, "the old one is gone");
// Missing file, then unreadable lines.
var none = new HotkeyLookup(() => Path.Combine(_temp, "missing.txt"));
Check(none.KeyFor("/rdef use 1", 0) == null, "no file: no keys");
Eq(HotkeyLookup.Parse("on\tF1\tcommand\n").Count, 0, "a short line is skipped");
}
// ── Session ─────────────────────────────────────────────────────────
private sealed class Rig
{
public readonly DefSession S;
public readonly List<string> Chat = new();
public int Saves;
public uint Selected;
public List<CarriedItem> Inv = new();
public string HotkeyPath;
public Rig(string name)
{
HotkeyPath = Path.Combine(_temp, "rig-" + name + ".txt");
S = new DefSession(new HotkeyLookup(() => HotkeyPath))
{
LoggedIn = true,
Character = "Test",
};
S.Items = () => Inv;
S.SelectedId = () => Selected;
S.Save = () => Saves++;
S.RunChat = line => { Chat.Add(line); return true; };
}
}
private static void SessionSlots()
{
var rig = new Rig("slots");
rig.Inv = new List<CarriedItem> { Kit(10), Potion(11), Melee(12, "Sword") };
string m = rig.S.SetFromSelected(1);
Check(m.Contains("Select the item") && rig.S.Data.Slots[0].Empty, "nothing selected: told how");
rig.Selected = 999;
m = rig.S.SetFromSelected(1);
Check(m.Contains("isn't in your pack") && rig.S.Data.Slots[0].Empty, "selected but not carried (a monster, a corpse)");
rig.Selected = 10;
m = rig.S.SetFromSelected(1);
Check(rig.S.Data.Slots[0].Item?.Id == 10 && rig.Saves == 1, "set from the selected kit, saved");
Check(m.Contains("Peerless Healing Kit") && m.Contains("used on you"), "and it says what pressing does: " + m);
rig.Selected = 12;
Check(rig.S.SetFromSelected(2).Contains("wielded"), "a sword is wielded");
m = rig.S.SetFromName(3, "health");
Check(rig.S.Data.Slots[2].Item?.Name == "Health Potion" && m.Contains("Slot 3"), "set by name");
Check(rig.S.SetFromName(3, "elixir").Contains("No item named"), "a name that matches nothing");
Check(rig.S.SetFromSelected(0).Contains("no slot") && rig.S.SetFromSelected(25).Contains("no slot"), "slot numbers are checked");
rig.S.SetSlotMode(1, UseMode.Use);
Eq(rig.S.Data.Slots[0].Mode, UseMode.Use, "mode");
rig.S.SetSlot(1, rig.Inv[0]);
Eq(rig.S.Data.Slots[0].Mode, UseMode.Auto, "a new item resets the mode");
// Move.
Check(rig.S.SwapSlots(1, 2), "swap");
Check(rig.S.Data.Slots[0].Item!.Name == "Sword" && rig.S.Data.Slots[1].Item!.Name == "Peerless Healing Kit", "swapped");
Check(!rig.S.SwapSlots(1, 0) && !rig.S.SwapSlots(8, 9) && !rig.S.SwapSlots(2, 2), "no swap past the ends (8 slots) or with itself");
Eq(rig.S.ClearSlot(2), "Slot 2 cleared.", "clear");
Check(rig.S.Data.Slots[1].Empty && rig.S.Data.Slots[1].Mode == UseMode.Auto, "cleared slot is empty");
rig.S.SetSlotCount(100);
Eq(rig.S.Settings.SlotCount, 24, "slot count clamped");
rig.S.SetSlotCount(0);
Eq(rig.S.Settings.SlotCount, 1, "slot count at least 1");
// Pressing a slot.
rig.S.SetSlotCount(8);
Check(rig.S.UseSlot(2)!.Contains("empty"), "an empty slot says so");
Check(rig.S.UseSlot(40)!.Contains("no slot"), "a slot that doesn't exist");
Check(rig.S.UseSlot(1) == null && rig.S.Use.HasPending, "a set slot queues its item");
}
private static void SessionKeys()
{
var rig = new Rig("keys");
rig.Inv = new List<CarriedItem> { Kit(10, "Greater Stamina Kit") };
rig.S.SetSlot(3, rig.Inv[0]);
string m = rig.S.BindKey(3, "F9", byName: false);
Eq(rig.Chat.Count, 1, "one line to the engine (no key to take off yet)");
Eq(rig.Chat[0], "/rc hotkey add F9 /rdef use 3", "the slot's command");
Check(m.Contains("F9"), "message");
// The engine's file now has it.
File.WriteAllText(rig.HotkeyPath, "on\tF9\tcommand\t/rdef use 3\n");
rig.S.Keys.Invalidate();
Eq(rig.S.KeyOfSlot(3), "F9", "the slot shows its key");
rig.Chat.Clear();
rig.S.BindKey(3, "Ctrl+F9", byName: false);
Eq(string.Join("|", rig.Chat), "/rc hotkey remove F9|/rc hotkey add Ctrl+F9 /rdef use 3", "re-binding takes the old key off first");
File.WriteAllText(rig.HotkeyPath, "");
rig.S.Keys.Invalidate();
rig.Chat.Clear();
rig.S.BindKey(3, "F10", byName: true);
Eq(rig.Chat[^1], "/rc hotkey add F10 /rdef use Greater Stamina Kit", "by name: the item's full name");
File.WriteAllText(rig.HotkeyPath, "on\tF10\tcommand\t/rdef use Greater Stamina Kit\n");
rig.S.Keys.Invalidate();
Eq(rig.S.KeyOfSlot(3), "F10", "the key of a name binding shows on the slot holding that item");
rig.Chat.Clear();
m = rig.S.UnbindKey(3);
Eq(rig.Chat.Single(), "/rc hotkey remove F10", "unbind");
Check(m.Contains("F10"), "says which key");
File.WriteAllText(rig.HotkeyPath, "");
rig.S.Keys.Invalidate();
Check(rig.S.UnbindKey(3).Contains("no key"), "unbind with none");
Check(rig.S.BindKey(3, "", false).Contains("Type the key"), "a blank key");
Check(rig.S.BindKey(3, "Ctrl + F9", false).Contains("no spaces"), "spaces in a key");
Check(rig.S.BindKey(4, "F9", true).Contains("empty"), "by name needs an item");
Check(rig.S.BindKey(30, "F9", false).Contains("no slot"), "slot checked");
rig.S.RunChat = _ => false;
Check(rig.S.BindKey(3, "F11", false).Contains("/rc hotkey add F11 /rdef use 3"), "an engine that can't: the exact line to type");
}
private static void SessionMisc()
{
var rig = new Rig("misc");
long now = 5000;
rig.S.Now = () => now;
rig.S.SetStatus("hello");
Eq(rig.S.Status(out bool warn), "hello", "status shows");
Check(!warn, "not a warning");
now += DefSession.StatusShownMs + 1;
Eq(rig.S.Status(out _), "", "and fades");
rig.S.SetStatus("bad", true);
Check(rig.S.Status(out warn) == "bad" && warn, "warning flag");
rig.Inv = new List<CarriedItem> { Melee(5, "Sword") };
Check(rig.S.ToggleSelectedFavourite().Contains("Select a weapon"), "no selection");
rig.Selected = 5;
Check(rig.S.ToggleSelectedFavourite().Contains("is a favourite") && rig.S.Data.Favourites.Count == 1, "favourite the selected weapon");
Check(rig.S.ToggleSelectedFavourite().Contains("no longer") && rig.S.Data.Favourites.Count == 0, "and again takes it out");
rig.S.UseByName("Sword");
Check(rig.S.Use.HasPending && rig.S.Use.Pending!.Name == "Sword", "use by name queues a name request");
rig.S.Wield(ItemRef.From(rig.Inv[0]));
Check(rig.S.Use.Pending!.Mode == UseMode.Equip, "the picker's request wields");
}
}
}

View file

@ -0,0 +1,268 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Plugin.RynthDefective;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
using RynthCore.Plugin.RynthDefective.Views;
// The engine parser's only outside dependency: the registry's limits (the engine's values).
namespace RynthCore.Engine.UI.ScriptWindows
{
internal static class ScriptWindowRegistry
{
public const int MaxOpsPerWindow = 1500;
public const int MaxBytesPerWindow = 64 * 1024;
public const int MaxWindowsPerOwner = 32;
public const int MaxBytesPerSubmit = 256 * 1024;
}
}
namespace RynthDefective.Tests
{
internal static partial class Program
{
private static int _pass, _fail;
private static string _temp = "";
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Write")]
private static extern int Write(UiHost h);
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_submit")]
private static extern ref byte[] SubmitBuffer(UiHost h);
[UnsafeAccessor(UnsafeAccessorKind.Method, Name = "Apply")]
private static extern void Apply(UiHost h, ReadOnlySpan<byte> data);
private static int Main()
{
_temp = Path.Combine(Path.GetTempPath(), "RynthDefective.Tests." + Environment.ProcessId);
Directory.CreateDirectory(_temp);
try
{
Run("kinds: kits, wands by element, shields, ammunition, armor", KindsClassify);
Run("kinds: actions and stance by kind", KindsActions);
Run("match: the exact object, else the same name / wcid / material", MatchRebind);
Run("match: counts, uses left, the smaller stack first", MatchCounts);
Run("match: slots follow their items; nothing is cleared", MatchMaintain);
Run("match: items by what the player typed", MatchByName);
Run("picker: groups, order, search words, kind filter", PickerGroups);
Run("picker: favourites and recent weapons first", PickerShortcuts);
Run("pack list: one line per kind of item", PackLists);
Run("commands: /rdef parsing", Commands);
Run("store: save and load", StoreRoundTrip);
Run("store: odd files", StoreOddFiles);
Run("hotkeys: the engine's file read for the key under a slot", HotkeyFile);
Run("session: set from selected, clear, move", SessionSlots);
Run("session: bind and unbind through /rc hotkey", SessionKeys);
Run("session: favourites and the status line", SessionMisc);
Run("use: a kit on yourself, answered by UseDone", UseKit);
Run("use: one at a time, the newest wish wins, a held key queues once", UseQueue);
Run("use: busy, animating and RynthAi waiting hold a request, then it gives up", UseBusy);
Run("use: no UseDone, the quiet release and the time limit", UseUnanswered);
Run("use: a slot whose object is gone uses the next of its name", UseRebind);
Run("use: by name, missing items, target needed", UseByNameAndTargets);
Run("use: wield, confirmed by the item in hand", UseWield);
Run("use: wield refusals and time-outs", UseWieldFails);
Run("use: RynthAi's macro and weapon swaps", UseBot);
Run("use: the stance after a swap", UseStance);
Run("use: logout and portal space drop everything", UseReset);
Run("window: the bar's display list parses in the engine", WindowBar);
Run("window: editor, pack list and settings parse", WindowEditor);
Run("window: the picker parses and a click wields", WindowPicker);
Run("window: a bar button of its own, one-shot size request", WindowHeader);
Run("window: slot clicks and editor events reach their code", WindowEvents);
Run("window: lists stay inside the engine's limits", WindowLimits);
}
finally
{
try { Directory.Delete(_temp, true); } catch { }
}
Console.WriteLine($"{_pass} passed, {_fail} failed");
if (_pass == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; }
return _fail == 0 ? 0 : 1;
}
private static void Run(string name, Action test)
{
int before = _fail;
try { test(); }
catch (Exception ex) { _fail++; Console.WriteLine($"FAIL: {name} threw {ex}"); }
Console.WriteLine($" {(before == _fail ? "ok " : "FAIL")} {name}");
}
private static void Check(bool ok, string what)
{
if (ok) _pass++;
else { _fail++; Console.WriteLine("FAIL: " + what); }
}
private static void Eq<T>(T actual, T expected, string what) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}");
// ── Sample items ────────────────────────────────────────────────────
private const uint Me = 0x50000001;
private static CarriedItem Item(uint id, string name, int stack = 1, int maxStack = 1, uint wcid = 0, int material = 0)
{
return new CarriedItem { Id = id, Name = name, Stack = stack, MaxStack = maxStack, Wcid = wcid, Material = material };
}
private static CarriedItem Kit(uint id, string name = "Peerless Healing Kit", int uses = 28, uint wcid = 628)
{
var it = Item(id, name, wcid: wcid);
it.Bitfield = ItemKinds.BitfieldHealer;
it.MaxUses = 30;
it.Uses = uses;
it.Icon = 0x06001234;
return it;
}
private static CarriedItem Potion(uint id, string name = "Health Potion", int stack = 5)
{
var it = Item(id, name, stack, 100, wcid: 1000);
it.ItemType = 0x80; // Misc
it.Icon = 0x06001111;
return it;
}
private static CarriedItem Melee(uint id, string name, int material = 0, bool wielded = false)
{
var it = Item(id, name, wcid: 300, material: material);
it.ItemType = ItemKinds.TypeMelee;
it.ValidLocations = 0x00100000;
it.CombatUse = 1;
if (wielded) it.WieldedLocation = 0x00100000;
return it;
}
private static CarriedItem Bow(uint id, string name = "Yumi", bool wielded = false)
{
var it = Item(id, name, wcid: 400);
it.ItemType = ItemKinds.TypeMissile;
it.ValidLocations = 0x00400000;
it.CombatUse = 2;
if (wielded) it.WieldedLocation = 0x00400000;
return it;
}
private static CarriedItem Arrows(uint id, bool wielded = false)
{
var it = Item(id, "Arrow", 200, 250, wcid: 500);
it.ItemType = ItemKinds.TypeMissile;
it.ValidLocations = ItemKinds.AmmoSlot;
it.CombatUse = ItemKinds.CombatUseAmmo;
if (wielded) it.WieldedLocation = ItemKinds.AmmoSlot;
return it;
}
private static CarriedItem Wand(uint id, string name, int damageType = 0x10, int material = 0, bool wielded = false)
{
var it = Item(id, name, wcid: 600, material: material);
it.ItemType = ItemKinds.TypeCaster;
it.ValidLocations = 0x01000000;
it.DamageType = damageType;
if (wielded) it.WieldedLocation = 0x01000000;
return it;
}
private static CarriedItem Shield(uint id, string name = "Kite Shield", bool wielded = false)
{
var it = Item(id, name, wcid: 700);
it.ItemType = ItemKinds.TypeArmor;
it.ValidLocations = ItemKinds.ShieldSlot;
it.CombatUse = ItemKinds.CombatUseShield;
if (wielded) it.WieldedLocation = ItemKinds.ShieldSlot;
return it;
}
// ── A scripted game ─────────────────────────────────────────────────
internal sealed class FakeWorld : IDefWorld
{
public long NowMs { get; set; } = 1_000_000;
public bool InWorld { get; set; } = true;
public uint PlayerId => Me;
public uint SelectedId { get; set; }
public bool ClientBusy { get; set; }
public bool Animating { get; set; }
public bool? BotWaitingOnServer { get; set; }
public bool? BotMacroRunning { get; set; }
public int UseDoneSeq { get; set; } = 1;
public int CombatMode { get; set; } = Stance.NonCombat;
public int RefusalSeq { get; set; }
public uint RefusedObject;
public List<CarriedItem> Inventory = new();
public bool RefuseSends;
public readonly List<string> Sent = new();
public bool RefusalNamed(uint objectId) => RefusedObject == objectId;
public IReadOnlyList<CarriedItem> Items() => Inventory;
public CarriedItem? Live(uint id) => Inventory.FirstOrDefault(i => i.Id == id);
public bool UseObject(uint id)
{
if (RefuseSends) return false;
Sent.Add($"use {id:X}");
return true;
}
public bool UseObjectOn(uint id, uint target)
{
if (RefuseSends) return false;
Sent.Add($"useon {id:X} {(target == Me ? "me" : target.ToString("X"))}");
return true;
}
public bool SetCombatMode(int mode)
{
Sent.Add("mode " + mode);
CombatMode = mode;
return true;
}
public void Advance(long ms) => NowMs += ms;
public void Answer() => UseDoneSeq++;
}
private sealed class Harness
{
public readonly FakeWorld World = new();
public readonly UseController Use = new();
public readonly List<string> Said = new(), Warned = new(), Logged = new();
public readonly List<CarriedItem> Wielded = new();
public Harness()
{
Use.Say = Said.Add;
Use.Warn = Warned.Add;
Use.Log = Logged.Add;
Use.Wielded = Wielded.Add;
}
public void Tick(long advance = 0)
{
World.Advance(advance);
Use.Tick(World);
}
public void Ticks(int count, long step)
{
for (int i = 0; i < count; i++) Tick(step);
}
public bool Slot(ItemRef r, UseMode mode = UseMode.Auto) =>
Use.Request(new UseRequest(r, null, mode, "slot", World.NowMs));
public bool Named(string name) =>
Use.Request(new UseRequest(null, name, UseMode.Auto, "name", World.NowMs));
}
}
}

View file

@ -0,0 +1,48 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for RynthDefective: item kinds (kits, wands by element, shields, ammunition),
a slot following its item by name / wcid / material when the exact object is gone, counts and uses
left, the weapon picker's groups, search, kind filter, favourites and recent order, the pack list,
/rdef command parsing, the per-character file (round trip and odd files), the hotkey file
reader, the slot actions (set from selected, clear, move, bind and unbind through the engine's
"/rc hotkey" commands), the use controller (one action at a time, a queued request replaced by
the newest, the busy gates and their time limit, kits on yourself, potions, wield and the
stance that follows it, RynthAi's macro, refusals and time-outs), and that the windows'
display lists - icons and image buttons included - are accepted by the engine's own parser
(RynthCore src/RynthCore.Engine/UI/ScriptWindows/DisplayListParser.cs, compiled in from the
sibling RynthCore checkout) and that clicks reach the code that drew the button.
Nothing native is loaded: no AC, no ImGui context. Files go to a temp folder, never C:\Games.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthDefective.Tests</RootNamespace>
<NoWarn>$(NoWarn);CS0649;CS0169;CS0414;CS8618</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<!-- The engine parser's whitelists use ImGui.NET's enums. -->
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthDefective\**\*.cs" Exclude="..\..\Plugins\RynthCore.Plugin.RynthDefective\obj\**;..\..\Plugins\RynthCore.Plugin.RynthDefective\bin\**" Link="RynthDefective\%(RecursiveDir)%(Filename)%(Extension)" />
<Compile Include="..\..\Plugins\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- The shortcut bar, panel buttons and Selection windows (2026-10-22) draw with the shared ImGui look. -->
<Compile Include="..\..\Plugins\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="..\..\Plugins\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,439 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Use;
namespace RynthDefective.Tests
{
internal static partial class Program
{
private static Harness With(params CarriedItem[] items)
{
var h = new Harness();
h.World.Inventory.AddRange(items);
return h;
}
private static void UseKit()
{
Harness h = With(Kit(0x10));
Check(h.Slot(ItemRef.From(Kit(0x10))), "queued");
Check(h.Use.HasPending && !h.Use.InFlight, "waiting for the next tick");
h.Tick();
Eq(string.Join("|", h.World.Sent), "useon 10 me", "a kit is used on yourself");
Check(h.Use.InFlight && !h.Use.HasPending, "in flight");
Check(h.Said.Count == 1 && h.Said[0] == "Using Peerless Healing Kit...", "the status line says so: " + string.Join(";", h.Said));
Check(h.Logged.Count == 1 && h.Logged[0].Contains("slot") && h.Logged[0].Contains("use on you"), "and the log: " + string.Join(";", h.Logged));
h.Tick(100);
Check(h.Use.InFlight, "no answer yet: still in flight");
h.World.Answer();
h.Tick(100);
Check(!h.Use.InFlight && !h.Use.HasPending, "the server's UseDone ends it");
Eq(h.World.Sent.Count, 1, "nothing else sent");
Eq(h.Warned.Count, 0, "no warnings");
// A potion is used by itself.
h = With(Potion(0x20));
h.Slot(ItemRef.From(Potion(0x20)));
h.Tick();
Eq(string.Join("|", h.World.Sent), "use 20", "a potion is used with UseObject");
}
private static void UseQueue()
{
Harness h = With(Kit(0x10), Potion(0x20), Item(0x30, "Mana Potion", 3, 100));
ItemRef kit = ItemRef.From(Kit(0x10)), health = ItemRef.From(Potion(0x20)), mana = ItemRef.From(h.World.Inventory[2]);
h.Slot(kit);
h.Tick();
Check(h.Slot(health), "a second request while the first is in flight waits");
Check(h.Slot(mana), "a third replaces it: the newest wish wins");
Check(!h.Slot(mana), "the same request again (a key held down) does not queue twice");
h.Tick(100);
Eq(h.World.Sent.Count, 1, "nothing goes out while the first is unanswered");
h.World.Answer();
h.Tick(10);
Eq(h.World.Sent.Count, 1, "and not in the same tick it was answered (a short gap)");
h.Tick(300);
Eq(string.Join("|", h.World.Sent), "useon 10 me|use 30", "then the newest request, not the one it replaced");
// The same item pressed again while it is in flight is a new use afterwards, once.
h = With(Kit(0x10));
h.Slot(kit);
h.Tick();
Check(h.Slot(kit), "pressed again during the use: one more is queued");
Check(!h.Slot(kit), "but only one");
h.World.Answer();
h.Tick(10);
h.Tick(300);
Eq(h.World.Sent.Count, 2, "so a second kit goes out after the first");
}
private static void UseBusy()
{
Harness h = With(Kit(0x10));
ItemRef kit = ItemRef.From(Kit(0x10));
h.World.ClientBusy = true;
h.Slot(kit);
h.Ticks(5, 1000);
Eq(h.World.Sent.Count, 0, "the client's busy count holds it");
Check(h.Use.HasPending && h.Warned.Count == 0, "still waiting inside the limit");
h.Ticks(2, 1000);
Check(!h.Use.HasPending && h.Warned.Count == 1 && h.Warned[0] == "Peerless Healing Kit: not used, the character is busy.", "past the limit it gives up and says why: " + string.Join(";", h.Warned));
h = With(Kit(0x10));
h.World.Animating = true;
h.Slot(kit);
h.Ticks(7, 1000);
Check(h.Warned.Count == 1 && h.Warned[0].Contains("an animation is playing"), "a gesture holds it: " + string.Join(";", h.Warned));
h = With(Kit(0x10));
h.World.BotWaitingOnServer = true;
h.Slot(kit);
h.Ticks(3, 1000);
Eq(h.World.Sent.Count, 0, "RynthAi waiting on the server holds it");
h.World.BotWaitingOnServer = false;
h.Tick(100);
Eq(h.World.Sent.Count, 1, "and it goes the moment RynthAi is done");
// Busy clears in time: sent, no warning.
h = With(Kit(0x10));
h.World.ClientBusy = true;
h.Slot(kit);
h.Ticks(3, 1000);
h.World.ClientBusy = false;
h.Tick(100);
Check(h.World.Sent.Count == 1 && h.Warned.Count == 0, "busy cleared inside the limit: used");
// RynthAi absent (null) never holds anything.
h = With(Kit(0x10));
h.World.BotWaitingOnServer = null;
h.Slot(kit);
h.Tick();
Eq(h.World.Sent.Count, 1, "no RynthAi: nothing to wait for");
}
private static void UseUnanswered()
{
Harness h = With(Potion(0x20));
ItemRef p = ItemRef.From(Potion(0x20));
h.Slot(p);
h.Tick();
h.Tick(1000);
Check(h.Use.InFlight, "1 s with no UseDone: still waiting");
h.Tick(600);
Check(!h.Use.InFlight, "the client is quiet and 1.5 s have passed: let go (a refusal sends no UseDone)");
h = With(Potion(0x20));
h.World.Animating = true;
h.Slot(p);
h.Tick(); // animating holds the send
h.World.Animating = false;
h.Tick(100);
h.World.ClientBusy = true;
h.Tick(2000);
Check(h.Use.InFlight, "busy count up: not let go early");
h.Tick(6500);
Check(!h.Use.InFlight, "the 8 s limit lets go");
Check(h.Logged.Any(l => l.Contains("no UseDone")), "and logs it");
}
private static void UseRebind()
{
ItemRef r = ItemRef.From(Kit(0x10));
Harness h = With(Kit(0x11), Potion(0x20));
h.Slot(r);
h.Tick();
Eq(string.Join("|", h.World.Sent), "useon 11 me", "the slot's object is gone: the next kit of that name is used");
h = With(Potion(0x20));
h.Slot(r);
h.Tick();
Check(h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0] == "Peerless Healing Kit: you aren't carrying one.", "none left: says so, sends nothing: " + string.Join(";", h.Warned));
Check(!h.Use.HasPending, "and doesn't wait for one");
}
private static void UseByNameAndTargets()
{
Harness h = With(Kit(3, "Lesser Stamina Kit"), Kit(4, "Greater Stamina Kit"));
h.Named("greater stamina");
h.Tick();
Eq(string.Join("|", h.World.Sent), "useon 4 me", "by the name typed");
h = With(Kit(3));
h.Named("Elixir");
h.Tick();
Check(h.Warned.Count == 1 && h.Warned[0] == "No item named 'Elixir' in your pack.", "no such item: " + string.Join(";", h.Warned));
// Use on the selected target.
h = With(Potion(0x20, "Mana Charge"));
ItemRef r = ItemRef.From(h.World.Inventory[0]);
h.Slot(r, UseMode.OnSelected);
h.Tick();
Check(h.Warned.Count == 1 && h.Warned[0].Contains("select a target first") && h.World.Sent.Count == 0, "no target selected: nothing sent");
h.World.SelectedId = 0x1234;
h.Slot(r, UseMode.OnSelected);
h.Tick(300);
Eq(string.Join("|", h.World.Sent), "useon 20 1234", "used on the selected object");
// A kit used by itself when the slot says so.
h = With(Kit(0x10));
h.Slot(ItemRef.From(Kit(0x10)), UseMode.Use);
h.Tick();
Eq(string.Join("|", h.World.Sent), "use 10", "slot mode 'use it' overrides the kit rule");
// The client turns the request away.
h = With(Kit(0x10));
h.World.RefuseSends = true;
h.Slot(ItemRef.From(Kit(0x10)));
h.Tick();
Check(h.Warned.Count == 1 && h.Warned[0].Contains("didn't take") && !h.Use.InFlight, "a refused send is reported and not waited on");
}
private static void UseWield()
{
Harness h = With(Melee(0x32, "Sword"));
ItemRef sword = ItemRef.From(h.World.Inventory[0]);
h.Slot(sword);
h.Tick();
Eq(string.Join("|", h.World.Sent), "use 32", "a weapon is wielded with UseObject (the client's double-click)");
Check(h.Said[0] == "Wielding Sword...", "status: " + h.Said[0]);
h.Tick(100);
Check(h.Use.InFlight && h.Wielded.Count == 0, "not in hand yet: waits for it (a wield sends no UseDone)");
h.World.Answer();
h.Tick(100);
Check(h.Use.InFlight, "a UseDone does not end a wield; the item in hand does");
h.World.Inventory[0].WieldedLocation = 0x00100000;
h.Tick(100);
Check(!h.Use.InFlight && h.Wielded.Count == 1 && h.Wielded[0].Id == 0x32, "in hand: done, and reported (the picker's recent list)");
Check(h.Said[^1] == "Sword is in your hands.", "status: " + h.Said[^1]);
// Already in hand: nothing is sent (a use would take it off).
h = With(Melee(0x32, "Sword", wielded: true));
h.Slot(ItemRef.From(h.World.Inventory[0]));
h.Tick();
Check(h.World.Sent.Count == 0 && h.Said.Count == 1 && h.Said[0] == "Sword is already in your hands.", "already wielded: no use sent: " + string.Join(";", h.Said));
// Armor and rings are worn the same way and take no stance.
var helm = Item(0x40, "Helm"); helm.ItemType = ItemKinds.TypeArmor; helm.ValidLocations = 1;
h = With(helm);
h.World.CombatMode = Stance.Melee;
h.Slot(ItemRef.From(helm));
h.Tick();
helm.WieldedLocation = 1;
h.Tick(100);
Check(h.World.Sent.SequenceEqual(new[] { "use 40" }) && !h.Use.InFlight, "armor: worn, no stance change");
// Pressing the weapon again while it is being wielded does not queue another wield.
h = With(Melee(0x32, "Sword"));
h.Slot(sword);
h.Tick();
Check(!h.Slot(sword) && !h.Use.HasPending, "the same wield again is ignored");
}
private static void UseWieldFails()
{
Harness h = With(Melee(0x32, "Sword"));
ItemRef sword = ItemRef.From(h.World.Inventory[0]);
h.Slot(sword);
h.Tick();
h.Tick(3000);
Check(h.Use.InFlight, "3 s: still waiting");
h.Tick(600);
Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("not in your hands after"), "never wielded: reported once and released: " + string.Join(";", h.Warned));
Eq(h.World.Sent.Count, 1, "no automatic retry loop");
h = With(Melee(0x32, "Sword"));
h.Slot(sword);
h.Tick();
h.World.RefusalSeq++;
h.World.RefusedObject = 0x99;
h.Tick(100);
Check(h.Use.InFlight, "a refusal about another object is not ours");
h.World.RefusedObject = 0x32;
h.World.RefusalSeq++;
h.Tick(100);
Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("wouldn't let you wield"), "the server refused this wield: said at once: " + string.Join(";", h.Warned));
}
private static void UseBot()
{
Harness h = With(Melee(0x32, "Sword"), Kit(0x10));
h.World.BotMacroRunning = true;
ItemRef sword = ItemRef.From(h.World.Inventory[0]);
h.Slot(sword);
h.Tick();
Check(h.World.Sent.Count == 0 && h.Warned.Count == 1 && h.Warned[0].Contains("RynthAi's macro is running"), "a weapon is not wielded under RynthAi's macro: " + string.Join(";", h.Warned));
h.Slot(ItemRef.From(h.World.Inventory[1]));
h.Tick(300);
Eq(string.Join("|", h.World.Sent), "useon 10 me", "a kit still works (that is the point of hands-on)");
h = With(Melee(0x32, "Sword"));
h.World.BotMacroRunning = true;
h.Use.Settings.SwapWhileBotRuns = true;
h.Slot(sword);
h.Tick();
Eq(h.World.Sent.Count, 1, "allowed in the settings: wielded");
h = With(Melee(0x32, "Sword"));
h.World.BotMacroRunning = false;
h.Slot(sword);
h.Tick();
Eq(h.World.Sent.Count, 1, "macro stopped: wielded");
var helm = Item(0x40, "Helm"); helm.ItemType = ItemKinds.TypeArmor; helm.ValidLocations = 1;
h = With(helm);
h.World.BotMacroRunning = true;
h.Slot(ItemRef.From(helm));
h.Tick();
Eq(h.World.Sent.Count, 1, "armor is not a weapon swap: allowed");
}
private static void UseStance()
{
static void Wield(Harness h, CarriedItem item) => h.World.Inventory.First(i => i.Id == item.Id).WieldedLocation = 0x1;
Check(Stance.Wanted(ItemKind.Melee, false, false, Stance.NonCombat) == 0, "peace stays peace");
Check(Stance.Wanted(ItemKind.Melee, false, false, 0) == 0, "mode unknown: left alone");
Eq(Stance.Wanted(ItemKind.WarWand, false, false, Stance.Melee), Stance.Magic, "a wand from melee: magic");
Eq(Stance.Wanted(ItemKind.VoidWand, false, false, Stance.Missile), Stance.Magic, "a void wand: magic");
Eq(Stance.Wanted(ItemKind.Melee, false, false, Stance.Magic), Stance.Melee, "melee from magic");
Eq(Stance.Wanted(ItemKind.Missile, true, true, Stance.Melee), Stance.Missile, "a bow with arrows in hand: missile");
Eq(Stance.Wanted(ItemKind.Missile, true, false, Stance.Melee), Stance.NonCombat, "a bow without arrows: peace, not a stance it can't use");
Eq(Stance.Wanted(ItemKind.Missile, false, false, Stance.Melee), Stance.Missile, "thrown weapons need no ammunition");
Eq(Stance.Wanted(ItemKind.Shield, false, false, Stance.Melee), 0, "a shield leaves the stance");
Eq(Stance.Wanted(ItemKind.Armor, false, false, Stance.Magic), 0, "so does armor");
// Melee -> wand.
var wand = Wand(0x50, "Wand");
Harness h = With(wand);
h.World.CombatMode = Stance.Melee;
h.Slot(ItemRef.From(wand));
h.Tick();
Wield(h, wand);
h.Tick(100);
Check(h.Use.InFlight && h.World.Sent.Count == 1, "wielded; the stance waits for the character to settle");
h.Tick(300);
Eq(h.World.Sent.Count, 1, "still settling");
h.Tick(300);
Eq(string.Join("|", h.World.Sent), "use 50|mode 8", "then magic");
Check(!h.Use.InFlight && h.Said[^1] == "Wand is in your hands, magic stance.", "done: " + h.Said[^1]);
// Busy delays the stance; the time limit reports.
h = With(wand);
wand.WieldedLocation = 0;
h.World.CombatMode = Stance.Melee;
h.Slot(ItemRef.From(wand));
h.Tick();
Wield(h, wand);
h.World.ClientBusy = true;
h.Tick(100);
h.Tick(1000);
Eq(h.World.Sent.Count, 1, "busy: no stance request");
h.World.ClientBusy = false;
h.Tick(100);
Eq(h.World.Sent.Last(), "mode 8", "the stance goes as soon as the character is free");
h = With(wand);
wand.WieldedLocation = 0;
h.World.CombatMode = Stance.Melee;
h.Slot(ItemRef.From(wand));
h.Tick();
Wield(h, wand);
h.World.Animating = true;
h.Tick(100);
h.Tick(4500);
Check(!h.Use.InFlight && h.Warned.Count == 1 && h.Warned[0].Contains("magic stance wasn't taken"), "never free: reported, not stuck: " + string.Join(";", h.Warned));
// Magic -> melee weapon.
var sword = Melee(0x51, "Sword");
h = With(sword);
h.World.CombatMode = Stance.Magic;
h.Slot(ItemRef.From(sword));
h.Tick();
Wield(h, sword);
h.Tick(100);
h.Tick(600);
Eq(h.World.Sent.Last(), "mode 2", "from magic to melee");
// Already in the right stance: no request.
h = With(sword);
sword.WieldedLocation = 0;
h.World.CombatMode = Stance.Melee;
h.Slot(ItemRef.From(sword));
h.Tick();
Wield(h, sword);
h.Tick(100);
h.Tick(600);
Check(h.World.Sent.SequenceEqual(new[] { "use 51" }) && !h.Use.InFlight, "the server already put us in melee: nothing sent");
// Bow without arrows, then with.
var bow = Bow(0x52);
h = With(bow);
h.World.CombatMode = Stance.Melee;
h.Slot(ItemRef.From(bow));
h.Tick();
Wield(h, bow);
h.Tick(100);
h.Tick(600);
Eq(h.World.Sent.Last(), "mode 1", "no arrows in hand: back to peace");
Check(h.Said[^1].Contains("no ammunition"), "and it says why: " + h.Said[^1]);
bow.WieldedLocation = 0;
var arrows = Arrows(0x53, wielded: true);
h = With(bow, arrows);
h.World.CombatMode = Stance.Melee;
h.Slot(ItemRef.From(bow));
h.Tick();
Wield(h, bow);
h.Tick(100);
h.Tick(600);
Eq(h.World.Sent.Last(), "mode 4", "arrows in hand: missile");
// At peace the character stays at peace.
h = With(sword);
sword.WieldedLocation = 0;
h.World.CombatMode = Stance.NonCombat;
h.Slot(ItemRef.From(sword));
h.Tick();
Wield(h, sword);
h.Tick(100);
Check(h.World.Sent.SequenceEqual(new[] { "use 51" }) && !h.Use.InFlight, "peace: no stance request");
// A shield from melee keeps melee.
var shield = Shield(0x54);
h = With(shield);
h.World.CombatMode = Stance.Melee;
h.Slot(ItemRef.From(shield));
h.Tick();
Wield(h, shield);
h.Tick(100);
Check(h.World.Sent.SequenceEqual(new[] { "use 54" }), "a shield: stance untouched");
}
private static void UseReset()
{
Harness h = With(Kit(0x10));
ItemRef kit = ItemRef.From(Kit(0x10));
h.Slot(kit);
h.Tick();
h.Slot(kit);
Check(h.Use.InFlight && h.Use.HasPending, "one in flight, one waiting");
h.World.InWorld = false;
h.Tick(100);
Check(!h.Use.InFlight && !h.Use.HasPending, "portal space / logout: both dropped");
h.World.InWorld = true;
h.Tick(1000);
Eq(h.World.Sent.Count, 1, "and nothing is sent afterwards");
h = With(Kit(0x10));
h.World.InWorld = false;
h.Slot(kit);
h.Tick();
Check(!h.Use.HasPending && h.World.Sent.Count == 0, "a request made out of the world is dropped, not held for later");
}
}
}

View file

@ -0,0 +1,412 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Plugin.RynthDefective;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
using RynthCore.Plugin.RynthDefective.Views;
namespace RynthDefective.Tests
{
internal static partial class Program
{
private sealed class Windows
{
public Rig R;
public DefSession S => R.S;
public BarView Bar;
public PickerView Picker;
public UiHost Host = new();
public UiWindow BarWin, PickerWin;
public uint Seq;
public Windows(string name, bool icons = true)
{
R = new Rig(name);
S.IconsAvailable = icons;
Bar = new BarView(S);
Picker = new PickerView(S);
BarWin = Host.Add(new UiWindow("RynthDefective/Bar", "Defective") { Visible = true });
PickerWin = Host.Add(new UiWindow("RynthDefective/Weapons", "Defective Weapons") { Visible = true });
}
public void DrawBar() { BarWin.Begin(); Bar.Draw(BarWin); BarWin.End(); }
public void DrawPicker() { PickerWin.Begin(); Picker.Draw(PickerWin); PickerWin.End(); }
public string BarText => Encoding.UTF8.GetString(BarWin.Body);
public string PickerText => Encoding.UTF8.GetString(PickerWin.Body);
public void Click(UiWindow w, string id) => Apply(Host, EventFor(1, w, id, new byte[] { 1, 0 }));
public void SetInt(UiWindow w, string id, int v) => Apply(Host, EventFor(3, w, id, BitConverter.GetBytes(v)));
public void SetBool(UiWindow w, string id, bool v) => Apply(Host, EventFor(2, w, id, new byte[] { (byte)(v ? 1 : 0) }));
public void SetText(UiWindow w, string id, string text)
{
byte[] utf8 = Encoding.UTF8.GetBytes(text);
var p = new byte[3 + utf8.Length];
p[0] = 0;
BitConverter.GetBytes((ushort)utf8.Length).CopyTo(p, 1);
utf8.CopyTo(p, 3);
Apply(Host, EventFor(5, w, id, p));
}
private byte[] EventFor(ushort type, UiWindow w, string id, byte[] payload)
{
var e = new byte[16 + payload.Length];
BitConverter.GetBytes(type).CopyTo(e, 0);
BitConverter.GetBytes((ushort)e.Length).CopyTo(e, 2);
BitConverter.GetBytes(++Seq).CopyTo(e, 4);
BitConverter.GetBytes(w.Hash).CopyTo(e, 8);
BitConverter.GetBytes(w.KeyOf(id)).CopyTo(e, 12);
payload.CopyTo(e, 16);
return e;
}
}
private static Windows Stocked(string name, bool icons = true)
{
var w = new Windows(name, icons);
w.R.Inv = new List<CarriedItem>(Armory());
w.R.Inv.Add(Potion(20, "Health Potion", 23));
w.R.Inv.Add(Kit(21, uses: 10));
w.R.Inv.Add(Kit(22, uses: 28));
w.S.LoggedIn = true;
w.S.SetSlot(1, Kit(21));
w.S.SetSlot(2, Potion(20));
w.S.SetSlot(3, Melee(3, "Mace", wielded: true));
w.S.SetSlot(4, new CarriedItem { Id = 99, Name = "Mana Stone", Icon = 0x06004444 }); // not carried
File.WriteAllText(w.R.HotkeyPath, "on\tF9\tcommand\t/rdef use 1\non\tCtrl+F2\tcommand\t/rdef use 3\n");
w.S.Keys.Invalidate();
return w;
}
private static unsafe List<ParsedWindow> ParseAll(UiHost host, string what, out int maxOps)
{
int n = Write(host);
byte[] buf = SubmitBuffer(host);
int rc;
List<ParsedWindow> windows;
string error;
fixed (byte* p = buf) rc = DisplayListParser.Parse(p, n, 4000f, out _, out windows, out error);
Check(rc == 0, $"{what}: engine parser refused the submit ({rc}): {error}");
maxOps = windows.Where(x => x.List != null).Select(x => x.List!.OpCount).DefaultIfEmpty(0).Max();
return windows;
}
private static int CountOps(ParsedWindow w, ScriptOp op)
{
int n = 0;
if (w.List == null) return 0;
for (int i = 0; i < w.List.OpCount; i++)
if (w.List.Ops[i].Code == op) n++;
return n;
}
private static void WindowBar()
{
Windows w = Stocked("bar");
w.DrawBar();
List<ParsedWindow> parsed = ParseAll(w.Host, "bar", out int ops);
Check(ops > 10 && ops < 1500, $"ops in range ({ops})");
string body = w.BarText;
Check(body.Contains("66") && body.Contains("x28") && body.Contains("in hand") && body.Contains("none"), "uses left, a stack's count, the weapon in hand, and the missing one");
Check(body.Contains("F9") && body.Contains("C+F2"), "the keys under their slots: " + body);
Check(body.Contains("Edit slots") && body.Contains("Settings") && body.Contains("Weapons"), "the toolbar");
Check(body.Contains("Click a slot, or press its key."), "the idle status line");
ParsedWindow bar = parsed.First(p => p.Key == "RynthDefective/Bar");
Eq(CountOps(bar, ScriptOp.ImageButton), 4, "four set slots drawn as image buttons (the missing one from its stored picture)");
Eq(CountOps(bar, ScriptOp.Button), 4 + 3, "four empty slots (+ signs) and the three toolbar buttons");
// Icons off or unavailable: text buttons.
Windows t = Stocked("bar-text", icons: false);
t.DrawBar();
parsed = ParseAll(t.Host, "bar without icons", out _);
bar = parsed.First(p => p.Key == "RynthDefective/Bar");
Check(CountOps(bar, ScriptOp.ImageButton) == 0 && CountOps(bar, ScriptOp.Button) >= 8, "no pictures: text buttons");
Check(t.BarText.Contains("PHK"), "named by initials: " + "PHK");
t.S.IconsAvailable = true;
t.S.Settings.ShowIcons = false;
t.DrawBar();
Eq(CountOps(ParseAll(t.Host, "icons off", out _).First(p => p.Key == "RynthDefective/Bar"), ScriptOp.ImageButton), 0, "ShowIcons off: no pictures either");
// Counts and keys can be switched off.
Windows c = Stocked("bar-nocounts");
c.S.Settings.ShowCounts = false;
c.DrawBar();
ParseAll(c.Host, "no counts", out _);
Check(!c.BarText.Contains("x28") && !c.BarText.Contains("C+F2"), "no counts or keys under the slots");
// Pending and status lines.
Windows p = Stocked("bar-status");
p.S.Use.Request(new UseRequest(null, "Health Potion", UseMode.Auto, "t", 0));
p.DrawBar();
Check(p.BarText.Contains("Waiting to use Health Potion..."), "a waiting request shows");
p.S.Use.Reset();
p.S.SetStatus("Slot 1 cleared.");
p.DrawBar();
Check(p.BarText.Contains("Slot 1 cleared."), "the status line shows");
// Not logged in.
var out1 = new Windows("bar-out");
out1.S.LoggedIn = false;
out1.DrawBar();
ParseAll(out1.Host, "logged out", out _);
Check(out1.BarText.Contains("Log in to use the item bar."), "before login");
// Window size that fits.
(float ww, float hh) = w.Bar.WantedSize();
Check(ww >= 250f && hh > 80f, $"a fitting size ({ww} x {hh})");
w.S.Settings.SlotCount = 24; w.S.Settings.SlotsPerRow = 6;
(float w2, float h2) = w.Bar.WantedSize();
Check(h2 > hh, "more rows, taller");
}
private static void WindowEditor()
{
Windows w = Stocked("editor");
w.Bar.EditOpen = true;
w.Bar.SettingsOpen = true;
w.Bar.Editor.Select(1);
w.DrawBar();
ParseAll(w.Host, "editor", out int ops);
string body = w.BarText;
Check(body.Contains("Set from selected") && body.Contains("Pick from pack") && body.Contains("Clear") && body.Contains("Move up"), "the slot buttons");
Check(body.Contains("Slot 1: Peerless Healing Kit") && body.Contains("1. Peerless Healing Kit [F9]"), "the list shows the item and its key");
Check(body.Contains("Pressing it") && body.Contains("It is a healing or stamina kit: pressing the slot has it used on you."), "how it is used: " + body);
Check(body.Contains("Key: F9") && body.Contains("Key to bind") && body.Contains("Bind to this slot") && body.Contains("Bind to this item") && body.Contains("Unbind"), "the key controls");
Check(body.Contains("Selected in the game: nothing"), "and what is selected");
Check(body.Contains("Slots per row") && body.Contains("Button size") && body.Contains("Hazridi") && body.Contains("no code from it"), "settings and the credit");
// The missing slot's editor says so.
w.Bar.Editor.Select(4);
w.DrawBar();
ParseAll(w.Host, "editor, missing", out _);
Check(w.BarText.Contains("Not in your pack right now."), "a missing item is explained");
// The pack list.
w.Bar.Editor.Select(5);
w.DrawBar();
w.Click(w.BarWin, "ed.pick");
w.DrawBar();
ParseAll(w.Host, "pack list", out _);
body = w.BarText;
Check(w.Bar.Editor.Picking && body.Contains("Search your pack") && body.Contains("Health Potion x28") && body.Contains("Peerless Healing Kit x3"), "the pack list with counts: " + body);
Check(!body.Contains("Pressing it"), "an empty slot has no use setting");
w.SetText(w.BarWin, "ed.packsearch", "potion");
w.DrawBar();
Check(w.BarText.Contains("Health Potion") && !w.BarText.Contains("Yumi"), "the pack list narrows");
}
private static void WindowPicker()
{
Windows w = Stocked("picker");
w.S.Data.Favourites.Add(ItemRef.From(w.R.Inv[9])); // Gold Wand
w.S.Data.Recent.Add(ItemRef.From(w.R.Inv[0])); // Sword
w.DrawPicker();
List<ParsedWindow> parsed = ParseAll(w.Host, "picker", out int ops);
string body = w.PickerText;
Check(ops > 20 && ops < 1500, $"ops in range ({ops})");
Check(body.Contains("Favourites") && body.Contains("Recent") && body.Contains("Melee (3)") && body.Contains("War Magic (2)")
&& body.Contains("Void Magic (2)") && body.Contains("Shields (1)") && body.Contains("Ammunition (1)"), "sections: " + body);
Check(body.Contains("Mace [in hand]") && body.Contains("In hand: Mace"), "the weapon in hand is marked");
Check(body.Contains("Silver Wand (Fire)") && body.Contains("Orb (Nether)"), "casters with their element");
Check(body.IndexOf("Favourites", StringComparison.Ordinal) < body.IndexOf("Recent", StringComparison.Ordinal)
&& body.IndexOf("Recent", StringComparison.Ordinal) < body.IndexOf("Melee (3)", StringComparison.Ordinal), "favourites, recent, then the kinds");
ParsedWindow pk = parsed.First(p => p.Key == "RynthDefective/Weapons");
Check(CountOps(pk, ScriptOp.Image) >= 12 && CountOps(pk, ScriptOp.Selectable) >= 12, "a picture and a row for each weapon");
Check(CountOps(pk, ScriptOp.Child) == 1, "one scrolling list");
// Clicking a row wields it.
w.Click(w.PickerWin, "pkg1"); // the Sword in the Melee group
Check(w.S.Use.HasPending && w.S.Use.Pending!.Mode == UseMode.Equip && w.S.Use.Pending.Item!.Name == "Sword", "one click on a row queues the wield");
// The star: favourites.
w.Click(w.PickerWin, "favg1");
Check(w.S.Data.Favourites.Any(f => f.Name == "Sword"), "+ adds a favourite");
w.DrawPicker();
Check(w.PickerText.Contains("-"), "and shows - for it");
// Kind buttons and search.
w.Click(w.PickerWin, "pk.kind" + (int)KindFilter.Void);
Eq(w.S.Settings.PreferredKind, KindFilter.Void, "the kind button sets the preferred kind");
w.DrawPicker();
ParseAll(w.Host, "void filter", out _);
Check(w.PickerText.Contains("Void Magic (2)") && !w.PickerText.Contains("Melee ("), "only void shown");
Check(w.PickerText.Contains("2 of 11 shown"), "how many of how many: " + w.PickerText);
w.Click(w.PickerWin, "pk.kind" + (int)KindFilter.All);
w.SetText(w.PickerWin, "pk.search", "mace");
w.DrawPicker();
ParseAll(w.Host, "search", out _);
Check(w.PickerText.Contains("Melee (1)") && !w.PickerText.Contains("Void Magic ("), "search narrows");
w.SetText(w.PickerWin, "pk.search", "zzz");
w.DrawPicker();
Check(w.PickerText.Contains("Nothing matches."), "and says when nothing does");
w.Click(w.PickerWin, "pk.clear");
Eq(w.Picker.Search, "", "clear");
// No weapons / not logged in.
var none = new Windows("picker-none") { };
none.S.LoggedIn = true;
none.DrawPicker();
ParseAll(none.Host, "empty picker", out _);
Check(none.PickerText.Contains("No weapons or wands in your pack.") && none.PickerText.Contains("In hand: nothing"), "an empty pack");
var out2 = new Windows("picker-out");
out2.S.LoggedIn = false;
out2.DrawPicker();
Check(out2.PickerText.Contains("Log in to pick a weapon."), "before login");
// Icons off: rows without pictures.
Windows t = Stocked("picker-text", icons: false);
t.DrawPicker();
Eq(CountOps(ParseAll(t.Host, "picker, text", out _).First(p => p.Key == "RynthDefective/Weapons"), ScriptOp.Image), 0, "no pictures when the engine can't draw them");
}
private static void WindowHeader()
{
Eq(UiFormat.FlagBarButton, WindowFlags.BarButton, "the plugin's bit is the engine's");
Windows w = Stocked("header");
w.DrawBar();
w.DrawPicker();
List<ParsedWindow> parsed = ParseAll(w.Host, "header", out _);
Check(parsed.Count == 2 && parsed[0].Title == "Defective" && parsed[1].Title == "Defective Weapons", "two windows, titled for their bar buttons");
Check(parsed.All(p => (p.Flags & WindowFlags.ShowInBar) != 0 && (p.Flags & WindowFlags.BarButton) != 0), "each has a button of its own on the bar");
Check(float.IsNaN(parsed[0].RequestSize.X), "no size request by default");
w.BarWin.RequestWidth = 320f;
w.BarWin.RequestHeight = 210f;
parsed = ParseAll(w.Host, "size request", out _);
Check(parsed[0].RequestSize.X == 320f && parsed[0].RequestSize.Y == 210f, "a size request goes out");
w.BarWin.MarkSubmitted(true);
w.PickerWin.MarkSubmitted(true);
Check(float.IsNaN(w.BarWin.RequestWidth), "and is forgotten once sent (a standing request would undo the player's resizing)");
Check(!w.BarWin.HeaderDirty, "so the header is clean again");
}
private static void WindowEvents()
{
Windows w = Stocked("events");
w.DrawBar();
w.BarWin.MarkSubmitted(true);
// A slot button runs the slot.
w.Click(w.BarWin, "slot2");
Check(w.S.Use.HasPending && w.S.Use.Pending!.Item!.Name == "Health Potion", "clicking the slot queues its item");
w.S.Use.Reset();
w.Click(w.BarWin, "slot5"); // an empty slot: opens the editor on it
Check(w.Bar.EditOpen && w.Bar.Editor.SelectedSlot == 5, "an empty slot opens the editor on it");
w.Click(w.BarWin, "slot4"); // the missing one
Check(w.S.Use.HasPending, "a missing slot still queues (and the controller reports it)");
w.S.Use.Reset();
// Toolbar.
w.Click(w.BarWin, "tb.settings");
Check(w.Bar.SettingsOpen, "Settings toggles");
bool shown = false;
w.Bar.ShowPicker = () => shown = true;
w.Click(w.BarWin, "tb.weapons");
Check(shown, "Weapons asks for the picker");
int fits = 0;
w.Bar.RequestFit = () => fits++;
w.Click(w.BarWin, "tb.edit");
Check(fits == 1 && !w.Bar.EditOpen, "toggling a section asks the window to fit");
// Editor: set from the game's selection, mode, key.
w.Bar.EditOpen = true;
w.Bar.Editor.Select(5);
w.R.Selected = 20; // the Health Potion
w.DrawBar();
Check(w.BarText.Contains("Selected in the game: Health Potion"), "the selection is named");
w.Click(w.BarWin, "ed.set");
Check(w.S.Data.Slots[4].Item?.Name == "Health Potion", "Set from selected fills the slot");
w.DrawBar();
w.SetInt(w.BarWin, "ed.mode", (int)UseMode.OnSelected);
Eq(w.S.Data.Slots[4].Mode, UseMode.OnSelected, "the use mode");
w.SetText(w.BarWin, "ed.key", "F7");
w.DrawBar();
w.Click(w.BarWin, "ed.bind");
Check(w.R.Chat.Contains("/rc hotkey add F7 /rdef use 5"), "Bind to this slot types the engine's hotkey command: " + string.Join("|", w.R.Chat));
w.Click(w.BarWin, "ed.bindname");
Check(w.R.Chat.Contains("/rc hotkey add F7 /rdef use Health Potion"), "and by name");
w.Click(w.BarWin, "ed.clear");
Check(w.S.Data.Slots[4].Empty, "Clear");
w.Bar.Editor.Select(2);
w.DrawBar();
w.Click(w.BarWin, "ed.down");
Check(w.S.Data.Slots[2].Item?.Name == "Health Potion" && w.S.Data.Slots[1].Item?.Name == "Mace" && w.Bar.Editor.SelectedSlot == 3, "Move down swaps and follows");
w.DrawBar();
w.Click(w.BarWin, "ed.up");
Check(w.S.Data.Slots[1].Item?.Name == "Health Potion" && w.Bar.Editor.SelectedSlot == 2, "Move up swaps back");
w.DrawBar();
w.Click(w.BarWin, "row6");
Eq(w.Bar.Editor.SelectedSlot, 6, "picking a row selects the slot");
// Pack list click assigns.
w.Bar.Editor.Select(6);
w.DrawBar();
w.Click(w.BarWin, "ed.pick");
w.DrawBar();
w.Click(w.BarWin, "pk" + 4); // Yumi, id 4
Check(w.S.Data.Slots[5].Item?.Name == "Yumi" && !w.Bar.Editor.Picking, "choosing from the pack list sets the slot and closes the list");
// Settings.
w.Bar.SettingsOpen = true;
w.DrawBar();
fits = 0;
w.SetInt(w.BarWin, "set.slots", 12);
Check(w.S.Settings.SlotCount == 12 && fits == 1, "slot count slider, window refits");
w.SetInt(w.BarWin, "set.perrow", 4);
Eq(w.S.Settings.SlotsPerRow, 4, "per row");
w.SetInt(w.BarWin, "set.button", 48);
Eq(w.S.Settings.ButtonSize, 48, "button size");
w.SetInt(w.BarWin, "set.picker", 40);
Eq(w.S.Settings.PickerIconSize, 40, "picker icon size");
w.SetBool(w.BarWin, "set.icons", false);
Check(!w.S.Settings.ShowIcons, "icons off");
w.SetBool(w.BarWin, "set.counts", false);
Check(!w.S.Settings.ShowCounts, "counts off");
w.SetBool(w.BarWin, "set.swap", true);
Check(w.S.Settings.SwapWhileBotRuns, "swap switch");
w.SetInt(w.BarWin, "set.slots", 500);
Eq(w.S.Settings.SlotCount, 24, "the slider's value is clamped to the maximum");
Check(w.R.Saves > 5, "every change asks for a save");
}
private static void WindowLimits()
{
// A big pack: 24 slots, editor with the pack list (40 rows), settings.
Windows w = Stocked("limits");
for (uint i = 0; i < 300; i++) w.R.Inv.Add(Potion(1000 + i, "Potion Number " + i, 3));
w.S.Settings.SlotCount = 24;
w.S.Settings.SlotsPerRow = 8;
for (int i = 0; i < 24; i++) w.S.SetSlot(i + 1, w.R.Inv[Math.Min(w.R.Inv.Count - 1, 14 + i)]);
w.Bar.EditOpen = true;
w.Bar.SettingsOpen = true;
w.Bar.Editor.Select(3);
w.DrawBar();
w.Click(w.BarWin, "ed.pick");
w.DrawBar();
ParseAll(w.Host, "full bar", out int ops);
Check(ops < 1500 && w.BarWin.Body.Length < UiFormat.MaxBodyBytes, $"the full bar fits the engine's limits ({ops} ops, {w.BarWin.Body.Length} bytes)");
Check(w.BarText.Contains("more - type to narrow the list."), "the pack list says when it was cut");
// 400 weapons in the picker: cut with a note, still accepted.
Windows p = new Windows("limits-picker");
p.S.LoggedIn = true;
for (uint i = 0; i < 400; i++) p.R.Inv.Add(Melee(5000 + i, "Blade " + i.ToString("000")));
for (uint i = 0; i < 40; i++) p.S.Data.Favourites.Add(new ItemRef { Id = 5000 + i, Name = "Blade " + i.ToString("000"), Wcid = 300 });
p.DrawPicker();
ParseAll(p.Host, "400 weapons", out ops);
Check(ops < 1500 && p.PickerWin.Body.Length < UiFormat.MaxBodyBytes, $"400 weapons stay inside the limits ({ops} ops, {p.PickerWin.Body.Length} bytes)");
Check(p.PickerText.Contains("more than fits in one window"), "and it says the list was cut");
// ... and a search brings the one wanted back into the list.
p.Picker.Search = "Blade 399";
p.DrawPicker();
ParseAll(p.Host, "search in 400", out _);
Check(p.PickerText.Contains("Blade 399") && !p.PickerText.Contains("more than fits"), "a search finds it");
}
}
}