Snapshot for release 2026.10.23.1 (internal 7581cff)
This commit is contained in:
parent
893973d0dd
commit
92f28bd243
73 changed files with 12203 additions and 308 deletions
|
|
@ -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; }
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
|
|
|||
893
Tools/RynthCore.RynthAiHostTests/Tests/HandSwapTests.cs
Normal file
893
Tools/RynthCore.RynthAiHostTests/Tests/HandSwapTests.cs
Normal 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(); }
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
|
|
|||
603
Tools/RynthDefective.Tests/ModelTests.cs
Normal file
603
Tools/RynthDefective.Tests/ModelTests.cs
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
268
Tools/RynthDefective.Tests/Program.cs
Normal file
268
Tools/RynthDefective.Tests/Program.cs
Normal 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
48
Tools/RynthDefective.Tests/RynthDefective.Tests.csproj
Normal file
48
Tools/RynthDefective.Tests/RynthDefective.Tests.csproj
Normal 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>
|
||||
439
Tools/RynthDefective.Tests/UseTests.cs
Normal file
439
Tools/RynthDefective.Tests/UseTests.cs
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
412
Tools/RynthDefective.Tests/WindowTests.cs
Normal file
412
Tools/RynthDefective.Tests/WindowTests.cs
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue