RynthSuite as of 2026-11-08 (internal 6ec9b64): release 2026.11.8.1
This commit is contained in:
parent
7166d256ce
commit
f8fa62b64c
196 changed files with 24980 additions and 633 deletions
|
|
@ -58,6 +58,14 @@ internal static unsafe class FakeHost
|
|||
/// engine's EquipmentTracker: item -> EquipMask). <see cref="EquippedNotReady"/> answers -1.</summary>
|
||||
public static bool EquippedCalls;
|
||||
public static bool EquippedNotReady;
|
||||
/// <summary>Opt-in (set before Create): v93 GetMonsterHealth answering <see cref="PlateHealth"/> (the
|
||||
/// engine monster plates' last server reading: id -> ratio, age in ms). <see cref="PlateHealthVersion"/>
|
||||
/// non-zero sets the table's Version (e.g. 92: the slot is there but the engine is too old).
|
||||
/// Calls are counted in <see cref="PlateHealthQueries"/>.</summary>
|
||||
public static bool PlateHealthCalls;
|
||||
public static uint PlateHealthVersion;
|
||||
public static readonly Dictionary<uint, (float Ratio, uint AgeMs)> PlateHealth = new();
|
||||
public static int PlateHealthQueries;
|
||||
public static readonly Dictionary<uint, uint> Equipped = new();
|
||||
/// <summary>Item id -> the creature wielding it (GetObjectOwnershipInfo's wielder). Entries here
|
||||
/// also install GetObjectOwnershipInfo; an id in neither map reads as unknown ownership.</summary>
|
||||
|
|
@ -130,6 +138,9 @@ internal static unsafe class FakeHost
|
|||
public static bool AttackSendCalls;
|
||||
/// <summary>Every melee or missile attack (kind, target, height, power), in order (opt-in with <see cref="AttackSendCalls"/>).</summary>
|
||||
public static readonly List<(string Kind, uint Target, int Height, float Power)> AttackCalls = new();
|
||||
/// <summary>Opt-in (set before Create): wires NativeAttack and SelectItem; a native attack lands in
|
||||
/// <see cref="AttackCalls"/> as ("native", the selected item, height, power).</summary>
|
||||
public static bool NativeAttackCalls;
|
||||
/// <summary>Opt-in (set before Create): wires CancelAttack; calls are counted in <see cref="CancelAttacks"/>.</summary>
|
||||
public static bool CancelAttackCalls;
|
||||
public static int CancelAttacks;
|
||||
|
|
@ -260,6 +271,8 @@ internal static unsafe class FakeHost
|
|||
public static bool PluginCommandDelivered = true;
|
||||
/// <summary>Every SendPluginCommand (plugin, action, value), in order.</summary>
|
||||
public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new();
|
||||
/// <summary>For each <see cref="PluginCommands"/> entry, how many chat lines were written before it (call order).</summary>
|
||||
public static readonly List<int> PluginCommandChatCounts = new();
|
||||
/// <summary>Opt-in (set before Create): ForceResetBusyCount (counted in <see cref="ForceResets"/>)
|
||||
/// and GetBusyState (answering <see cref="BusyStateValue"/>).</summary>
|
||||
public static bool BusyCalls;
|
||||
|
|
@ -297,6 +310,7 @@ internal static unsafe class FakeHost
|
|||
public static void Reset()
|
||||
{
|
||||
EquippedCalls = false; EquippedNotReady = false; Equipped.Clear();
|
||||
PlateHealthCalls = false; PlateHealthVersion = 0; PlateHealth.Clear(); PlateHealthQueries = 0;
|
||||
#if !RYNTHILT_TESTS
|
||||
RynthCore.Plugin.RynthAi.EquippedState.Invalidate();
|
||||
#endif
|
||||
|
|
@ -310,7 +324,7 @@ internal static unsafe class FakeHost
|
|||
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
|
||||
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
|
||||
Logs.Clear(); Chat.Clear(); ChatTypes.Clear(); ChatCommands.Clear(); AfterCastSpell = null;
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); CancelAttackCalls = false; CancelAttacks = 0; Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
|
||||
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Order.Clear(); Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); NativeAttackCalls = false; CancelAttackCalls = false; CancelAttacks = 0; Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
|
||||
Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1;
|
||||
RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true;
|
||||
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
|
||||
|
|
@ -328,7 +342,7 @@ internal static unsafe class FakeHost
|
|||
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
|
||||
SelectedItem = 0;
|
||||
UseOnCalls = false; UsesOn.Clear();
|
||||
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear();
|
||||
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear(); PluginCommandChatCounts.Clear();
|
||||
TradeVendorCalls = false; TradeActions.Clear(); VendorSells.Clear(); VendorBuys.Clear();
|
||||
CombatModeCalls = false; CombatModeRequests.Clear(); CombatModeRefuse = false; CombatModeRefusals = 0;
|
||||
BusyCalls = false; ForceResets = 0; BusyStateValue = 0;
|
||||
|
|
@ -396,9 +410,14 @@ internal static unsafe class FakeHost
|
|||
api.MeleeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, float, int>)&MeleeAttack;
|
||||
api.MissileAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, float, int>)&MissileAttack;
|
||||
}
|
||||
if (NativeAttackCalls)
|
||||
{
|
||||
api.NativeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, float, int>)&NativeAttack;
|
||||
api.SelectItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&SelectItem;
|
||||
}
|
||||
if (Nav3DCalls)
|
||||
{
|
||||
api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nav3DClear;
|
||||
api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nav3DClear;
|
||||
api.Nav3DAddRingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, uint, void>)&Nav3DAddRing;
|
||||
api.Nav3DAddLineFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, float, float, uint, void>)&Nav3DAddLine;
|
||||
api.Nav3DAddTriangleFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, float, float, float, float, uint, void>)&Nav3DAddTriangle;
|
||||
|
|
@ -541,6 +560,11 @@ internal static unsafe class FakeHost
|
|||
ConfigureApi?.Invoke(ref api);
|
||||
LastApi = api;
|
||||
if (EquippedCalls) api.Version = Math.Max(api.Version, 87u); // v87 GetWieldedItems
|
||||
if (PlateHealthCalls)
|
||||
{
|
||||
api.GetMonsterHealthFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, float*, uint*, int>)&GetMonsterHealth;
|
||||
api.Version = PlateHealthVersion != 0 ? PlateHealthVersion : Math.Max(api.Version, 93u); // v93
|
||||
}
|
||||
return new RynthCoreHost(api);
|
||||
}
|
||||
|
||||
|
|
@ -623,6 +647,7 @@ internal static unsafe class FakeHost
|
|||
private static int SendPluginCommand(IntPtr plugin, IntPtr action, IntPtr value)
|
||||
{
|
||||
PluginCommands.Add((Marshal.PtrToStringAnsi(plugin) ?? "", Marshal.PtrToStringAnsi(action) ?? "", Marshal.PtrToStringAnsi(value) ?? ""));
|
||||
PluginCommandChatCounts.Add(Chat.Count);
|
||||
return PluginCommandDelivered ? 1 : 0;
|
||||
}
|
||||
|
||||
|
|
@ -660,6 +685,16 @@ internal static unsafe class FakeHost
|
|||
return 1;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetMonsterHealth(uint id, float* ratio, uint* ageMs)
|
||||
{
|
||||
PlateHealthQueries++;
|
||||
bool ok = PlateHealth.TryGetValue(id, out var h);
|
||||
if (ratio != null) *ratio = ok ? h.Ratio : -1f;
|
||||
if (ageMs != null) *ageMs = ok ? h.AgeMs : uint.MaxValue;
|
||||
return ok ? 1 : 0;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetWieldedItems(uint* ids, uint* locations, int max)
|
||||
{
|
||||
|
|
@ -882,6 +917,10 @@ internal static unsafe class FakeHost
|
|||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int MeleeAttack(uint target, int height, float power) { AttackCalls.Add(("melee", target, height, power)); return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int NativeAttack(int height, float power) { AttackCalls.Add(("native", SelectedItem, height, power)); return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int SelectItem(uint id) { SelectedItem = id; return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int MissileAttack(uint target, int height, float power) { AttackCalls.Add(("missile", target, height, power)); return 1; }
|
||||
|
|
|
|||
137
Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-clamp.usd
Normal file
137
Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-clamp.usd
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
MyMonsters
|
||||
21
|
||||
MonsterName
|
||||
AttackPriority
|
||||
DamageType
|
||||
WeaponToUse
|
||||
Imperil
|
||||
Vuln
|
||||
Yield
|
||||
GravityW
|
||||
Attack
|
||||
Ring
|
||||
Broadside
|
||||
Fester
|
||||
WeakeningCurse
|
||||
FesteringCurse
|
||||
Corruption
|
||||
DestructiveCurse
|
||||
Corrosion
|
||||
Streak
|
||||
SecondaryVuln
|
||||
SecondaryEquip
|
||||
PetDamageType
|
||||
y
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
2
|
||||
s
|
||||
<DEFAULT>
|
||||
i
|
||||
1
|
||||
i
|
||||
1
|
||||
i
|
||||
-1
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
True
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
i
|
||||
0
|
||||
i
|
||||
-1
|
||||
i
|
||||
101
|
||||
s
|
||||
Drudge Skulker
|
||||
i
|
||||
1
|
||||
i
|
||||
1
|
||||
i
|
||||
-1
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
True
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
i
|
||||
0
|
||||
i
|
||||
-1
|
||||
i
|
||||
101
|
||||
s
|
||||
MinimumRingTargets
|
||||
i
|
||||
30
|
||||
s
|
||||
RingDistance
|
||||
d
|
||||
0.3
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
MyMonsters
|
||||
21
|
||||
MonsterName
|
||||
AttackPriority
|
||||
DamageType
|
||||
WeaponToUse
|
||||
Imperil
|
||||
Vuln
|
||||
Yield
|
||||
GravityW
|
||||
Attack
|
||||
Ring
|
||||
Broadside
|
||||
Fester
|
||||
WeakeningCurse
|
||||
FesteringCurse
|
||||
Corruption
|
||||
DestructiveCurse
|
||||
Corrosion
|
||||
Streak
|
||||
SecondaryVuln
|
||||
SecondaryEquip
|
||||
PetDamageType
|
||||
y
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
2
|
||||
s
|
||||
<DEFAULT>
|
||||
i
|
||||
1
|
||||
i
|
||||
1
|
||||
i
|
||||
-1
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
True
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
i
|
||||
0
|
||||
i
|
||||
-1
|
||||
i
|
||||
101
|
||||
s
|
||||
Drudge Skulker
|
||||
i
|
||||
1
|
||||
i
|
||||
1
|
||||
i
|
||||
-1
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
True
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
i
|
||||
0
|
||||
i
|
||||
-1
|
||||
i
|
||||
101
|
||||
s
|
||||
MinimumRingTargets
|
||||
i
|
||||
0
|
||||
141
Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-none.usd
Normal file
141
Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings-none.usd
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
MyMonsters
|
||||
21
|
||||
MonsterName
|
||||
AttackPriority
|
||||
DamageType
|
||||
WeaponToUse
|
||||
Imperil
|
||||
Vuln
|
||||
Yield
|
||||
GravityW
|
||||
Attack
|
||||
Ring
|
||||
Broadside
|
||||
Fester
|
||||
WeakeningCurse
|
||||
FesteringCurse
|
||||
Corruption
|
||||
DestructiveCurse
|
||||
Corrosion
|
||||
Streak
|
||||
SecondaryVuln
|
||||
SecondaryEquip
|
||||
PetDamageType
|
||||
y
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
2
|
||||
s
|
||||
<DEFAULT>
|
||||
i
|
||||
1
|
||||
i
|
||||
1
|
||||
i
|
||||
-1
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
True
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
i
|
||||
0
|
||||
i
|
||||
-1
|
||||
i
|
||||
101
|
||||
s
|
||||
Drudge Skulker
|
||||
i
|
||||
1
|
||||
i
|
||||
1
|
||||
i
|
||||
-1
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
True
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
i
|
||||
0
|
||||
i
|
||||
-1
|
||||
i
|
||||
101
|
||||
s
|
||||
EnableLooting
|
||||
b
|
||||
False
|
||||
s
|
||||
AttackDistance
|
||||
d
|
||||
0.3
|
||||
s
|
||||
summonpets
|
||||
b
|
||||
False
|
||||
149
Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings.usd
Normal file
149
Tools/RynthCore.RynthAiHostTests/Fixtures/vtank-rings.usd
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
MyMonsters
|
||||
21
|
||||
MonsterName
|
||||
AttackPriority
|
||||
DamageType
|
||||
WeaponToUse
|
||||
Imperil
|
||||
Vuln
|
||||
Yield
|
||||
GravityW
|
||||
Attack
|
||||
Ring
|
||||
Broadside
|
||||
Fester
|
||||
WeakeningCurse
|
||||
FesteringCurse
|
||||
Corruption
|
||||
DestructiveCurse
|
||||
Corrosion
|
||||
Streak
|
||||
SecondaryVuln
|
||||
SecondaryEquip
|
||||
PetDamageType
|
||||
y
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
n
|
||||
2
|
||||
s
|
||||
<DEFAULT>
|
||||
i
|
||||
1
|
||||
i
|
||||
1
|
||||
i
|
||||
-1
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
True
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
i
|
||||
0
|
||||
i
|
||||
-1
|
||||
i
|
||||
101
|
||||
s
|
||||
Drudge Skulker
|
||||
i
|
||||
1
|
||||
i
|
||||
1
|
||||
i
|
||||
-1
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
True
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
b
|
||||
False
|
||||
i
|
||||
0
|
||||
i
|
||||
-1
|
||||
i
|
||||
101
|
||||
s
|
||||
EnableLooting
|
||||
b
|
||||
False
|
||||
s
|
||||
AttackDistance
|
||||
d
|
||||
0.3
|
||||
s
|
||||
MinimumRingTargets
|
||||
i
|
||||
2
|
||||
s
|
||||
RingDistance
|
||||
d
|
||||
0.0166666666666667
|
||||
s
|
||||
summonpets
|
||||
b
|
||||
False
|
||||
|
|
@ -20,6 +20,9 @@ internal static class Program
|
|||
/// <summary>DungeonHazardStore's folder before Main pointed it at the scratch folder.</summary>
|
||||
public static string LiveHazardFolder { get; private set; } = "";
|
||||
|
||||
/// <summary>DungeonRouteMaker's folder (NavProfiles) before Main pointed it at the scratch folder.</summary>
|
||||
public static string LiveRouteFolder { get; private set; } = "";
|
||||
|
||||
/// <summary>CreatureProfileStore's folder before Main pointed it at the scratch folder.</summary>
|
||||
public static string LiveCreatureFolder { get; private set; } = "";
|
||||
|
||||
|
|
@ -46,6 +49,9 @@ internal static class Program
|
|||
LiveHazardTextureFolder = RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Folder;
|
||||
RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Folder = Path.Combine(TempRoot, "HazardTextures");
|
||||
RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Reload();
|
||||
// Dungeon routes (/ra dunroute, /ra dunpatrol-save, RynthAi.Routes) are saved to C:\Games\RynthSuite\RynthAi\NavProfiles.
|
||||
LiveRouteFolder = RynthCore.Plugin.RynthAi.DungeonRouteMaker.Folder;
|
||||
RynthCore.Plugin.RynthAi.DungeonRouteMaker.Folder = Path.Combine(TempRoot, "NavProfiles");
|
||||
// Appraised creatures are saved to C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json.
|
||||
LiveCreatureFolder = RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder;
|
||||
RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder = Path.Combine(TempRoot, "CreatureData");
|
||||
|
|
@ -63,6 +69,7 @@ internal static class Program
|
|||
LootWandTests.Register(runner);
|
||||
LootRaresModeTests.Register(runner);
|
||||
LootChatLineTests.Register(runner);
|
||||
ItemInfoTextColorTests.Register(runner);
|
||||
LootSurveyTests.Register(runner);
|
||||
PropertyDumpTests.Register(runner);
|
||||
T11LootTests.Register(runner);
|
||||
|
|
@ -79,12 +86,14 @@ internal static class Program
|
|||
PatrolSettingsTests.Register(runner);
|
||||
PatrolPocketTests.Register(runner);
|
||||
PatrolPortalTests.Register(runner);
|
||||
DunRouteTests.Register(runner);
|
||||
BuffTests.Register(runner);
|
||||
SpellCatalogTests.Register(runner);
|
||||
CombatMathTests.Register(runner);
|
||||
WeaponTests.Register(runner);
|
||||
RadarSnapshotTests.Register(runner);
|
||||
AmmoTests.Register(runner);
|
||||
MissileAmmoSwapTests.Register(runner);
|
||||
VTankYieldTests.Register(runner);
|
||||
OffhandTests.Register(runner);
|
||||
HandSwapTests.Register(runner);
|
||||
|
|
@ -96,10 +105,13 @@ internal static class Program
|
|||
LootRetryTimingTests.Register(runner);
|
||||
LootClaimMismatchTests.Register(runner);
|
||||
BoostNavTests.Register(runner);
|
||||
NavHeadingTests.Register(runner);
|
||||
LootNothingLineTests.Register(runner);
|
||||
ChestLootTests.Register(runner);
|
||||
ItemToolTests.Register(runner);
|
||||
VanishedItemTests.Register(runner);
|
||||
KitUsedUpTests.Register(runner);
|
||||
VitalWandGateTests.Register(runner);
|
||||
OwnCorpseTests.Register(runner);
|
||||
UseRefusalTests.Register(runner);
|
||||
CorpseKillerTests.Register(runner);
|
||||
|
|
@ -107,9 +119,13 @@ internal static class Program
|
|||
MultiTargetTests.Register(runner);
|
||||
CastSafetyTests.Register(runner);
|
||||
HealLatencyTests.Register(runner);
|
||||
HealGraceTests.Register(runner);
|
||||
HealHoldTests.Register(runner);
|
||||
BlastTests.Register(runner);
|
||||
ArcWhenClearTests.Register(runner);
|
||||
WallTests.Register(runner);
|
||||
RingTests.Register(runner);
|
||||
VtRingImportTests.Register(runner);
|
||||
CombatHookTests.Register(runner);
|
||||
UseAtLoginTests.Register(runner);
|
||||
LearnSpellsTests.Register(runner);
|
||||
|
|
@ -125,13 +141,18 @@ internal static class Program
|
|||
MonsterEditorTests.Register(runner);
|
||||
InstallPathsTests.Register(runner);
|
||||
PetRefillTests.Register(runner);
|
||||
PetSummonStopsTests.Register(runner);
|
||||
AutoStackTests.Register(runner);
|
||||
AutoVendorSplitTests.Register(runner);
|
||||
AutoVendorZeroRateTests.Register(runner);
|
||||
AutoVendorZeroPayTests.Register(runner);
|
||||
AutoVendorFoldersTests.Register(runner);
|
||||
BackAwayTests.Register(runner);
|
||||
ServerPluginForwardTests.Register(runner);
|
||||
IgnoreMonsterTests.Register(runner);
|
||||
WorldCacheTypedTests.Register(runner);
|
||||
VendorFlagTests.Register(runner);
|
||||
LootByNameTests.Register(runner);
|
||||
NavOverlayTests.Register(runner);
|
||||
ActionPacingTests.Register(runner);
|
||||
HazardEscapeTests.Register(runner);
|
||||
|
|
@ -145,12 +166,15 @@ internal static class Program
|
|||
CastNoDamageTests.Register(runner);
|
||||
ManaReserveTests.Register(runner);
|
||||
DamageRowsTests.Register(runner);
|
||||
ShieldFacingTests.Register(runner);
|
||||
NavMapEditTests.Register(runner);
|
||||
LootSpeedTests.Register(runner);
|
||||
MeleeStallTests.Register(runner);
|
||||
NativeAttackTests.Register(runner);
|
||||
ServerMenuTests.Register(runner);
|
||||
MiniRemoteMoveTests.Register(runner);
|
||||
SessionDeathTests.Register(runner);
|
||||
SessionBankProfileTests.Register(runner);
|
||||
SectionsTests.Register(runner);
|
||||
ItemsCleanTests.Register(runner);
|
||||
DeathRecallTests.Register(runner);
|
||||
|
|
@ -188,9 +212,13 @@ internal static class Program
|
|||
DifficultyTierTests.Register(runner);
|
||||
TickIsolationTests.Register(runner);
|
||||
ChoresInFightTests.Register(runner);
|
||||
AetheriaUnboxTests.Register(runner);
|
||||
CommandReplyTests.Register(runner);
|
||||
MonsterStatsTests.Register(runner);
|
||||
MetaSaveTests.Register(runner);
|
||||
MetaResumeTests.Register(runner);
|
||||
FellowOpenTests.Register(runner);
|
||||
WieldBanTests.Register(runner);
|
||||
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,8 +43,31 @@ internal static class ActionPacingTests
|
|||
private static readonly (uint Cell, float X, float Y, float Z) Me0 = (0xA9B40019u, 100f, 100f, 0f);
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
|
||||
|
||||
// The macro switched off while the player runs by hand: RynthAi leaves the character running
|
||||
// (the owner, 2026-11-07). It stops only movement of its own: autorun or a motion it turned on,
|
||||
// or the server's walk to a target or a corpse for it (Combat, Looting).
|
||||
private static void MacroStopLeavesPlayersRun()
|
||||
{
|
||||
Check.False(RynthAiPlugin.MacroStopHalts(false, "Default"), "idle, nothing of ours moving: no stop");
|
||||
Check.False(RynthAiPlugin.MacroStopHalts(false, "Buffing"), "buffing, nothing of ours moving: no stop");
|
||||
Check.False(RynthAiPlugin.MacroStopHalts(false, null), "no action yet: no stop");
|
||||
Check.True(RynthAiPlugin.MacroStopHalts(true, "Navigating"), "nav's autorun: stopped");
|
||||
Check.True(RynthAiPlugin.MacroStopHalts(false, "Combat"), "fighting (the server may be walking us to the target): stopped");
|
||||
Check.True(RynthAiPlugin.MacroStopHalts(false, "Looting"), "looting (the walk to the corpse): stopped");
|
||||
|
||||
FakeHost.Reset();
|
||||
MoveAudit.Reset();
|
||||
var host = FakeHost.Create();
|
||||
Check.False(MoveAudit.OwnMovementActive, "nothing sent: nothing of ours moving");
|
||||
host.SetAutoRunBy("Nav", true);
|
||||
Check.True(MoveAudit.OwnMovementActive, "our autorun: ours is moving");
|
||||
host.SetAutoRunBy("Nav", false);
|
||||
Check.False(MoveAudit.OwnMovementActive, "stopped again: not ours");
|
||||
}
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("macro off: the player's own running is left alone; RynthAi's movement is stopped", MacroStopLeavesPlayersRun);
|
||||
r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers);
|
||||
r.Add("pacing: the player's turn (RynthAi.Yield) holds every start, mode change and move, ends by itself, and lets what is out finish", PlayersTurn);
|
||||
r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld);
|
||||
|
|
|
|||
290
Tools/RynthCore.RynthAiHostTests/Tests/AetheriaUnboxTests.cs
Normal file
290
Tools/RynthCore.RynthAiHostTests/Tests/AetheriaUnboxTests.cs
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Unbox Aetheria When Idle (a player's request, 2026-11-01: "auto aetheria unbox when idle option").
|
||||
// ACE (Entity/Aetheria.cs): an Aetheria Mana Stone used on a Coalesced Aetheria reveals its sigil
|
||||
// ("A sigil rises ...", the name becomes "Aetheria", UseDone); the stone is not used up; busy is
|
||||
// UseDone YoureTooBusy. RynthAi does it one piece at a time, only when idle, and backs off a refusal.
|
||||
internal static class AetheriaUnboxTests
|
||||
{
|
||||
private const uint Player = TickIsolationTests.Player;
|
||||
private const uint Blue = 0x80000A51, Red = 0x80000A52, Stone = 0x80000A53, Revealed = 0x80000A54, Monster = 0x80000A55;
|
||||
private const uint ItemTypeMisc = 0x80;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("aetheria: idle with the option on, a mana stone goes on one coalesced aetheria, and the next only after its sigil rose", UnboxesOneAtATime);
|
||||
r.Add("aetheria: nothing while a monster is on us; it unboxes once the fight is over, and a fight mid-unbox takes the tick back", NotInAFight);
|
||||
r.Add("aetheria: nothing with the option off or the macro off", NothingWhenOff);
|
||||
r.Add("aetheria: a 'too busy' refusal waits 10 s, then longer; no answer at all is a failed try", RefusalBacksOff);
|
||||
r.Add("aetheria: coalesced aetheria and no mana stone: said once in chat, not again", NoStoneSaidOnce);
|
||||
r.Add("aetheria: an already revealed 'Aetheria' is left alone", RevealedLeftAlone);
|
||||
r.Add("aetheria: /ra aetheria unbox does every piece with the option and the macro off, then says how many", ManualRun);
|
||||
r.Add("aetheria: settings - off by default, saved, copied, sent to the engine face, metas reach UnboxAetheriaWhenIdle", Settings);
|
||||
}
|
||||
|
||||
private static void Item(uint id, string name, uint wcid)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = ItemTypeMisc;
|
||||
FakeHost.Wcids[id] = wcid;
|
||||
FakeHost.Containers[id] = Player;
|
||||
}
|
||||
|
||||
private static TickIsolationTests.Bot Rig(bool stone = true, bool combat = false, bool revealedOnly = false)
|
||||
{
|
||||
var bot = new TickIsolationTests.Bot(combat: combat, heal: false, arrange: () =>
|
||||
{
|
||||
FakeHost.ContentsCalls = true; // the live pack walk
|
||||
FakeHost.UseOnCalls = true;
|
||||
if (revealedOnly) Item(Revealed, "Aetheria", AetheriaUnboxer.WcidBlue);
|
||||
else
|
||||
{
|
||||
Item(Blue, AetheriaUnboxer.CoalescedName, AetheriaUnboxer.WcidBlue);
|
||||
Item(Red, AetheriaUnboxer.CoalescedName, AetheriaUnboxer.WcidRed);
|
||||
}
|
||||
if (stone) Item(Stone, AetheriaUnboxer.StoneName, AetheriaUnboxer.WcidManaStone);
|
||||
});
|
||||
foreach (uint id in new[] { Blue, Red, Stone, Revealed })
|
||||
if (FakeHost.Names.ContainsKey(id)) _ = bot.Cache[unchecked((int)id)];
|
||||
bot.S.UnboxAetheriaWhenIdle = true;
|
||||
bot.S.MonsterRange = 20;
|
||||
var unboxer = (AetheriaUnboxer)bot.Call("CreateAetheriaUnboxer", bot.S)!;
|
||||
unboxer.NowMs = () => bot.Now;
|
||||
bot.Set("_aetheriaUnboxer", unboxer);
|
||||
return bot;
|
||||
}
|
||||
|
||||
private static AetheriaUnboxer U(TickIsolationTests.Bot bot) => (AetheriaUnboxer)bot.Get("_aetheriaUnboxer")!;
|
||||
private static bool Tick(TickIsolationTests.Bot bot) => (bool)bot.Call("TickAetheriaUnbox", bot.S)!;
|
||||
|
||||
/// <summary>The server's answer to the unbox in flight: the sigil line, the new name, the UseDone.</summary>
|
||||
private static void Reveal(TickIsolationTests.Bot bot, uint id)
|
||||
{
|
||||
U(bot).OnChat(AetheriaUnboxer.SigilLine);
|
||||
FakeHost.Names[id] = "Aetheria";
|
||||
FakeHost.UseDone(0);
|
||||
}
|
||||
|
||||
private static CombatManager.ScannedTarget At(double yards) =>
|
||||
new() { Id = unchecked((int)Monster), Distance = yards, Name = "Drudge Skulker" };
|
||||
|
||||
private static void UnboxesOneAtATime()
|
||||
{
|
||||
try
|
||||
{
|
||||
var bot = Rig();
|
||||
Check.True(Tick(bot), "the unbox goes out, and the bot holds still for the clap");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "one use-on");
|
||||
var first = FakeHost.UsesOn[0];
|
||||
Check.True(first.Source == Stone && (first.Target == Blue || first.Target == Red), "the mana stone on a coalesced aetheria");
|
||||
|
||||
for (int i = 0; i < 5; i++) { bot.Now += 500; Tick(bot); }
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "no answer yet: nothing more goes out");
|
||||
|
||||
Reveal(bot, first.Target);
|
||||
Check.False(Tick(bot), "the sigil rose: the unbox is over");
|
||||
Check.Eq(U(bot).Revealed, 1, "one revealed");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[Aetheria] revealed")), "and logged");
|
||||
|
||||
bot.Now += 500;
|
||||
Tick(bot);
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "the server stays busy for the return to ready: a short pause first");
|
||||
bot.Now += AetheriaUnboxer.GapMs;
|
||||
Check.True(Tick(bot), "the next piece goes out");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 2, "two use-ons");
|
||||
var second = FakeHost.UsesOn[1];
|
||||
Check.True(second.Source == Stone && second.Target != first.Target && (second.Target == Blue || second.Target == Red),
|
||||
"the same stone (it isn't used up) on the other piece");
|
||||
|
||||
Reveal(bot, second.Target);
|
||||
Tick(bot);
|
||||
for (int i = 0; i < 20; i++) { bot.Now += 1_000; Tick(bot); }
|
||||
Check.Eq(FakeHost.UsesOn.Count, 2, "nothing coalesced left: nothing more");
|
||||
Check.Eq(U(bot).Revealed, 2, "both revealed");
|
||||
Check.False(FakeHost.Chat.Any(c => c.Contains("no Aetheria Mana Stone")), "and no out-of-stones line (the stone is still there)");
|
||||
}
|
||||
finally { TickIsolationTests.Done(); }
|
||||
}
|
||||
|
||||
private static void NotInAFight()
|
||||
{
|
||||
try
|
||||
{
|
||||
var bot = Rig(combat: true);
|
||||
var cm = (CombatManager)bot.Get("_combatManager")!;
|
||||
cm.SetScannedTargetsForTests(new[] { At(2) });
|
||||
for (int i = 0; i < 5; i++) { bot.Now += 2_000; Tick(bot); }
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "a monster on us: no unbox (the server would put us in peace mode)");
|
||||
|
||||
bot.S.EnableCombat = false;
|
||||
for (int i = 0; i < 3; i++) { bot.Now += 2_000; Tick(bot); }
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "not with Enable Combat off either: a fight by hand counts");
|
||||
bot.S.EnableCombat = true;
|
||||
|
||||
cm.SetScannedTargetsForTests(Array.Empty<CombatManager.ScannedTarget>());
|
||||
bot.Now += 2_000;
|
||||
Check.True(Tick(bot), "the fight is over: it unboxes");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "one use-on");
|
||||
|
||||
cm.SetScannedTargetsForTests(new[] { At(5) });
|
||||
Check.False(Tick(bot), "a monster comes mid-unbox: no hold, combat has the tick");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "and nothing more goes out");
|
||||
}
|
||||
finally { TickIsolationTests.Done(); }
|
||||
}
|
||||
|
||||
private static void NothingWhenOff()
|
||||
{
|
||||
try
|
||||
{
|
||||
var bot = Rig();
|
||||
bot.S.UnboxAetheriaWhenIdle = false;
|
||||
for (int i = 0; i < 5; i++) { bot.Now += 6_000; Tick(bot); }
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "the option off: nothing");
|
||||
|
||||
bot.S.UnboxAetheriaWhenIdle = true;
|
||||
bot.S.IsMacroRunning = false;
|
||||
for (int i = 0; i < 5; i++) { bot.Now += 6_000; Tick(bot); }
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "the macro off: nothing");
|
||||
|
||||
bot.S.IsMacroRunning = true;
|
||||
bot.Now += 6_000;
|
||||
Tick(bot);
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "both on: it unboxes");
|
||||
}
|
||||
finally { TickIsolationTests.Done(); }
|
||||
}
|
||||
|
||||
private static void RefusalBacksOff()
|
||||
{
|
||||
try
|
||||
{
|
||||
var bot = Rig();
|
||||
Tick(bot);
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "the first try");
|
||||
FakeHost.UseDone(AetheriaUnboxer.TooBusyErr);
|
||||
Check.False(Tick(bot), "refused as busy: over");
|
||||
|
||||
bot.Now += 9_000;
|
||||
Tick(bot);
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "9 s later: still waiting");
|
||||
bot.Now += 1_500;
|
||||
Tick(bot);
|
||||
Check.Eq(FakeHost.UsesOn.Count, 2, "past 10 s: tried again");
|
||||
|
||||
// No answer at all: a failed try after the timeout, and a longer wait (30 s).
|
||||
bot.Now += AetheriaUnboxer.UnboxTimeoutMs;
|
||||
Check.False(Tick(bot), "no answer in 10 s: given up for now");
|
||||
bot.Now += 20_000;
|
||||
Tick(bot);
|
||||
Check.Eq(FakeHost.UsesOn.Count, 2, "20 s later: the second wait is 30 s");
|
||||
bot.Now += 11_000;
|
||||
Tick(bot);
|
||||
Check.Eq(FakeHost.UsesOn.Count, 3, "past 30 s: tried again");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[Aetheria] unbox of") && l.Contains("too busy")), "the refusal is logged");
|
||||
}
|
||||
finally { TickIsolationTests.Done(); }
|
||||
}
|
||||
|
||||
private static void NoStoneSaidOnce()
|
||||
{
|
||||
try
|
||||
{
|
||||
var bot = Rig(stone: false);
|
||||
for (int i = 0; i < 6; i++) { bot.Now += 6_000; Tick(bot); }
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "no stone: nothing to use");
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("no Aetheria Mana Stone")), 1, "said once in chat");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("2 coalesced aetheria")), "with how many are waiting");
|
||||
}
|
||||
finally { TickIsolationTests.Done(); }
|
||||
}
|
||||
|
||||
private static void RevealedLeftAlone()
|
||||
{
|
||||
try
|
||||
{
|
||||
var bot = Rig(revealedOnly: true);
|
||||
for (int i = 0; i < 4; i++) { bot.Now += 6_000; Tick(bot); }
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "an 'Aetheria' (sigil showing) is not unboxed again");
|
||||
Check.True(U(bot).Describe().Contains("0 coalesced"), "status: none coalesced (" + U(bot).Describe() + ")");
|
||||
}
|
||||
finally { TickIsolationTests.Done(); }
|
||||
}
|
||||
|
||||
private static void ManualRun()
|
||||
{
|
||||
try
|
||||
{
|
||||
var bot = Rig();
|
||||
bot.S.UnboxAetheriaWhenIdle = false;
|
||||
bot.S.IsMacroRunning = false;
|
||||
var u = U(bot);
|
||||
Check.True(u.RequestManual(out string reply), "asked by hand: " + reply);
|
||||
Check.True(reply.Contains("2 coalesced"), "the reply says how many");
|
||||
Check.False(Tick(bot), "the macro is off: nothing to hold");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "but the unbox goes out");
|
||||
Reveal(bot, FakeHost.UsesOn[0].Target);
|
||||
Tick(bot);
|
||||
bot.Now += AetheriaUnboxer.GapMs;
|
||||
Tick(bot);
|
||||
Check.Eq(FakeHost.UsesOn.Count, 2, "the second piece");
|
||||
Reveal(bot, FakeHost.UsesOn[1].Target);
|
||||
Tick(bot);
|
||||
bot.Now += AetheriaUnboxer.GapMs;
|
||||
Tick(bot);
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Aetheria: revealed 2")), "the run ends with how many: " + string.Join(" | ", FakeHost.Chat));
|
||||
Check.False(u.ManualRun, "and is over");
|
||||
Check.False(u.RequestManual(out string none), "nothing left to unbox: refused");
|
||||
Check.True(none.Contains("no Coalesced Aetheria"), "with the reason: " + none);
|
||||
}
|
||||
finally { TickIsolationTests.Done(); }
|
||||
}
|
||||
|
||||
private static void Settings()
|
||||
{
|
||||
Check.False(new LegacyUiSettings().UnboxAetheriaWhenIdle, "off by default");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableAutostack\":true}", RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.False(old.UnboxAetheriaWhenIdle, "a profile from before the setting: off");
|
||||
var saved = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { UnboxAetheriaWhenIdle = true }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.True(saved.UnboxAetheriaWhenIdle, "on saves and loads");
|
||||
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { UnboxAetheriaWhenIdle = true }, dst });
|
||||
Check.True(dst.UnboxAetheriaWhenIdle, "a profile switch copies it");
|
||||
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.UnboxAetheriaWhenIdle == null, "an older engine's payload has no value");
|
||||
var s = new LegacyUiSettings { UnboxAetheriaWhenIdle = true };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); // a stand-in with its profile in memory
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent != null && sent.UnboxAetheriaWhenIdle == true, "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.True(s.UnboxAetheriaWhenIdle, "an engine save without the field leaves it");
|
||||
dash.ApplySettingsJson("{\"UnboxAetheriaWhenIdle\":false}");
|
||||
Check.False(s.UnboxAetheriaWhenIdle, "an engine save with it sets it");
|
||||
|
||||
var ms = new LegacyUiSettings();
|
||||
var e = ExpressionTests.Engine(settings: ms);
|
||||
Check.Eq(e.Evaluate("vtsetsetting[UnboxAetheriaWhenIdle, 1]"), "1", "metas: vtsetsetting knows it");
|
||||
Check.True(ms.UnboxAetheriaWhenIdle, "and turns it on");
|
||||
Check.Eq(e.Evaluate("vtgetsetting[UnboxAetheriaWhenIdle]"), "1", "vtgetsetting reads it back");
|
||||
}
|
||||
}
|
||||
|
|
@ -13,6 +13,43 @@ internal static class AutoStackTests
|
|||
{
|
||||
r.Add("autostack: stacks group by WCID; the name is only the fallback while the WCID is unknown", GroupKey);
|
||||
r.Add("autostack: a partial fill (target grew, source shrank) is progress; an untouched pair is not", Progress);
|
||||
r.Add("autostack: name guesses match pyreals exactly and the rest as whole words (Pyreal Mote, Spear, Pearl don't stack)", NameGuess);
|
||||
r.Add("autostack: a guessed group the server refuses 3 times running is given up; a merge between resets it", Refusals);
|
||||
}
|
||||
|
||||
private static void NameGuess()
|
||||
{
|
||||
Check.Eq(25000, InventoryManager.NameFallbackMaxStack("Pyreal"), "pyreal coins");
|
||||
Check.Eq(25000, InventoryManager.NameFallbackMaxStack("Pyreals"), "pyreal coins, plural");
|
||||
Check.Eq(1, InventoryManager.NameFallbackMaxStack("Pyreal Mote"), "2026-11-08: motes don't stack");
|
||||
Check.Eq(1, InventoryManager.NameFallbackMaxStack("Quality Pyreal Ingot"), "ingots don't stack");
|
||||
Check.Eq(1, InventoryManager.NameFallbackMaxStack("Spear"), "'pea' inside a word");
|
||||
Check.Eq(1, InventoryManager.NameFallbackMaxStack("Black Pearl"), "'pea' inside a word");
|
||||
Check.Eq(1, InventoryManager.NameFallbackMaxStack("Arrowheads"), "'arrow' inside a word");
|
||||
Check.Eq(250, InventoryManager.NameFallbackMaxStack("Greater Deadly Armor Piercing Arrow"), "arrows");
|
||||
Check.Eq(250, InventoryManager.NameFallbackMaxStack("Deadly Fire Quarrel"), "quarrels");
|
||||
Check.Eq(100, InventoryManager.NameFallbackMaxStack("Iron Scarab"), "scarabs");
|
||||
Check.Eq(100, InventoryManager.NameFallbackMaxStack("Prismatic Taper"), "tapers");
|
||||
Check.Eq(1, InventoryManager.NameFallbackMaxStack(null), "no name");
|
||||
Check.Eq(1, InventoryManager.NameFallbackMaxStack(" "), "blank name");
|
||||
}
|
||||
|
||||
private static void Refusals()
|
||||
{
|
||||
var r = new StackGroupRefusals();
|
||||
Check.False(r.Refused("w:6353"), "1st refusal");
|
||||
Check.False(r.Refused("w:6353"), "2nd refusal");
|
||||
Check.False(r.GivenUp("w:6353"), "not yet");
|
||||
Check.True(r.Refused("w:6353"), "3rd refusal gives it up, once");
|
||||
Check.True(r.GivenUp("w:6353"), "given up");
|
||||
Check.False(r.Refused("w:6353"), "already given up: no second notice");
|
||||
|
||||
Check.False(r.Refused("w:1"), "other group 1st");
|
||||
Check.False(r.Refused("w:1"), "other group 2nd");
|
||||
r.Merged("w:1");
|
||||
Check.False(r.Refused("w:1"), "a merge between resets the count");
|
||||
Check.False(r.GivenUp("w:1"), "the other group goes on");
|
||||
Check.False(r.Refused(""), "an empty group never counts");
|
||||
}
|
||||
|
||||
private static void GroupKey()
|
||||
|
|
|
|||
246
Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorFoldersTests.cs
Normal file
246
Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorFoldersTests.cs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.Plugin.RynthAi.Vendor;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-11-04 (Discord): "Autovendor creates folders for each server, but it only reads from the
|
||||
// parent folder". A vendor's run looked in the character, server and main folders (UB's order),
|
||||
// but everything a player sees or picks named the main folder only: the Loot Editor's picker listed
|
||||
// AutoVendor and its server folders as one tree and never the character folder, the dashboard's
|
||||
// Edit on a vendor with no profile made the new one in the main folder, beside the server folder
|
||||
// AutoVendor had just made, and "No vendor profile exists" gave the main folder's path alone.
|
||||
//
|
||||
// AutoVendorManager.MainProfileDir points at the scratch folder here; FakeHost.WorldName is the server.
|
||||
internal static unsafe class AutoVendorFoldersTests
|
||||
{
|
||||
private const uint Player = 0x50000B01;
|
||||
private const uint Vendor = 0x70000B01;
|
||||
private const string VendorFile = "Town Vendor.utl";
|
||||
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("autovendor folders: a profile only in AutoVendor\\<server> is found, for the run and the Edit button", ServerFolderFound);
|
||||
r.Add("autovendor folders: character folder, then server, then main (named profiles before default.utl)", UbOrder);
|
||||
r.Add("autovendor folders: the folders a vendor open makes are the ones read (a server name with a bad file character)", MadeFoldersAreRead);
|
||||
r.Add("autovendor folders: a vendor with no profile gets its new one in the server folder (main before the server is known)", NewProfileInServerFolder);
|
||||
r.Add("autovendor folders: the Loot Editor lists character, server and main profiles in that order, marked by folder", PickerListsEveryFolder);
|
||||
r.Add("autovendor folders: the plugin's Loot Editor picker reads AutoVendor's folders", PluginPickerWired);
|
||||
r.Add("autovendor folders: 'No vendor profile exists' names every folder it looked in", MissingProfileNamesEveryFolder);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public AutoVendorManager M = null!;
|
||||
public string Main = "", Char = "", CharAv = "";
|
||||
public RynthCoreHost Host;
|
||||
}
|
||||
|
||||
/// <summary>A fresh main and character folder; <paramref name="world"/> is the server ("" = not known).</summary>
|
||||
private static Rig World(string world, FakeHost.ApiHook? api = null)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.ConfigureApi = api;
|
||||
FakeHost.WorldName = world;
|
||||
FakeHost.Names[Player] = "Test Seller";
|
||||
FakeHost.Names[Vendor] = "Town Vendor";
|
||||
string root = Path.Combine(Program.TempRoot, "avfolders-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
var rig = new Rig { Main = Path.Combine(root, "AutoVendor"), Char = Path.Combine(root, "SettingsProfiles", "Srv", "Char") };
|
||||
rig.CharAv = Path.Combine(rig.Char, AutoVendorManager.ProfileSubfolder);
|
||||
AutoVendorManager.MainProfileDirOverride = rig.Main;
|
||||
rig.Host = FakeHost.Create(Player);
|
||||
var cache = new WorldObjectCache(rig.Host);
|
||||
cache.SetPlayerId(Player);
|
||||
// Off: the open only resolves the Edit button's profile, no session.
|
||||
var settings = new LegacyUiSettings { AutoVendorEnabled = false, AutoVendorShowMerchantInfo = false };
|
||||
string charFolder = rig.Char;
|
||||
rig.M = new AutoVendorManager(rig.Host, settings, cache, Player, () => charFolder);
|
||||
return rig;
|
||||
}
|
||||
|
||||
private static void Scoped(Action body)
|
||||
{
|
||||
string? old = AutoVendorManager.MainProfileDirOverride;
|
||||
try { body(); }
|
||||
finally { AutoVendorManager.MainProfileDirOverride = old; FakeHost.WorldName = ""; }
|
||||
}
|
||||
|
||||
private static string Put(string dir, string name)
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
string p = Path.Combine(dir, name);
|
||||
File.WriteAllText(p, "UTL\n1\n0\n");
|
||||
return p;
|
||||
}
|
||||
|
||||
private static bool Same(string? a, string b)
|
||||
=> a != null && string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void ServerFolderFound() => Scoped(() =>
|
||||
{
|
||||
var rig = World("Conquest");
|
||||
string server = Path.Combine(rig.Main, "Conquest");
|
||||
string p = Put(server, VendorFile);
|
||||
Put(rig.Main, "Other Vendor.utl"); // something in the main folder that isn't this vendor's
|
||||
|
||||
Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), p), "the run's lookup finds AutoVendor\\Conquest\\" + VendorFile);
|
||||
rig.M.OnVendorOpen(Vendor);
|
||||
Check.True(Same(rig.M.OpenVendorProfilePath, p), "the Edit button opens the server folder's profile: " + rig.M.OpenVendorProfilePath);
|
||||
Check.True(Same(rig.M.ResolveProfilePath("Town Vendor", true), p), "/ub autovendor Town Vendor (no .utl) finds it too");
|
||||
});
|
||||
|
||||
private static void UbOrder() => Scoped(() =>
|
||||
{
|
||||
var rig = World("Conquest");
|
||||
string server = Path.Combine(rig.Main, "Conquest");
|
||||
string inChar = Put(rig.CharAv, VendorFile);
|
||||
string inServer = Put(server, VendorFile);
|
||||
string inMain = Put(rig.Main, VendorFile);
|
||||
|
||||
Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), inChar), "the character folder wins");
|
||||
File.Delete(inChar);
|
||||
Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), inServer), "then the server folder");
|
||||
File.Delete(inServer);
|
||||
Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), inMain), "the main folder last");
|
||||
|
||||
// UB: the vendor's own profile in any folder before default.utl in any folder.
|
||||
string serverDefault = Put(server, "default.utl");
|
||||
Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), inMain), "a named profile in main beats default.utl in the server folder");
|
||||
File.Delete(inMain);
|
||||
Put(rig.Main, "default.utl");
|
||||
Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), serverDefault), "the server's default.utl before main's");
|
||||
|
||||
List<string> dirs = rig.M.ProfileDirs();
|
||||
Check.Eq(dirs.Count, 3, "three folders");
|
||||
Check.True(dirs.Count == 3 && Same(dirs[0], rig.CharAv) && Same(dirs[1], server) && Same(dirs[2], rig.Main),
|
||||
"ProfileDirs: character, server, main: " + string.Join(" | ", dirs));
|
||||
});
|
||||
|
||||
private static void MadeFoldersAreRead() => Scoped(() =>
|
||||
{
|
||||
var rig = World("Dream:Weave ");
|
||||
rig.M.OnVendorOpen(Vendor); // EnsureProfileFolders
|
||||
string made = Path.Combine(rig.Main, "Dream_Weave");
|
||||
Check.True(Directory.Exists(made), "the server folder is made with the name's bad character replaced");
|
||||
Check.True(Directory.Exists(rig.CharAv), "the character's AutoVendor folder is made");
|
||||
var dirs = rig.M.ProfileDirs();
|
||||
Check.True(dirs.Any(d => Same(d, made)) && dirs.Any(d => Same(d, rig.CharAv)), "and both are read: " + string.Join(" | ", dirs));
|
||||
string p = Put(made, VendorFile);
|
||||
Check.True(Same(rig.M.ResolveProfilePath(VendorFile, false), p), "a profile put in the made folder is found");
|
||||
});
|
||||
|
||||
private static void NewProfileInServerFolder() => Scoped(() =>
|
||||
{
|
||||
var rig = World("Conquest");
|
||||
rig.M.OnVendorOpen(Vendor);
|
||||
string expect = Path.Combine(rig.Main, "Conquest", VendorFile);
|
||||
Check.True(Same(rig.M.OpenVendorProfilePath, expect), "Edit with no profile anywhere: a new one in AutoVendor\\Conquest: " + rig.M.OpenVendorProfilePath);
|
||||
Check.True(Directory.Exists(Path.GetDirectoryName(expect)!), "its folder exists, so Save can create it");
|
||||
|
||||
var unknown = World("");
|
||||
Check.True(Same(unknown.M.ResolveProfilePath(VendorFile, false), Path.Combine(unknown.Main, VendorFile)),
|
||||
"no server name: the main folder, as UB");
|
||||
});
|
||||
|
||||
private static List<LootEditFile> VendorFiles(LootEditorBridge b)
|
||||
{
|
||||
LootEditState s = JsonSerializer.Deserialize(b.StateJson(), LootEditJsonContext.Default.LootEditState)!;
|
||||
return s.Files.Where(f => f.Display.StartsWith("AutoVendor", StringComparison.Ordinal)).ToList();
|
||||
}
|
||||
|
||||
private static void PickerListsEveryFolder() => Scoped(() =>
|
||||
{
|
||||
var rig = World("Conquest");
|
||||
string inChar = Put(rig.CharAv, VendorFile);
|
||||
string inServer = Put(Path.Combine(rig.Main, "Conquest"), "default.utl");
|
||||
string inMain = Put(rig.Main, "default.utl");
|
||||
string otherServer = Put(Path.Combine(rig.Main, "DreamWeave"), "Elder Vendor.utl");
|
||||
|
||||
var b = new LootEditorBridge(() => string.Empty, _ => { }, () => rig.M.ProfileDirs());
|
||||
List<LootEditFile> files = VendorFiles(b);
|
||||
string shown = string.Join(" | ", files.Select(f => f.Display));
|
||||
Check.Eq(files.Count, 4, "four AutoVendor profiles: " + shown);
|
||||
if (files.Count != 4) return;
|
||||
Check.True(Same(files[0].Path, inChar), "the character folder's first");
|
||||
Check.Eq(files[0].Display, "AutoVendor (character): " + VendorFile, "marked as the character's");
|
||||
Check.True(Same(files[1].Path, inServer), "then this server's");
|
||||
Check.Eq(files[1].Display, "AutoVendor (Conquest): default.utl", "marked by the server's folder");
|
||||
Check.True(Same(files[2].Path, inMain), "then the main folder's");
|
||||
Check.Eq(files[2].Display, "AutoVendor: default.utl", "the main folder keeps the plain mark");
|
||||
Check.True(Same(files[3].Path, otherServer), "other servers' folders last");
|
||||
Check.Eq(files[3].Display, "AutoVendor (DreamWeave): Elder Vendor.utl", "marked by their folder");
|
||||
Check.False(shown.Contains("Srv") || shown.Contains("Char"), "the character's name and folder path aren't in the picker");
|
||||
});
|
||||
|
||||
private static void PluginPickerWired() => Scoped(() =>
|
||||
{
|
||||
var rig = World("Conquest");
|
||||
string inChar = Put(rig.CharAv, VendorFile);
|
||||
string inServer = Put(Path.Combine(rig.Main, "Conquest"), VendorFile);
|
||||
|
||||
var plugin = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
|
||||
typeof(RynthAiPlugin).GetField("_autoVendor", Any)!.SetValue(plugin, rig.M);
|
||||
List<LootEditFile> files = VendorFiles(plugin.LootEditor);
|
||||
Check.True(files.Any(f => Same(f.Path, inChar)), "the character folder's profile is listed: " + string.Join(" | ", files.Select(f => f.Display)));
|
||||
Check.True(files.Any(f => Same(f.Path, inServer)), "the server folder's profile is listed");
|
||||
});
|
||||
|
||||
// The engine's vendor calls, present but with no vendor to show: enough for a session to start.
|
||||
private static void VendorCalls(ref RynthCoreApiNative api)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 82u);
|
||||
api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorInfoNative*, int>)&NoVendorInfo;
|
||||
api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorItemNative*, int, int>)&NoVendorItems;
|
||||
api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, VendorTradeEntryNative*, int, uint>)&NoBuy;
|
||||
api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, uint>)&NoSell;
|
||||
api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorTradeStatusNative*, int>)&NoTradeStatus;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int NoVendorInfo(VendorInfoNative* info) => 0;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int NoVendorItems(VendorItemNative* items, int max) => 0;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint NoBuy(uint vendor, VendorTradeEntryNative* entries, int count) => 0;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint NoSell(uint vendor, uint* ids, int count) => 0;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int NoTradeStatus(VendorTradeStatusNative* status) => 0;
|
||||
|
||||
private static void MissingProfileNamesEveryFolder() => Scoped(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var rig = World("Conquest", VendorCalls);
|
||||
var settings = new LegacyUiSettings { AutoVendorEnabled = true, AutoVendorShowMerchantInfo = false };
|
||||
string charFolder = rig.Char;
|
||||
var m = new AutoVendorManager(rig.Host, settings, new WorldObjectCache(rig.Host), Player, () => charFolder);
|
||||
m.OnVendorOpen(Vendor);
|
||||
string line = FakeHost.Chat.FirstOrDefault(c => c.Contains("No vendor profile exists")) ?? string.Empty;
|
||||
Check.True(line.Length > 0, "a vendor with no profile says so: " + string.Join(" / ", FakeHost.Chat));
|
||||
Check.True(line.Contains(VendorFile) && line.Contains("default.utl"), "the names it looked for: " + line);
|
||||
Check.True(line.Contains(rig.CharAv) && line.Contains(Path.Combine(rig.Main, "Conquest")) && line.Contains(rig.Main),
|
||||
"the character, server and main folders: " + line);
|
||||
}
|
||||
finally { FakeHost.ConfigureApi = null; }
|
||||
});
|
||||
}
|
||||
148
Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorZeroPayTests.cs
Normal file
148
Tools/RynthCore.RynthAiHostTests/Tests/AutoVendorZeroPayTests.cs
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Vendor;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The engine trades with zero-rate vendors (a free storage vault, buy=0 sell=0). A vendor that pays
|
||||
/// nothing for items (buy rate 0) met with default.utl gets nothing sold to it: that profile's Sell
|
||||
/// rules turn loot into pyreals, and would hand every match over for nothing. The vendor's own
|
||||
/// profile (or one named on /ub autovendor) sells as written, so a vault can still be filled.
|
||||
/// TestMode shows the plan without trading.
|
||||
/// </summary>
|
||||
internal static unsafe class AutoVendorZeroPayTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const uint Vendor = 0x70000D01;
|
||||
private const string PaysNothing = "pays nothing for items";
|
||||
|
||||
private static float _buyRate, _sellRate;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("autovendor zero pay: a vendor paying nothing, met with default.utl, gets nothing sold (said once, held back in TestMode)", DefaultProfileSellsNothing);
|
||||
r.Add("autovendor zero pay: the vendor's own profile still sells to a zero-rate vault", OwnProfileSells);
|
||||
r.Add("autovendor zero pay: a profile named on /ub autovendor counts as the vendor's own", NamedProfileSells);
|
||||
r.Add("autovendor zero pay: a vendor that pays (buy rate above 0) is as before with default.utl", PayingVendorUnchanged);
|
||||
}
|
||||
|
||||
private static void VendorCalls(ref RynthCoreApiNative api)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 82u);
|
||||
api.GetVendorInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorInfoNative*, int>)&GetVendorInfo;
|
||||
api.GetVendorItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorItemNative*, int, int>)&NoVendorItems;
|
||||
api.VendorBuyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, VendorTradeEntryNative*, int, uint>)&NoBuy;
|
||||
api.VendorSellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, uint>)&NoSell;
|
||||
api.GetVendorTradeStatusFn = (IntPtr)(delegate* unmanaged[Cdecl]<VendorTradeStatusNative*, int>)&NoTradeStatus;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetVendorInfo(VendorInfoNative* info)
|
||||
{
|
||||
*info = default;
|
||||
info->VendorId = Vendor;
|
||||
info->ItemTypes = 0xFFFFFFFF;
|
||||
info->MaxValue = 1_000_000;
|
||||
info->BuyRate = _buyRate;
|
||||
info->SellRate = _sellRate;
|
||||
info->Flags = 1; // trading available
|
||||
byte[] name = Encoding.ASCII.GetBytes("Town Vendor");
|
||||
for (int i = 0; i < name.Length; i++) info->Name[i] = name[i];
|
||||
return 1;
|
||||
}
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int NoVendorItems(VendorItemNative* items, int max) => 0;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint NoBuy(uint vendor, VendorTradeEntryNative* entries, int count) => 0;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint NoSell(uint vendor, uint* ids, int count) => 0;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int NoTradeStatus(VendorTradeStatusNative* status) => 0;
|
||||
|
||||
/// <summary>Runs one TestMode session at the vendor with <paramref name="profileFile"/> in the main folder.</summary>
|
||||
private static void Session(float buy, float sell, string profileFile, Action<AutoVendorManager>? start = null)
|
||||
{
|
||||
_buyRate = buy;
|
||||
_sellRate = sell;
|
||||
FakeHost.Reset();
|
||||
FakeHost.ConfigureApi = VendorCalls;
|
||||
FakeHost.Names[Player] = "Test Seller";
|
||||
FakeHost.Names[Vendor] = "Town Vendor";
|
||||
string root = Path.Combine(Program.TempRoot, "avzero-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
string main = Path.Combine(root, "AutoVendor");
|
||||
Directory.CreateDirectory(main);
|
||||
File.WriteAllText(Path.Combine(main, profileFile), "UTL\n1\n0\n");
|
||||
AutoVendorManager.MainProfileDirOverride = main;
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
var settings = new LegacyUiSettings
|
||||
{
|
||||
AutoVendorEnabled = start == null, AutoVendorEnableSelling = true, AutoVendorTestMode = true, AutoVendorShowMerchantInfo = false,
|
||||
};
|
||||
string charFolder = Path.Combine(root, "Char");
|
||||
var m = new AutoVendorManager(host, settings, cache, Player, () => charFolder);
|
||||
long now = 1_000_000;
|
||||
AutoVendorManager.Clock = () => now;
|
||||
m.OnVendorOpen(Vendor);
|
||||
if (start != null) { settings.AutoVendorEnabled = true; start(m); }
|
||||
for (int i = 0; i < 10; i++) { now += 250; m.Tick(0); }
|
||||
}
|
||||
|
||||
private static void Scoped(Action body)
|
||||
{
|
||||
string? oldDir = AutoVendorManager.MainProfileDirOverride;
|
||||
var oldClock = AutoVendorManager.Clock;
|
||||
try { body(); }
|
||||
finally { AutoVendorManager.MainProfileDirOverride = oldDir; AutoVendorManager.Clock = oldClock; FakeHost.ConfigureApi = null; }
|
||||
}
|
||||
|
||||
private static string AllChat() => string.Join(" / ", FakeHost.Chat);
|
||||
private static bool Said(string text) => FakeHost.Chat.Any(c => c.Contains(text, StringComparison.Ordinal));
|
||||
|
||||
private static void DefaultProfileSellsNothing() => Scoped(() =>
|
||||
{
|
||||
foreach (float sell in new[] { 1.15f, 0f }) // a shop that pays nothing, and a vault
|
||||
{
|
||||
Session(0f, sell, "default.utl");
|
||||
Check.True(Said("TestMode is on"), $"sell {sell}: the TestMode session ran: " + AllChat());
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains(PaysNothing, StringComparison.Ordinal)), 1, $"sell {sell}: said once, at the start: " + AllChat());
|
||||
Check.True(Said("Town Vendor.utl"), $"sell {sell}: and names the profile to make");
|
||||
Check.True(Said("Held back (never sold):") && Said("everything - Town Vendor pays nothing"), $"sell {sell}: TestMode shows everything held back");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains(PaysNothing, StringComparison.Ordinal)), $"sell {sell}: in the log too");
|
||||
}
|
||||
});
|
||||
|
||||
private static void OwnProfileSells() => Scoped(() =>
|
||||
{
|
||||
Session(0f, 0f, "Town Vendor.utl");
|
||||
Check.True(Said("TestMode is on"), "the TestMode session ran: " + AllChat());
|
||||
Check.False(Said(PaysNothing), "the vendor's own profile: no 'pays nothing' line");
|
||||
Check.False(Said("everything - "), "nothing held back for the rate");
|
||||
});
|
||||
|
||||
private static void NamedProfileSells() => Scoped(() =>
|
||||
{
|
||||
Session(0f, 0f, "default.utl", m => m.CommandAutoVendor("default"));
|
||||
Check.True(Said("TestMode is on"), "the TestMode session ran: " + AllChat());
|
||||
Check.False(Said(PaysNothing), "a profile named on the command: no 'pays nothing' line");
|
||||
});
|
||||
|
||||
private static void PayingVendorUnchanged() => Scoped(() =>
|
||||
{
|
||||
Session(0.7f, 1.15f, "default.utl");
|
||||
Check.True(Said("TestMode is on"), "the TestMode session ran: " + AllChat());
|
||||
Check.False(Said(PaysNothing), "a vendor that pays: no 'pays nothing' line");
|
||||
Check.False(Said("everything - "), "nothing held back for the rate");
|
||||
});
|
||||
}
|
||||
|
|
@ -46,6 +46,7 @@ internal static class ChestLootTests
|
|||
r.Add("chest loot: reopening the chest loots it again (never marked done)", ReopenLootsAgain);
|
||||
r.Add("chest loot: a salvage-only item is left when no UST is carried, as on corpses", SalvageWithoutUstLeft);
|
||||
r.Add("chest loot: opened mid-fight it waits for combat, then is looted if still open", ChestWaitsForCombat);
|
||||
r.Add("chest loot: an open chest is looted before a fight further than 5 yd off (a chest closes when you walk away)", OpenChestBeforeDistantFight);
|
||||
r.Add("chest loot: closed by the player mid-loot -> session ends, chest not reopened", ClosedMidLootNotReopened);
|
||||
r.Add("chest loot: a chest gets 2 minutes (not the 12 s corpse timeout), restarted by each pickup", ChestTimeoutLongAndRestarted);
|
||||
}
|
||||
|
|
@ -482,6 +483,56 @@ internal static class ChestLootTests
|
|||
Check.Eq(FakeHost.Closes.Count, 1, "looted and closed after the fight");
|
||||
}
|
||||
|
||||
private const uint Monster = 0x80263301;
|
||||
|
||||
/// <summary>The chest world with a monster <paramref name="meters"/> off and combat on.</summary>
|
||||
private static Bot ChestWithMonster(float meters, out CombatManager combat)
|
||||
{
|
||||
BaseWorld("Unearthed Cache");
|
||||
FakeHost.Names[Monster] = "Drumtaken Ironstone Golem";
|
||||
FakeHost.ItemTypes[Monster] = 0x10; // creature
|
||||
FakeHost.Positions[Monster] = (Me0.Cell, Me0.X + meters, Me0.Y + 0.5f, Me0.Z);
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.S.EnableCombat = true;
|
||||
bot.S.MonsterRange = 50;
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
_ = bot.Cache[unchecked((int)Monster)];
|
||||
bot.Cache.OnUpdateHealth(Monster, 1f);
|
||||
bot.Cache.Tick();
|
||||
combat = new CombatManager(host, bot.S, bot.Cache);
|
||||
combat.SetPlayerId(Player);
|
||||
typeof(CombatManager).GetField("_lastScanTime", Any)?.SetValue(combat, DateTime.MinValue);
|
||||
combat.ScanNearbyTargets();
|
||||
bot.Set("_combatManager", combat);
|
||||
return bot;
|
||||
}
|
||||
|
||||
// 2026-11-07: a meta opened a treasure cache with a golem 32 m off; combat walked to the golem, the
|
||||
// cache closed and nothing was taken.
|
||||
private static void OpenChestBeforeDistantFight()
|
||||
{
|
||||
var bot = ChestWithMonster(30f, out var combat);
|
||||
Check.True(combat.HasEngageableTarget, "a monster 30 m off: combat wants the tick");
|
||||
Check.False((bool)bot.Call("IsOpenChestTurn", true, true)!, "no chest open: no chest turn");
|
||||
bot.ServerOpens(Chest);
|
||||
Check.True(bot.HasLootWork(), "the open chest wants the tick");
|
||||
Check.True((bool)bot.Call("IsOpenChestTurn", true, true)!, "open chest, nothing within 5 yd: the chest goes first");
|
||||
Check.False((bool)bot.Call("IsOpenChestTurn", false, true)!, "(only when there is loot work)");
|
||||
var inputs = new ArbiterInputs(true, false, true, true, false, false, lootStarved: true);
|
||||
Check.Eq(ActivityArbiter.Decide(in inputs), BotActivity.Looting, "the arbiter gives Looting the tick");
|
||||
bot.Set("_lootStarveTurn", true);
|
||||
LootGemAndFinish(bot, Gem);
|
||||
Check.True(FakeHost.Closes.Count >= 1, "the gem taken before the fight, the chest closed");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("looted before the fight")), "logged");
|
||||
Check.Eq(bot.Get<uint>("_lastChestLootedId"), Chest, "ralastchestlooted[] names the chest looted to the end");
|
||||
|
||||
var close = ChestWithMonster(2f, out var combat2);
|
||||
Check.True(combat2.HasCloseThreat(RynthAiPlugin.LootStarveCloseYards), "a monster within 5 yd");
|
||||
close.ServerOpens(Chest);
|
||||
Check.False((bool)close.Call("IsOpenChestTurn", true, true)!, "a monster at the chest is fought first");
|
||||
}
|
||||
|
||||
private static void ClosedMidLootNotReopened()
|
||||
{
|
||||
BaseWorld();
|
||||
|
|
@ -499,6 +550,7 @@ internal static class ChestLootTests
|
|||
Check.False(FakeHost.Uses.Contains(Chest), "the chest is never reopened by the looter");
|
||||
Check.Eq(FakeHost.Closes.Count, 0, "nothing to close: it is closed already");
|
||||
Check.False(bot.Marked(Chest), "and not marked: opening it again loots it");
|
||||
Check.Eq(bot.Get<uint>("_lastChestLootedId"), 0u, "a chest closed mid-loot doesn't count as looted (a meta opens it again)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Chest loot:") && l.Contains("before looting finished")), "logged");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,6 +53,8 @@ internal static class CombatHookTests
|
|||
r.Add("combat hook: a script answer at an ignored monster is rejected, even one hitting us (RynthAi casts its own)", HookRejectsIgnoredTarget);
|
||||
r.Add("combat hook: a script heal (a drain) at a fight target whose rule turned to Priority 0 is rejected", HookHealRejectsIgnoredTarget);
|
||||
r.Add("blacklist: casts answered 'too busy' (UseDone 0x1D) are not no-damage casts (answered 0: the target is dropped)", RefusedCastsNotJudged);
|
||||
r.Add("loot jump: Think sends no cast while in the air after a loot jump; it casts on the landing, or at the cap", LootJumpHoldsAttack);
|
||||
r.Add("loot jump: a swing refused in the air (WeenieError 0x4EB) is not a no-damage attack (without it: a miss)", MeleeInAirNotJudged);
|
||||
r.Add("combat hook: ctx.pending is the cast in flight; ctx.last the last resolved one, err its first UseDone (final; -1 when missed or after 7 s)", LastErrIsTheCastsAnswer);
|
||||
r.Add("combat hook: an attack and a heal in flight take their UseDones in send order (attack 0x401, heal 0)", AnswersInSendOrder);
|
||||
r.Add("combat hook: a script heal refused for mana keeps its 2 s rest (no recovery fast retry)", ScriptHealNoFastRetry);
|
||||
|
|
@ -1049,9 +1051,9 @@ internal static class CombatHookTests
|
|||
private static void RefusedCastsNotJudged() => Guard(() =>
|
||||
{
|
||||
int drain = Id("Drain Health Other V");
|
||||
foreach (uint answer in new uint[] { 0, ActionPacer.TooBusyErr })
|
||||
foreach (uint answer in new uint[] { 0, ActionPacer.TooBusyErr, CombatManager.InTheAirErr })
|
||||
{
|
||||
string what = answer == 0 ? "answered 0" : "answered 0x1D";
|
||||
string what = answer == 0 ? "answered 0" : $"answered 0x{answer:X}";
|
||||
var rig = new AttackRig(setup: () => { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; });
|
||||
rig.S.BlacklistAttempts = 2;
|
||||
rig.S.EnableRaycasting = false;
|
||||
|
|
@ -1071,13 +1073,71 @@ internal static class CombatHookTests
|
|||
Check.Eq(rig.C.activeTargetId, 0, "answered 0: two no-damage casts blacklist and drop the target");
|
||||
else
|
||||
{
|
||||
Check.Eq(rig.C.activeTargetId, Target, "answered 0x1D: refusals are not casts, the target is kept");
|
||||
Check.Eq(rig.C.RefusedCastsNotJudged, 2, "both kept out of the count");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("refused 'too busy' (UseDone 0x1D): not counted")), "logged");
|
||||
Check.Eq(rig.C.activeTargetId, Target, $"{what}: refusals are not casts, the target is kept");
|
||||
Check.Eq(rig.C.RefusedCastsNotJudged, 2, $"{what}: both kept out of the count");
|
||||
Check.Eq(Field<int>(rig.C, "_consecutiveCastMisses"), 0, $"{what}: no miss counted");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains(answer == ActionPacer.TooBusyErr
|
||||
? "refused 'too busy' (UseDone 0x1D): not counted" : "refused in the air (UseDone 0x4EB): not counted")), $"{what}: logged");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// A jump-loot pickup's jump (ActionPacer.NoteLootJump) holds the attack until the landing.
|
||||
// ACE refuses a cast, swing or shot in the air (Player_Magic/Melee/Missile: IsJumping).
|
||||
private static void LootJumpHoldsAttack() => Guard(() =>
|
||||
{
|
||||
bool pacer = ActionPacer.Enabled;
|
||||
var clock = ActionPacer.NowMs;
|
||||
long t = 1_000_000;
|
||||
ActionPacer.Enabled = false; // only the air hold under test (it does not depend on the pacer switch)
|
||||
ActionPacer.NowMs = () => t;
|
||||
try
|
||||
{
|
||||
foreach (bool cap in new[] { false, true })
|
||||
{
|
||||
string what = cap ? "landing never seen" : "landing seen";
|
||||
var rig = new AttackRig(think: true);
|
||||
ActionPacer.ForgetLootJump();
|
||||
ActionPacer.NoteLootJump(rig.Host); // the pickup's jump, from the ground
|
||||
var ground = FakeHost.PlayerPose;
|
||||
FakeHost.PlayerPose = (ground.Cell, ground.X, ground.Y, ground.Z + 1.0f);
|
||||
rig.C.Think();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, $"{what}: no cast in the air");
|
||||
Check.Eq(rig.C.LastCombatSkipReason, "loot-jump-air", $"{what}: held for the landing");
|
||||
Check.Eq(rig.C.GetStateSnapshot().LastAttackCmd, DateTime.MinValue, $"{what}: no attack stamped");
|
||||
Check.Eq(rig.C.activeTargetId, Target, $"{what}: the target stays");
|
||||
t += ActionPacer.JumpLandMinMs + 100;
|
||||
rig.C.Think();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, $"{what}: still up: no cast");
|
||||
if (!cap)
|
||||
FakeHost.PlayerPose = ground; // landed
|
||||
else
|
||||
t += ActionPacer.JumpLandMaxMs; // up for good: the cap
|
||||
rig.C.Think();
|
||||
Check.Eq(rig.LastCast, "Flame Bolt VI", $"{what}: the cast goes at once");
|
||||
Check.Eq(Field<int>(rig.C, "_consecutiveCastMisses"), 0, $"{what}: nothing counted for the held ticks");
|
||||
}
|
||||
}
|
||||
finally { ActionPacer.Enabled = pacer; ActionPacer.NowMs = clock; ActionPacer.ForgetLootJump(); ActionPacer.Forget("test"); }
|
||||
});
|
||||
|
||||
private static void MeleeInAirNotJudged() => Guard(() =>
|
||||
{
|
||||
foreach (bool inAir in new[] { false, true })
|
||||
{
|
||||
var rig = new AttackRig(setup: () => { FakeHost.WeaponCalls = true; FakeHost.CombatModeValue = CombatMode.Melee; FakeHost.WeenieErrorCalls = true; });
|
||||
rig.S.BlacklistAttempts = 5;
|
||||
rig.S.EnableRaycasting = false; // (the raycast warm-up drops every judgement)
|
||||
rig.C.RecordOffensiveCast(Target); // a swing goes out
|
||||
if (inAir) FakeHost.WeenieError(CombatManager.InTheAirErr); // ACE: "You can't do that while in the air"
|
||||
SetField(rig.C, "_pendingJudgeCastAt", DateTime.Now.AddSeconds(-30));
|
||||
CallPrivate(rig.C, "JudgePendingCast");
|
||||
Check.Eq(Field<int>(rig.C, "_consecutiveCastMisses"), inAir ? 0 : 1,
|
||||
inAir ? "refused in the air: not a miss" : "control, no refusal: a no-damage swing is a miss");
|
||||
if (inAir) Check.True(FakeHost.Logs.Any(l => l.Contains("refused in the air (0x4EB)")), "logged");
|
||||
}
|
||||
});
|
||||
|
||||
private static void LastErrIsTheCastsAnswer() => Guard(() =>
|
||||
{
|
||||
int drain = Id("Drain Health Other V");
|
||||
|
|
|
|||
|
|
@ -119,6 +119,11 @@ internal static class CommandReplyTests
|
|||
new(null, "/ra dunnav 1 2", K.Act),
|
||||
new(null, "/ra dunnav", K.Act),
|
||||
new(null, "/ra dunnav-patrol", K.Act),
|
||||
new(null, "/ra dunroute banana", K.Act),
|
||||
new(null, "/ra dunroute Hive exit to exit", K.Act), // outdoors here: "requires you to be inside a dungeon"
|
||||
new(null, "/ra dunroute info", K.Act),
|
||||
new(null, "/ra dunpatrol-save", K.Act),
|
||||
new(null, "/ra dunpatrol-save Hive patrol", K.Act), // outdoors here
|
||||
new(null, "/ra nav restart", K.Act),
|
||||
new(null, "/ra nav banana", K.Act),
|
||||
new(null, "/ra meta banana", K.Act),
|
||||
|
|
@ -158,9 +163,13 @@ internal static class CommandReplyTests
|
|||
new(null, "/ra fellowship leader", K.Act),
|
||||
new("/ra mstats reset", "/ra mstats", K.Act), // no monster selected with stats: why, and the usage
|
||||
new(null, "/ra mstats show", K.Act), // this rig's engine has no plugin windows: says so
|
||||
new("/ra aetheria off", "/ra aetheria banana", K.Act),
|
||||
new(null, "/ra aetheria unbox", K.Act), // nothing coalesced in this rig's pack: says so
|
||||
new(null, "/ra nosuchverb", K.Act),
|
||||
// ── /ra: output asked for ──
|
||||
new("/ra help", null, K.Query),
|
||||
new("/ra aetheria", null, K.Query),
|
||||
new("/ra aetheria status", null, K.Query),
|
||||
new("/ra", null, K.Query),
|
||||
new("/ra version", null, K.Query),
|
||||
new("/ra server", null, K.Query),
|
||||
|
|
@ -207,6 +216,8 @@ internal static class CommandReplyTests
|
|||
new("/ra debug", null, K.Query),
|
||||
new("/ra loot", null, K.Query),
|
||||
new("/ra hazard", null, K.Query),
|
||||
new("/ra dunroute where", null, K.Query),
|
||||
new("/ra dunroute", null, K.Query),
|
||||
new("/ra hazard list", null, K.Query),
|
||||
new("/ra hazard texture list", null, K.Query),
|
||||
new("/ra groundloot", null, K.Query),
|
||||
|
|
@ -479,6 +490,7 @@ internal static class CommandReplyTests
|
|||
Set("_combatManager", combat);
|
||||
Set("_fellowshipTracker", new FellowshipTracker());
|
||||
Set("_jumper", new Jumper(host, S, text => P.Reply.Fail(text)));
|
||||
Set("_aetheriaUnboxer", new RynthCore.Plugin.RynthAi.Loot.AetheriaUnboxer(host, S, cache) { PlayerId = () => Player });
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
|
||||
|
|
|
|||
1342
Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs
Normal file
1342
Tools/RynthCore.RynthAiHostTests/Tests/DunRouteTests.cs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -677,6 +677,13 @@ internal static class ExpressionTests
|
|||
Check.Near(s.NavOffTrackYards, 160, 1e-6, "NavOffTrackYards clamps to at least 160");
|
||||
Is(e, "vtsetsetting[AutoVendorTries, 99]", "1");
|
||||
Check.Eq(s.AutoVendorTries, 20, "AutoVendorTries clamps to 20");
|
||||
Is(e, "vtgetsetting[ChestRelockWaitSec]", "125");
|
||||
Is(e, "vtsetsetting[ChestRelockWaitSec, 30]", "1");
|
||||
Check.Eq(s.ChestRelockWaitSec, 30, "ChestRelockWaitSec (Item Tool's re-lock wait) set");
|
||||
Is(e, "vtsetsetting[ChestRelockWaitSec, 2]", "1");
|
||||
Check.Eq(s.ChestRelockWaitSec, 5, "ChestRelockWaitSec clamps to at least 5");
|
||||
Is(e, "vtsetsetting[ChestRelockWaitSec, soon]", "1");
|
||||
Check.Eq(s.ChestRelockWaitSec, 5, "unparsable leaves the value");
|
||||
Is(e, "vtsetsetting[BowArcVelocity, NaN]", "1");
|
||||
Check.True(float.IsFinite(s.BowArcVelocity), "NaN is refused");
|
||||
Is(e, "vtsetsetting[NotASetting, 7]", "1");
|
||||
|
|
|
|||
200
Tools/RynthCore.RynthAiHostTests/Tests/FellowOpenTests.cs
Normal file
200
Tools/RynthCore.RynthAiHostTests/Tests/FellowOpenTests.cs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Open fellowship on create (2026-11-04, a Discord request): with Auto Fellowship Management on, a
|
||||
// fellowship RynthAi creates is opened once it exists and this character leads it, as VTank's auto
|
||||
// fellow management does. Never a fellowship made or closed by hand.
|
||||
internal static class FellowOpenTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("fellow open: /mt fellow create, then /fellowship open once we lead it (setting on)", OpenAfterCreate);
|
||||
r.Add("fellow open: nothing opened with the setting off, or with Auto Fellowship Management off", NotWhenOff);
|
||||
r.Add("fellow open: a meta's own /fellowship create is opened too", MetaCreateLine);
|
||||
r.Add("fellow open: never when already in a fellowship, led by another, already open, or a hand-made one", NeverOthers);
|
||||
r.Add("fellow open: the wait ends when no fellowship comes", WaitEnds);
|
||||
r.Add("fellow open: on by default, a meta setting, and an older engine leaves it alone", DefaultsAndPlumbing);
|
||||
}
|
||||
|
||||
private const uint Player = 0x50000F41;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const string Open = "/fellowship open";
|
||||
|
||||
private sealed class World
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new() { AutoFellowMgmt = true };
|
||||
public bool InFellowship, IsLeader, IsOpen;
|
||||
|
||||
public World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Names[Player] = "Tester";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); // a stand-in with its profile in memory
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
P.FellowStateOverride = () => (InFellowship, IsLeader, IsOpen);
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public bool Mt(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMtCommand", Any)!.Invoke(P, new object[] { line })!;
|
||||
public bool Meta(string line) => (bool)typeof(RynthAiPlugin).GetMethod("HandleMetaChatCommand", Any)!.Invoke(P, new object[] { line })!;
|
||||
public void Tick() => typeof(RynthAiPlugin).GetMethod("TickFellowOpen", Any)!.Invoke(P, null);
|
||||
public long WaitUntil
|
||||
{
|
||||
get => (long)typeof(RynthAiPlugin).GetField("_fellowOpenUntil", Any)!.GetValue(P)!;
|
||||
set => Set("_fellowOpenUntil", value);
|
||||
}
|
||||
public int Opens => FakeHost.ChatCommands.Count(c => c == Open);
|
||||
|
||||
/// <summary>The server made the fellowship: we lead it, closed.</summary>
|
||||
public void Created() { InFellowship = true; IsLeader = true; IsOpen = false; }
|
||||
}
|
||||
|
||||
private static void OpenAfterCreate()
|
||||
{
|
||||
var w = new World();
|
||||
Check.True(w.Mt("/mt fellow create Hunters"), "/mt fellow create is handled");
|
||||
Check.True(FakeHost.ChatCommands.Contains("/fellowship create Hunters"), "the create went to the chat parser");
|
||||
w.Tick();
|
||||
Check.Eq(w.Opens, 0, "not opened before the fellowship exists");
|
||||
w.Created();
|
||||
w.Tick();
|
||||
Check.Eq(w.Opens, 1, "opened once we lead it");
|
||||
Check.True(FakeHost.ChatCommands.IndexOf("/fellowship create Hunters") < FakeHost.ChatCommands.IndexOf(Open), "after the create");
|
||||
w.Tick(); w.Tick();
|
||||
Check.Eq(w.Opens, 1, "and only once");
|
||||
|
||||
// The player closes it by hand later: it stays closed.
|
||||
w.IsOpen = false;
|
||||
for (int i = 0; i < 5; i++) w.Tick();
|
||||
Check.Eq(w.Opens, 1, "a fellowship closed by hand is not opened again");
|
||||
}
|
||||
|
||||
private static void NotWhenOff()
|
||||
{
|
||||
var w = new World();
|
||||
w.S.OpenFellowOnCreate = false;
|
||||
w.Mt("/mt fellow create Hunters");
|
||||
Check.True(FakeHost.ChatCommands.Contains("/fellowship create Hunters"), "the create still goes out");
|
||||
w.Created();
|
||||
w.Tick(); w.Tick();
|
||||
Check.Eq(w.Opens, 0, "Open fellowship on create off: nothing opened");
|
||||
|
||||
var w2 = new World();
|
||||
w2.S.AutoFellowMgmt = false; // Open fellowship on create left on (its default)
|
||||
w2.Mt("/mt fellow create Hunters");
|
||||
w2.Created();
|
||||
w2.Tick();
|
||||
Check.Eq(w2.Opens, 0, "Auto Fellowship Management off: nothing opened");
|
||||
|
||||
// Switched off while the create waits.
|
||||
var w3 = new World();
|
||||
w3.Mt("/mt fellow create Hunters");
|
||||
w3.S.OpenFellowOnCreate = false;
|
||||
w3.Tick();
|
||||
w3.S.OpenFellowOnCreate = true;
|
||||
w3.Created();
|
||||
w3.Tick();
|
||||
Check.Eq(w3.Opens, 0, "switched off before the fellowship came: nothing opened");
|
||||
}
|
||||
|
||||
private static void MetaCreateLine()
|
||||
{
|
||||
var w = new World();
|
||||
Check.False(w.Meta("/fellowship create Hunters"), "a meta's /fellowship create goes on to the chat parser");
|
||||
w.Created();
|
||||
w.Tick();
|
||||
Check.Eq(w.Opens, 1, "and is opened");
|
||||
|
||||
var w2 = new World();
|
||||
w2.Meta("/mt fellow create Hunters");
|
||||
w2.Created();
|
||||
w2.Tick();
|
||||
Check.Eq(w2.Opens, 1, "a meta's /mt fellow create is opened");
|
||||
|
||||
var w3 = new World();
|
||||
w3.Meta("/fellowship recruit Hunters");
|
||||
w3.Meta("/fellowship create");
|
||||
w3.Created();
|
||||
w3.Tick();
|
||||
Check.Eq(w3.Opens, 0, "other fellowship lines, and a create without a name, arm nothing");
|
||||
}
|
||||
|
||||
private static void NeverOthers()
|
||||
{
|
||||
// Already in a fellowship: the create fails, and the fellowship we're in isn't ours to open.
|
||||
var w = new World();
|
||||
w.Created();
|
||||
w.Mt("/mt fellow create Hunters");
|
||||
w.Tick(); w.Tick();
|
||||
Check.Eq(w.Opens, 0, "already in a fellowship: nothing opened");
|
||||
|
||||
// Someone else's fellowship turns up (we were recruited meanwhile).
|
||||
var w2 = new World();
|
||||
w2.Mt("/mt fellow create Hunters");
|
||||
w2.InFellowship = true; w2.IsLeader = false;
|
||||
w2.Tick();
|
||||
w2.IsLeader = true; // made leader later
|
||||
w2.Tick();
|
||||
Check.Eq(w2.Opens, 0, "led by another: nothing opened, and the wait is over");
|
||||
|
||||
// Already open.
|
||||
var w3 = new World();
|
||||
w3.Mt("/mt fellow create Hunters");
|
||||
w3.Created(); w3.IsOpen = true;
|
||||
w3.Tick();
|
||||
Check.Eq(w3.Opens, 0, "already open: nothing sent");
|
||||
|
||||
// A fellowship the player made without RynthAi.
|
||||
var w4 = new World();
|
||||
w4.Created();
|
||||
for (int i = 0; i < 3; i++) w4.Tick();
|
||||
Check.Eq(w4.Opens, 0, "a fellowship RynthAi didn't create is left alone");
|
||||
}
|
||||
|
||||
private static void WaitEnds()
|
||||
{
|
||||
var w = new World();
|
||||
w.Mt("/mt fellow create Hunters");
|
||||
Check.True(w.WaitUntil > 0, "the create waits");
|
||||
w.WaitUntil = Environment.TickCount64 - 1; // the wait is over
|
||||
w.Tick();
|
||||
Check.Eq(w.WaitUntil, 0L, "the wait ends");
|
||||
w.Created();
|
||||
w.Tick();
|
||||
Check.Eq(w.Opens, 0, "a fellowship made after the wait is not opened");
|
||||
}
|
||||
|
||||
private static void DefaultsAndPlumbing()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().OpenFellowOnCreate, "on by default");
|
||||
Check.False(new LegacyUiSettings().AutoFellowMgmt, "Auto Fellowship Management stays off by default, so nothing changes until it's on");
|
||||
Check.Eq(new SettingsBridgePayload().OpenFellowOnCreate, (bool?)null, "the bridge sends null when an older engine doesn't know it");
|
||||
|
||||
FakeHost.Reset();
|
||||
var s = new LegacyUiSettings();
|
||||
var m = new MetaManager(s, FakeHost.Create(), new PlayerVitalsCache());
|
||||
Check.Eq(m.Expressions.Evaluate("ragetsetting[OpenFellowOnCreate]"), "1", "metas read it");
|
||||
m.Expressions.Evaluate("rasetsetting[OpenFellowOnCreate, 0]");
|
||||
Check.False(s.OpenFellowOnCreate, "and set it");
|
||||
}
|
||||
}
|
||||
321
Tools/RynthCore.RynthAiHostTests/Tests/HealGraceTests.cs
Normal file
321
Tools/RynthCore.RynthAiHostTests/Tests/HealGraceTests.cs
Normal file
|
|
@ -0,0 +1,321 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The heal grace (ActionPacer.HealGraceMs, 2 s): a heal under a heal line no longer waits on a kit the
|
||||
// server shows no sign of taking, a kit answered with a bare UseDone, a kit nobody answered, or a busy
|
||||
// count nobody cleared. A kit with no result line used to hold every vital for 8 s (the kit wait's old
|
||||
// time limit). The animation gate and the cast gate are unchanged: a heal still waits for a gesture.
|
||||
internal static class HealGraceTests
|
||||
{
|
||||
private const uint Player = 0x50000E41;
|
||||
private const uint Corpse = 0x80068AD1;
|
||||
private const uint Kit = 0x8004BF01;
|
||||
private const uint Potion = 0x8004BF02;
|
||||
private const uint Pack = Player;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("heal grace: the kit wait ends on its line, its UseDone(0) with no line, 2 s with no sign the server took it, or 3.5 s", KitWaitVerdicts);
|
||||
r.Add("heal grace: a heal goes ahead of a kit on yourself nobody answered after 2 s; a corpse use, a potion and a non-heal still wait", PacerItemUseGrace);
|
||||
r.Add("heal grace: a plain heal still waits for the character's animation past 2 s (the animation gate is unchanged)", PacerGestureUnchanged);
|
||||
r.Add("heal grace: a live busy count holds a heal 2 s at most from its rise (not on top of the pacer's hold)", BusyCountGrace);
|
||||
r.Add("heal grace: KitPending lets a kit with no sign from the server go at 2 s (a retry)", KitNoProgressRetried);
|
||||
r.Add("heal grace: KitPending waits for a kit the server started up to 3.5 s", KitStartedWaitsToLimit);
|
||||
r.Add("heal grace: with neither GetCastBusyState nor the UseDone sequence, a kit waits the 3.5 s limit (no retry at 2 s)", KitNoSignalsWaitsToLimit);
|
||||
r.Add("heal grace: KitPending ends 700 ms after the kit's own UseDone(0) with no line; a later UseDone or a playing motion keeps it", KitAnsweredNoLine);
|
||||
}
|
||||
|
||||
private static void KitWaitVerdicts()
|
||||
{
|
||||
const double G = ActionPacer.HealGraceMs;
|
||||
Check.Eq(BuffManager.KitWaitVerdict(500, -1, -1, false, false), BuffManager.KitWaitEnd.Waiting, "500 ms, nothing yet: wait");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(G - 1, -1, -1, false, false), BuffManager.KitWaitEnd.Waiting, "just under the grace: wait");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(G, -1, -1, false, false), BuffManager.KitWaitEnd.NotTaken, "the grace with no sign from the server: let go (sent again)");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(G + 500, -1, -1, false, true), BuffManager.KitWaitEnd.Waiting, "animating now: the kit may be playing, wait");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(G + 500, -1, -1, true, false), BuffManager.KitWaitEnd.Waiting, "the heal motion was seen: wait for its line");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(3500, -1, -1, true, true), BuffManager.KitWaitEnd.TimedOut, "3.5 s whatever happened: let go");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 699, true, false), BuffManager.KitWaitEnd.Waiting, "UseDone(0) 699 ms ago, no line: wait");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 700, true, false), BuffManager.KitWaitEnd.Answered, "UseDone(0) 700 ms ago, no line: none is coming");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(1200, -1, 700, true, true), BuffManager.KitWaitEnd.Waiting, "UseDone(0) but a motion plays: another action's answer, wait");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(1200, 300, -1, true, false), BuffManager.KitWaitEnd.Waiting, "line seen 300 ms ago: the vitals grace runs");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(9000, 300, -1, true, false), BuffManager.KitWaitEnd.Waiting, "a line seen: its grace runs out even past the limit");
|
||||
Check.Eq(BuffManager.KitWaitVerdict(1200, 700, -1, true, false), BuffManager.KitWaitEnd.Landed, "line seen 700 ms ago: done");
|
||||
}
|
||||
|
||||
private static long _t;
|
||||
|
||||
private static RynthCoreHost PacedWorld()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.SalvageCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.BusyCalls = true;
|
||||
FakeHost.CombatModeValue = 2;
|
||||
FakeHost.Names[Player] = "Tester";
|
||||
FakeHost.Names[Corpse] = "Corpse of Drumtaken Ursuin";
|
||||
FakeHost.Names[Kit] = "Treated Healing Kit";
|
||||
FakeHost.Names[Potion] = "Health Draught";
|
||||
FakeHost.Bitfields[Corpse] = 0x2000;
|
||||
FakeHost.Containers[Kit] = Pack;
|
||||
FakeHost.Containers[Potion] = Pack;
|
||||
_t = 20_000_000;
|
||||
ActionPacer.Reset();
|
||||
ActionPacer.Enabled = true;
|
||||
ActionPacer.NowMs = () => _t;
|
||||
UseAudit.Reset("RynthAi", () => true);
|
||||
UseAudit.NowMs = () => _t;
|
||||
MoveAudit.Reset();
|
||||
MoveAudit.NowMs = () => _t;
|
||||
var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!;
|
||||
UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u });
|
||||
return FakeHost.Create(Player);
|
||||
}
|
||||
|
||||
private static void PaceOff()
|
||||
{
|
||||
ActionPacer.Enabled = false;
|
||||
ActionPacer.Reset();
|
||||
ActionPacer.NowMs = () => Environment.TickCount64;
|
||||
UseAudit.Reset("?", null);
|
||||
UseAudit.NowMs = () => Environment.TickCount64;
|
||||
MoveAudit.Reset();
|
||||
MoveAudit.NowMs = () => Environment.TickCount64;
|
||||
FakeHost.CastBusy = 0;
|
||||
}
|
||||
|
||||
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
|
||||
private static void PacerItemUseGrace()
|
||||
{
|
||||
try
|
||||
{
|
||||
var host = PacedWorld();
|
||||
host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself");
|
||||
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "the kit is the outstanding action");
|
||||
_t += ActionPacer.HealGraceMs - 1;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "1 ms under the grace: the heal waits for the kit's answer");
|
||||
_t += 1;
|
||||
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "at the grace: a non-heal still waits");
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at the grace: the heal goes (the kit is sent again)");
|
||||
Check.True(Logged("heal grace"), "logged");
|
||||
|
||||
// A potion (an item use with no target) keeps the pacer's own limit.
|
||||
FakeHost.UseDone(0);
|
||||
host.UseFor(Potion, "Buff", "vitals: drink");
|
||||
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "the potion is the outstanding action");
|
||||
_t += ActionPacer.HealGraceMs + 100;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a potion at 2.1 s: the heal still waits (not on yourself)");
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "answered: the heal goes");
|
||||
|
||||
// A corpse use keeps its rule: a plain heal waits for its answer (the server's turn to it).
|
||||
host.UseFor(Corpse, "Loot", "open");
|
||||
_t += 3900;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a corpse use at 3.9 s: the plain heal still waits");
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "answered: the heal goes");
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
private static void PacerGestureUnchanged()
|
||||
{
|
||||
try
|
||||
{
|
||||
var host = PacedWorld();
|
||||
FakeHost.CastBusy = 1; // the client's motion queue reads busy
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "animating: the heal waits");
|
||||
_t += ActionPacer.HealGraceMs + 500;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "2.5 s of animation: a plain heal still waits (a send into a gesture draws 'too busy')");
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "the queue reads clear: the heal goes");
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
private static void BusyCountGrace()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0, UsePotions = false };
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, v);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 0, 0);
|
||||
DateTime now = t0;
|
||||
b.Clock = () => now;
|
||||
var resets = new System.Collections.Generic.List<string>();
|
||||
b.SetStaleBusyCallback(why => resets.Add(why));
|
||||
|
||||
FakeHost.UseDoneSeq = 5;
|
||||
b.BusyCount = 1; // rises at t0: a count with no UseDone since, real as far as anyone can tell
|
||||
Check.True(b.BusyHoldsHeal(), "t=0: the count holds the heal");
|
||||
now = t0.AddMilliseconds(ActionPacer.HealGraceMs - 1);
|
||||
Check.True(b.BusyHoldsHeal(), "1 ms under the grace from the rise: held");
|
||||
now = t0.AddMilliseconds(ActionPacer.HealGraceMs);
|
||||
Check.False(b.BusyHoldsHeal(), "2 s after the rise: the heal goes");
|
||||
Check.Eq(b.StaleBusyClears, 1, "cleared once");
|
||||
Check.Eq(b.BusyCount, 0, "the count is reset");
|
||||
Check.True(resets.Count == 1 && resets[0].Contains("heal grace", StringComparison.Ordinal), "through the stale-busy callback, saying why");
|
||||
|
||||
// First asked 1.9 s after the rise (the pacer's hold): the count holds it only 0.1 s more.
|
||||
now = t0.AddMilliseconds(10_000);
|
||||
b.BusyCount = 1;
|
||||
now = t0.AddMilliseconds(11_900);
|
||||
Check.True(b.BusyHoldsHeal(), "first asked 1.9 s after the rise: held");
|
||||
now = t0.AddMilliseconds(12_000);
|
||||
Check.False(b.BusyHoldsHeal(), "2.0 s after the rise: goes (no 2 s more on top of the pacer's hold)");
|
||||
|
||||
// A count that only goes up further (1 -> 2) keeps its rise time.
|
||||
now = t0.AddMilliseconds(20_000);
|
||||
b.BusyCount = 1;
|
||||
now = t0.AddMilliseconds(21_000);
|
||||
b.BusyCount = 2;
|
||||
now = t0.AddMilliseconds(22_000);
|
||||
Check.False(b.BusyHoldsHeal(), "2 s after the first rise, 1 s after 1 -> 2: goes");
|
||||
}
|
||||
|
||||
// -- KitPending and NoteKitProgress, driven through BuffManager (real time: the kit wait reads RynthClock)
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly BuffManager B;
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly RynthCoreHost H;
|
||||
public Rig(bool serverGates = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.ServerGates = serverGates; // GetCastBusyState and the UseDone sequence
|
||||
FakeHost.LastUseDoneCalls = serverGates;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic
|
||||
var host = FakeHost.Create();
|
||||
H = host;
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false,
|
||||
};
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
B = new BuffManager(host, S, sm, v);
|
||||
B.SetCharacterSkills(skills);
|
||||
B.MarkLiveBuffsReadyForTests();
|
||||
}
|
||||
}
|
||||
|
||||
private static void SleepUntil(System.Diagnostics.Stopwatch sw, long ms)
|
||||
{
|
||||
long left = ms - sw.ElapsedMilliseconds;
|
||||
if (left > 0) System.Threading.Thread.Sleep((int)left);
|
||||
}
|
||||
|
||||
private static void KitNoProgressRetried()
|
||||
{
|
||||
var r = new Rig();
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
r.B.MarkKitUsed();
|
||||
Check.True(r.B.KitPending(), "kit just used: waiting");
|
||||
SleepUntil(sw, 1700);
|
||||
Check.True(r.B.KitPending(), "1.7 s, nothing from the server: still waiting");
|
||||
SleepUntil(sw, ActionPacer.HealGraceMs + 100);
|
||||
Check.False(r.B.KitPending(), "past the heal grace with no motion, UseDone or line: let go");
|
||||
Check.Eq(r.B.KitRetries, 1, "counted as a retry");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("shows no sign the server took it", StringComparison.Ordinal)), "logged");
|
||||
}
|
||||
|
||||
// An engine with neither GetCastBusyState nor the UseDone sequence can't show the server took a kit:
|
||||
// no retry at the heal grace (the kit may be playing), only the 3.5 s limit.
|
||||
private static void KitNoSignalsWaitsToLimit()
|
||||
{
|
||||
var r = new Rig(serverGates: false);
|
||||
Check.False(r.H.HasGetCastBusyState || r.H.HasUseDoneSeq, "the rig: neither capability");
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
r.B.MarkKitUsed();
|
||||
SleepUntil(sw, ActionPacer.HealGraceMs + 300);
|
||||
Check.True(r.B.KitPending(), "past the heal grace: still waiting (nothing could show the server took it)");
|
||||
Check.Eq(r.B.KitRetries, 0, "no retry at 2 s");
|
||||
SleepUntil(sw, 3500 + 150);
|
||||
Check.False(r.B.KitPending(), "past 3.5 s: let go");
|
||||
}
|
||||
|
||||
private static void KitStartedWaitsToLimit()
|
||||
{
|
||||
var r = new Rig();
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
r.B.MarkKitUsed();
|
||||
FakeHost.CastBusy = 1; // the heal motion plays
|
||||
r.B.OnHeartbeat(); // the heartbeat records it (NoteKitProgress)
|
||||
FakeHost.CastBusy = 0;
|
||||
SleepUntil(sw, 3300);
|
||||
Check.True(r.B.KitPending(), "the server took it: 3.3 s, still waiting for its line");
|
||||
SleepUntil(sw, 3500 + 150); // the 3.5 s limit, as a literal: the test must not follow the constant
|
||||
Check.False(r.B.KitPending(), "past 3.5 s: let go");
|
||||
Check.Eq(r.B.KitRetries, 1, "counted");
|
||||
}
|
||||
|
||||
private static void KitAnsweredNoLine()
|
||||
{
|
||||
var r = new Rig();
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
r.B.MarkKitUsed();
|
||||
FakeHost.UseDone(0); // the kit's own answer (seq + 1), no result line
|
||||
Check.True(r.B.KitPending(), "answered just now: the line could still be in flight");
|
||||
SleepUntil(sw, 550);
|
||||
Check.True(r.B.KitPending(), "550 ms after the answer: waiting");
|
||||
SleepUntil(sw, 850);
|
||||
Check.False(r.B.KitPending(), "700 ms after a UseDone(0) with no line: none is coming, let go");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("was answered (UseDone) with no result line", StringComparison.Ordinal)), "logged");
|
||||
|
||||
// Not the kit's own answer: two UseDones since the send (another action's, then one more).
|
||||
var o = new Rig();
|
||||
FakeHost.UseDoneSeq = 20;
|
||||
var sw2 = System.Diagnostics.Stopwatch.StartNew();
|
||||
o.B.MarkKitUsed();
|
||||
FakeHost.UseDone(0);
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(o.B.KitPending(), "seq + 2 is not the kit's answer");
|
||||
SleepUntil(sw2, 850);
|
||||
Check.True(o.B.KitPending(), "850 ms: still waiting (not taken as answered)");
|
||||
|
||||
// A UseDone(0) while a motion plays (the heal motion of this kit; the UseDone was another action's).
|
||||
var m = new Rig();
|
||||
FakeHost.UseDoneSeq = 30;
|
||||
var sw3 = System.Diagnostics.Stopwatch.StartNew();
|
||||
m.B.MarkKitUsed();
|
||||
FakeHost.UseDone(0);
|
||||
FakeHost.CastBusy = 1;
|
||||
Check.True(m.B.KitPending(), "answered, the motion playing: waiting");
|
||||
SleepUntil(sw3, 900);
|
||||
Check.True(m.B.KitPending(), "900 ms, the motion still playing: still waiting for the line");
|
||||
FakeHost.CastBusy = 0;
|
||||
Check.False(m.B.KitPending(), "the motion over, no line: let go");
|
||||
}
|
||||
}
|
||||
339
Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs
Normal file
339
Tools/RynthCore.RynthAiHostTests/Tests/HealHoldTests.cs
Normal file
|
|
@ -0,0 +1,339 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The Buffing hold: health under Heal At held the
|
||||
// arbiter on Buffing for 17 s with no heal landing (a used-up kit re-sent), the character stopped
|
||||
// attacking the boss and died. In a fight, 6 s under a heal line with no heal landing now hands combat
|
||||
// the tick for 5 s (BuffManager.HealHold.cs).
|
||||
internal static class HealHoldTests
|
||||
{
|
||||
private const uint Player = 0x500000B6;
|
||||
private const uint ListedKit = 0x80088BDA; // the stack the Consumables rule was added from
|
||||
private const uint Kit1 = 0x80073C1B;
|
||||
private const uint Kit2 = 0x80073C1A;
|
||||
private const string KitName = "Treated Healing Kit";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("heal hold: 6 s under a heal line with no heal landing hands combat the tick for 5 s; a heal landing holds it again", HealHoldReleases);
|
||||
r.Add("heal hold: while combat has the tick a heal makes no stance change or wand swap; a caster in Magic still casts", HealHoldNoStanceChange);
|
||||
r.Add("heal hold: a macro stop resets the hold; the first heartbeat after a restart in a fight does not release", HealHoldResetsOnMacroStop);
|
||||
r.Add("heal hold: no release at 6 s while a kit in flight is animating; a kit that never animates still releases", HealHoldWaitsForAnimatingKit);
|
||||
r.Add("heal hold: no release at 6 s while a wand wield is in flight; released once it is done", HealHoldWaitsForWield);
|
||||
r.Add("heal hold: while combat has the tick, Kit Min Success is computed in the current stance, not peace", ReleasedKitChanceNotPeace);
|
||||
r.Add("heal hold: the release logs its start, its end and the first wand swap it refuses (one line each)", HealHoldLogLines);
|
||||
r.Add("heal hold: while combat has the tick, under Emergency Heal At the kit despite Kit Min Success still goes", ReleasedEmergencyLastResortKit);
|
||||
}
|
||||
|
||||
private static void HealHoldLogLines()
|
||||
{
|
||||
var b = MeleeSpellRig(out var v, out var setNow);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 0, 50);
|
||||
setNow(t0); b.OnHeartbeat();
|
||||
setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[RynthAi] Vitals: heal hold started", StringComparison.Ordinal)), 1, "the start is logged once");
|
||||
setNow(t0.AddMilliseconds(6500)); b.CheckVitals();
|
||||
setNow(t0.AddMilliseconds(7000)); b.CheckVitals();
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("heal hold: no wand swap for Heal Self while combat has the tick", StringComparison.Ordinal)), 1,
|
||||
"the refused wand swap is logged once per release: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("heal hold", StringComparison.Ordinal))));
|
||||
setNow(t0.AddMilliseconds(11_000)); b.OnHeartbeat();
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("heal hold ended (its 5 s are over", StringComparison.Ordinal)), "the window's end is logged");
|
||||
setNow(t0.AddMilliseconds(17_000)); b.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("heal hold started", StringComparison.Ordinal)), 2, "the second release is logged");
|
||||
v.CurrentHealth = 90;
|
||||
setNow(t0.AddMilliseconds(18_000)); b.OnHeartbeat();
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("heal hold ended (health 90% is over the heal lines)", StringComparison.Ordinal)), "health back over the line ends it, logged");
|
||||
}
|
||||
|
||||
// The safety floor: a release refuses stance changes, never the last-resort kit.
|
||||
private static void ReleasedEmergencyLastResortKit()
|
||||
{
|
||||
var b = KitRig();
|
||||
FakeHost.Skills[(Player, 21)] = (10, 2); // Healing low: the kit's chance is under any real Kit Min Success
|
||||
RigSettings.KitMinSuccessPct = 95;
|
||||
RigSettings.EmergencyHealAt = 30;
|
||||
SetHealth(b, 20);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 1, 3);
|
||||
b.Clock = () => t0;
|
||||
typeof(BuffManager).GetField("_hhReleasedUntil", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
|
||||
.SetValue(b, t0.AddMilliseconds(5000)); // combat has the tick
|
||||
Check.True(b.HealHoldReleased, "the rig: released");
|
||||
Check.True(b.CheckVitals(), "20% under Emergency Heal At 30%: the vitals act");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "a kit goes out");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("despite Kit Min Success", StringComparison.Ordinal)),
|
||||
"the kit despite Kit Min Success (logged): " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("Vitals", StringComparison.Ordinal))));
|
||||
}
|
||||
|
||||
private static BuffManager MeleeSpellRig(out PlayerVitalsCache v, out Func<DateTime, DateTime> setNow, int mode = CombatMode.Melee,
|
||||
bool monsterInRange = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.CombatModeValue = mode;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic
|
||||
var host = FakeHost.Create(Player);
|
||||
var s = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 75, TopOffHP = 75, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false,
|
||||
};
|
||||
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 = 48, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, v);
|
||||
b.SetCharacterSkills(skills);
|
||||
b.MarkLiveBuffsReadyForTests();
|
||||
b.InCombatOverride = () => monsterInRange; // the boss within Monster Range
|
||||
DateTime now = new DateTime(2026, 1, 1, 12, 0, 50);
|
||||
b.Clock = () => now;
|
||||
setNow = t => now = t;
|
||||
RigSettings = s;
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>The settings of the last rig built (MeleeSpellRig or KitRig).</summary>
|
||||
private static LegacyUiSettings RigSettings = new();
|
||||
|
||||
/// <summary>A melee character with two healing kits and Life Magic untrained: kits are the only heal.</summary>
|
||||
private static BuffManager KitRig(int mode = CombatMode.Melee, bool modeCalls = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeCalls = modeCalls;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.CombatModeValue = mode;
|
||||
FakeHost.Names[Kit1] = KitName;
|
||||
FakeHost.Names[Kit2] = KitName;
|
||||
// Life Magic untrained (a read, not the capable stub): kits are the only heal, no Heal Self.
|
||||
FakeHost.Skills[(Player, 33)] = (10, 1);
|
||||
var host = FakeHost.Create(Player);
|
||||
var s = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false,
|
||||
KitMinSuccessPct = 0, PeaceModeForKits = false,
|
||||
};
|
||||
s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)ListedKit), Name = KitName, Type = "HealthKit" });
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, v);
|
||||
b.SetCharacterSkills(skills);
|
||||
b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, new[] { Kit1, Kit2 }));
|
||||
RigSettings = s;
|
||||
return b;
|
||||
}
|
||||
|
||||
private static void SetHealth(BuffManager b, int hp)
|
||||
{
|
||||
var f = typeof(BuffManager).GetField("_vitals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
|
||||
((PlayerVitalsCache)f.GetValue(b)!).CurrentHealth = (uint)hp;
|
||||
}
|
||||
|
||||
// HeartbeatCore returns before TickHealHold while the macro is off, so the hold's timer must be reset
|
||||
// there: a restart in a fight (the HP failsafe's recall turning it back on, too) released at once.
|
||||
private static void HealHoldResetsOnMacroStop()
|
||||
{
|
||||
var b = MeleeSpellRig(out _, out var setNow, CombatMode.Magic);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 0, 50);
|
||||
setNow(t0); b.OnHeartbeat();
|
||||
setNow(t0.AddMilliseconds(5000)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "5 s under the line: held");
|
||||
RigSettings.IsMacroRunning = false;
|
||||
setNow(t0.AddMilliseconds(10_000)); b.OnHeartbeat();
|
||||
RigSettings.IsMacroRunning = true;
|
||||
setNow(t0.AddMilliseconds(15_000)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "macro back on in the fight: the vitals hold the tick (a fresh count)");
|
||||
Check.Eq(b.HealHoldReleases, 0, "no release on the first heartbeat after the restart");
|
||||
setNow(t0.AddMilliseconds(20_900)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "5.9 s after the restart: still held");
|
||||
setNow(t0.AddMilliseconds(21_000)); b.OnHeartbeat();
|
||||
Check.False(b.WantsVitalRecharge, "6 s after the restart with nothing landing: released");
|
||||
}
|
||||
|
||||
private static void HealHoldReleases()
|
||||
{
|
||||
// A caster in Magic stance: its Heal Self goes out with no stance step, so nothing but the
|
||||
// hold itself (no wand-flip backoff) decides what WantsVitalRecharge reads.
|
||||
var b = MeleeSpellRig(out var v, out var setNow, CombatMode.Magic);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 0, 50);
|
||||
setNow(t0);
|
||||
b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "48% under Heal At 75%: vitals want the tick");
|
||||
setNow(t0.AddMilliseconds(5900)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "5.9 s with no heal landing: still held");
|
||||
setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat();
|
||||
Check.False(b.WantsVitalRecharge, "6 s with no heal landing: combat gets the tick");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("no heal landed", StringComparison.Ordinal)), "logged");
|
||||
setNow(t0.AddMilliseconds(10_900)); b.OnHeartbeat();
|
||||
Check.False(b.WantsVitalRecharge, "4.9 s into the 5 s window: combat still has it");
|
||||
setNow(t0.AddMilliseconds(11_000)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "the window over: vitals hold the tick again");
|
||||
setNow(t0.AddMilliseconds(16_900)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "5.9 s into the next hold: held");
|
||||
setNow(t0.AddMilliseconds(17_000)); b.OnHeartbeat();
|
||||
Check.False(b.WantsVitalRecharge, "6 s again with nothing landing: released again");
|
||||
|
||||
// A heal landing (health up 3 points or more) ends a release and restarts the count.
|
||||
v.CurrentHealth = 52;
|
||||
setNow(t0.AddMilliseconds(18_000)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "a heal landed (48 -> 52): the vitals hold the tick again");
|
||||
v.CurrentHealth = 50;
|
||||
setNow(t0.AddMilliseconds(23_900)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "5.9 s after the landing: held");
|
||||
setNow(t0.AddMilliseconds(24_000)); b.OnHeartbeat();
|
||||
Check.False(b.WantsVitalRecharge, "6 s after it with nothing more: released");
|
||||
|
||||
// Over the line ends the episode; a new dip starts a fresh 6 s count.
|
||||
v.CurrentHealth = 90;
|
||||
setNow(t0.AddMilliseconds(25_000)); b.OnHeartbeat();
|
||||
v.CurrentHealth = 40;
|
||||
setNow(t0.AddMilliseconds(26_000)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "a new dip: held from the start");
|
||||
setNow(t0.AddMilliseconds(31_900)); b.OnHeartbeat();
|
||||
Check.True(b.WantsVitalRecharge, "5.9 s into the new dip: held (the count restarted)");
|
||||
setNow(t0.AddMilliseconds(32_000)); b.OnHeartbeat();
|
||||
Check.False(b.WantsVitalRecharge, "6 s into the new dip: released");
|
||||
|
||||
// No monster within Monster Range: nothing to fight, the vitals keep the tick.
|
||||
var q = MeleeSpellRig(out _, out var setNowQ, CombatMode.Magic, monsterInRange: false);
|
||||
setNowQ(t0); q.OnHeartbeat();
|
||||
setNowQ(t0.AddMilliseconds(20_000)); q.OnHeartbeat();
|
||||
Check.True(q.WantsVitalRecharge, "no monster in range: 20 s with no heal landing, still held (nav and loot don't get it)");
|
||||
Check.Eq(q.HealHoldReleases, 0, "never released");
|
||||
}
|
||||
|
||||
private static void HealHoldNoStanceChange()
|
||||
{
|
||||
var b = MeleeSpellRig(out _, out var setNow);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 0, 50);
|
||||
setNow(t0);
|
||||
Check.True(b.CheckVitals(), "control: melee, no kit: Heal Self starts its stance change");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "control: Magic mode was asked for");
|
||||
b.OnHeartbeat();
|
||||
int before = FakeHost.CombatModeRequests.Count;
|
||||
int wieldsBefore = FakeHost.Wields.Count;
|
||||
// The heartbeat that releases the hold runs the vitals step too (the flip's 2 s backoff is over).
|
||||
setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat();
|
||||
Check.False(b.WantsVitalRecharge, "the rig: combat has the tick");
|
||||
setNow(t0.AddMilliseconds(7000));
|
||||
b.CheckVitals();
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, before, "while combat has the tick: no stance change for Heal Self");
|
||||
Check.Eq(FakeHost.Wields.Count, wieldsBefore, "and no wield");
|
||||
|
||||
// A caster already in Magic stance needs no change: its Heal Self still goes.
|
||||
var c = MeleeSpellRig(out _, out var setNowC, CombatMode.Magic);
|
||||
setNowC(t0);
|
||||
c.OnHeartbeat();
|
||||
setNowC(t0.AddMilliseconds(6000)); c.OnHeartbeat();
|
||||
Check.False(c.WantsVitalRecharge, "caster rig: combat has the tick");
|
||||
int casts = FakeHost.Casts.Count;
|
||||
c.CheckVitals();
|
||||
Check.True(FakeHost.Casts.Count > casts, "caster in Magic: Heal Self is cast while combat has the tick");
|
||||
|
||||
// A caster in Magic stance with Use Kits in Magic Mode and Peace Mode for Kits: the kit's peace
|
||||
// switch is a stance change too. Control first (not released): it goes out.
|
||||
foreach (bool released in new[] { false, true })
|
||||
{
|
||||
var k = KitRig(CombatMode.Magic, modeCalls: true);
|
||||
RigSettings.UseKitsInMagicMode = true;
|
||||
RigSettings.PeaceModeForKits = true;
|
||||
var t1 = new DateTime(2026, 1, 1, 12, 1, 0);
|
||||
k.Clock = () => t1;
|
||||
if (released)
|
||||
typeof(BuffManager).GetField("_hhReleasedUntil", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
|
||||
.SetValue(k, t1.AddMilliseconds(5000));
|
||||
k.CheckVitals();
|
||||
int peace = FakeHost.CombatModeRequests.Count(m => m == CombatMode.NonCombat);
|
||||
if (released)
|
||||
{
|
||||
Check.Eq(peace, 0, "Magic stance, combat has the tick: no peace switch for the kit");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "the kit is used in the stance it is in");
|
||||
}
|
||||
else
|
||||
Check.Eq(peace, 1, "control, Magic stance, not released: the kit's peace switch goes out");
|
||||
}
|
||||
}
|
||||
|
||||
// A release must not cut off a heal the server is already playing. A kit that has animated
|
||||
// (heal grace's NoteKitProgress), or a wand wield in flight, holds the release back; a removed kit
|
||||
// never animates, so it still releases.
|
||||
private static void HealHoldWaitsForAnimatingKit()
|
||||
{
|
||||
foreach (bool animating in new[] { true, false })
|
||||
{
|
||||
string how = animating ? "animating kit" : "kit with no motion";
|
||||
var b = KitRig();
|
||||
b.InCombatOverride = () => true;
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 0, 58);
|
||||
DateTime now = t0;
|
||||
b.Clock = () => now;
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
b.OnHeartbeat(); // the hold starts counting
|
||||
if (FakeHost.UsesOn.Count == 0) b.CheckVitals();
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, $"{how}: the kit is in flight");
|
||||
FakeHost.CastBusy = animating ? 1 : 0;
|
||||
now = t0.AddMilliseconds(6000);
|
||||
b.OnHeartbeat();
|
||||
FakeHost.CastBusy = 0;
|
||||
if (animating)
|
||||
{
|
||||
Check.Eq(b.HealHoldReleases, 0, "6 s, the kit's heal motion playing: no release");
|
||||
Check.True(b.WantsVitalRecharge, "the vitals keep the tick for it");
|
||||
}
|
||||
else
|
||||
Check.Eq(b.HealHoldReleases, 1, "6 s, a kit the server never animated (the live failure): released");
|
||||
}
|
||||
}
|
||||
|
||||
private static void HealHoldWaitsForWield()
|
||||
{
|
||||
var b = MeleeSpellRig(out _, out var setNow);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 0, 50);
|
||||
var pending = typeof(BuffManager).GetField("_pendingWieldId", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
|
||||
setNow(t0); b.OnHeartbeat();
|
||||
pending.SetValue(b, unchecked((int)0x80084C1E)); // the wand's wield sent, the server not done yet
|
||||
setNow(t0.AddMilliseconds(6000)); b.OnHeartbeat();
|
||||
Check.Eq(b.HealHoldReleases, 0, "6 s, a wand wield in flight: no release");
|
||||
Check.True(b.WantsVitalRecharge, "the vitals keep the tick");
|
||||
pending.SetValue(b, 0);
|
||||
setNow(t0.AddMilliseconds(6100)); b.OnHeartbeat();
|
||||
Check.Eq(b.HealHoldReleases, 1, "the wield done, still nothing landed: released");
|
||||
}
|
||||
|
||||
private static void ReleasedKitChanceNotPeace()
|
||||
{
|
||||
var b = KitRig();
|
||||
FakeHost.Skills[(Player, 21)] = (75, 2); // Healing (STypeSkill 21), trained
|
||||
RigSettings.PeaceModeForKits = true;
|
||||
RigSettings.KitMinSuccessPct = 30;
|
||||
SetHealth(b, 34); // 66 missing
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 1, 3);
|
||||
b.Clock = () => t0;
|
||||
typeof(BuffManager).GetField("_hhReleasedUntil", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
|
||||
.SetValue(b, t0.AddMilliseconds(5000)); // combat has the tick
|
||||
Check.True(b.HealHoldReleased, "the rig: released");
|
||||
b.CheckVitals();
|
||||
// (75 + 25) x 1.1 = 110 against 66 x 2 x 1.1 = 145 in melee: 25%, under 30. In peace it would be
|
||||
// 66 x 2 = 132: 34%, over it. No peace switch goes out while released, so melee is the stance.
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("would work 25% of the time on 66 missing (skill 110 vs 145)", StringComparison.Ordinal)),
|
||||
"the chance is the melee one: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("would work", StringComparison.Ordinal))));
|
||||
}
|
||||
}
|
||||
249
Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTextColorTests.cs
Normal file
249
Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTextColorTests.cs
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-11-05, a player asked to colour the item info lines (AutoID on select, /ra iteminfo, ...)
|
||||
// without changing their chat type: picking "allegiance" as the chat type for its colour also
|
||||
// moved the lines to where allegiance lines go. Item Info's "Info text colour" asks the engine
|
||||
// (SendPluginCommand "RynthCore.Chat" nextcolor, engine UI/Data/ChatOwnColors.cs) to draw the next
|
||||
// line in that colour just before each line is written; the line keeps its chat type. Unset, the
|
||||
// lines go out exactly as before. An engine without it answers "no" once and is not asked again.
|
||||
internal static class ItemInfoTextColorTests
|
||||
{
|
||||
private const uint Player = 0x50000E52;
|
||||
private const uint Sword = 0x80266101;
|
||||
private const uint ItemTypeMelee = 0x1;
|
||||
private const string Target = "RynthCore.Chat";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("item info colour: unset, the lines go out as before and nothing is asked", DefaultUnchanged);
|
||||
r.Add("item info colour: set, each line asks for it just before it is written, its chat type unchanged", ColouredLines);
|
||||
r.Add("item info colour: an engine without it is asked once, then the lines go out plain", OlderEngine);
|
||||
r.Add("item info colour: the Test button and /ra iteminfo me use it too", TestButtonAndSelf);
|
||||
r.Add("item info colour: saved with the profile, reset, sanitized, the settings map", SettingsRoundTrip);
|
||||
r.Add("item info colour: /ra iteminfo color always answers", Command);
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new();
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true); // a stand-in with its profile in memory
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
Set("_objectCache", cache);
|
||||
Set("_playerId", Player);
|
||||
cache.OnCreateObject(Sword);
|
||||
cache.OnCreateObject(Player);
|
||||
cache.Tick();
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
public void Call(string method, params object[] args) => typeof(RynthAiPlugin).GetMethod(method, Any)!.Invoke(P, args);
|
||||
public void Print() => Call("PrintItemInfo", unchecked((int)Sword), true);
|
||||
public void Cmd(params string[] words) => Call("HandleItemInfoCommand", new object[] { new[] { "ra", "iteminfo" }.Concat(words).ToArray() });
|
||||
}
|
||||
|
||||
/// <summary>A gold long sword, identified, with a spell: pet-style output is several lines.</summary>
|
||||
private static Bot World(bool pluginCommands = true, bool delivered = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.PluginCommandCalls = pluginCommands;
|
||||
FakeHost.PluginCommandDelivered = delivered;
|
||||
FakeHost.Names[Player] = "Colour Tester";
|
||||
FakeHost.Names[Sword] = "Long Sword";
|
||||
FakeHost.ItemTypes[Sword] = ItemTypeMelee;
|
||||
FakeHost.Containers[Sword] = Player;
|
||||
foreach (var (k, v) in new (uint, int)[] { (1, (int)ItemTypeMelee), (19, 9000), (5, 300), (131, 60), (105, 6), (353, 2), (45, 1), (204, 0) })
|
||||
FakeHost.Ints[(Sword, k)] = v;
|
||||
FakeHost.SpellIds[Sword] = new[] { (uint)SpellDatabase.GetIdByName("Legendary Blood Thirst") };
|
||||
FakeHost.Appraised.Add(Sword);
|
||||
return new Bot(FakeHost.Create(Player));
|
||||
}
|
||||
|
||||
private static List<int> ItemLines() =>
|
||||
Enumerable.Range(0, FakeHost.Chat.Count).Where(i => FakeHost.Chat[i].StartsWith("[RynthAi Item] ", StringComparison.Ordinal)).ToList();
|
||||
|
||||
private static List<int> Asks() =>
|
||||
Enumerable.Range(0, FakeHost.PluginCommands.Count).Where(i => FakeHost.PluginCommands[i].Plugin == Target).ToList();
|
||||
|
||||
private static void DefaultUnchanged()
|
||||
{
|
||||
var fresh = new MagItemInfoSettings();
|
||||
Check.Eq(fresh.TextColor, "", "Info text colour: the chat type's own colour by default");
|
||||
|
||||
Bot bot = World();
|
||||
bot.S.ItemInfoSettings.DetailChatType = 7;
|
||||
bot.Print();
|
||||
List<int> lines = ItemLines();
|
||||
Check.True(lines.Count >= 2, "pet-style: a name line and detail lines: " + string.Join(" | ", FakeHost.Chat));
|
||||
Check.Eq(Asks().Count, 0, "no colour asked for");
|
||||
Check.Eq(FakeHost.PluginCommands.Count, 0, "nothing sent to the engine at all");
|
||||
if (lines.Count >= 2)
|
||||
{
|
||||
Check.Eq(FakeHost.ChatTypes[lines[0]], 1, "the name line in the Item Info chat type (1)");
|
||||
Check.True(lines.Skip(1).All(i => FakeHost.ChatTypes[i] == 7), "detail lines in theirs (7)");
|
||||
Check.True(FakeHost.Chat[lines[0]].StartsWith("[RynthAi Item] Gold Long Sword", StringComparison.Ordinal), "the text: " + FakeHost.Chat[lines[0]]);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ColouredLines()
|
||||
{
|
||||
Bot bot = World();
|
||||
bot.S.ItemInfoSettings.DetailChatType = 7;
|
||||
bot.Print();
|
||||
List<string> plain = ItemLines().Select(i => FakeHost.Chat[i]).ToList();
|
||||
List<int> plainTypes = ItemLines().Select(i => FakeHost.ChatTypes[i]).ToList();
|
||||
|
||||
bot = World();
|
||||
bot.S.ItemInfoSettings.DetailChatType = 7;
|
||||
bot.S.ItemInfoSettings.TextColor = "#EE921E";
|
||||
bot.Print();
|
||||
List<int> lines = ItemLines();
|
||||
List<int> asks = Asks();
|
||||
Check.Eq(lines.Count, plain.Count, "as many lines as without a colour");
|
||||
Check.True(lines.Select(i => FakeHost.Chat[i]).SequenceEqual(plain), "the same text");
|
||||
Check.True(lines.Select(i => FakeHost.ChatTypes[i]).SequenceEqual(plainTypes), "the same chat types (the same tab and AC chat window)");
|
||||
Check.Eq(asks.Count, lines.Count, "one colour asked for per line");
|
||||
Check.True(asks.All(i => FakeHost.PluginCommands[i] == (Target, "nextcolor", "#EE921E")), "nextcolor #EE921E: " + string.Join(" | ", FakeHost.PluginCommands));
|
||||
Check.True(asks.Select(i => FakeHost.PluginCommandChatCounts[i]).SequenceEqual(lines),
|
||||
"each asked for just before its own line (nothing written in between)");
|
||||
}
|
||||
|
||||
private static void OlderEngine()
|
||||
{
|
||||
Bot bot = World(delivered: false); // an engine from before 2026-11-05: no "RynthCore.Chat"
|
||||
bot.S.ItemInfoSettings.TextColor = "#EE921E";
|
||||
bot.Print();
|
||||
bot.Print();
|
||||
Check.Eq(Asks().Count, 1, "asked once");
|
||||
Check.Eq(ItemLines().Count % 2, 0, "every line of both prints written");
|
||||
Check.True(ItemLines().Count >= 4, "in its chat type's colour: " + string.Join(" | ", FakeHost.Chat));
|
||||
|
||||
bot = World(pluginCommands: false); // an engine before API v64
|
||||
bot.S.ItemInfoSettings.TextColor = "#EE921E";
|
||||
bot.Print();
|
||||
Check.True(ItemLines().Count >= 2, "no SendPluginCommand at all: the lines still go out");
|
||||
}
|
||||
|
||||
private static void TestButtonAndSelf()
|
||||
{
|
||||
Bot bot = World();
|
||||
bot.S.ItemInfoSettings.TextColor = "#3FBFFF";
|
||||
bot.Call("TestItemInfoChatType", 18);
|
||||
Check.Eq(FakeHost.Chat.LastOrDefault(), "[RynthAi Item] Item info chat test (type 18, colour #3FBFFF)", "the Test line names both");
|
||||
Check.Eq(FakeHost.ChatTypes.LastOrDefault(), 18, "in the chat type tested");
|
||||
Check.Eq(Asks().Count, 1, "in the colour");
|
||||
|
||||
bot.Call("PrintSelfRatings", Player, true);
|
||||
int selfLines = ItemLines().Count - 1;
|
||||
Check.True(selfLines >= 1, "your ratings print: " + string.Join(" | ", FakeHost.Chat));
|
||||
Check.Eq(Asks().Count, 1 + selfLines, "each ratings line in the colour too");
|
||||
}
|
||||
|
||||
private static void SettingsRoundTrip()
|
||||
{
|
||||
// Profile: save, load (CopySettings), save again unchanged.
|
||||
var saved = new LegacyUiSettings();
|
||||
saved.ItemInfoSettings.TextColor = "#EE921E";
|
||||
string json = JsonSerializer.Serialize(saved, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
var live = new LegacyUiSettings();
|
||||
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)!
|
||||
.Invoke(null, new object[] { JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!, live });
|
||||
Check.Eq(live.ItemInfoSettings.TextColor, "#EE921E", "the colour survives a save and load");
|
||||
Check.Eq(JsonSerializer.Serialize(live, RynthAiJsonContext.Default.LegacyUiSettings), json, "and saves back unchanged");
|
||||
|
||||
// A profile from before the setting: the chat type's own colour.
|
||||
var doc = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
|
||||
var info = doc[doc.Select(kv => kv.Key).Single(k => k.Equals("ItemInfoSettings", StringComparison.OrdinalIgnoreCase))]!.AsObject();
|
||||
string? key = info.Select(kv => kv.Key).SingleOrDefault(k => k.Equals("TextColor", StringComparison.OrdinalIgnoreCase));
|
||||
Check.True(key != null, "the field is in the profile JSON");
|
||||
if (key != null) info.Remove(key);
|
||||
var old = new LegacyUiSettings();
|
||||
typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.Static | Any)!
|
||||
.Invoke(null, new object[] { JsonSerializer.Deserialize(doc.ToJsonString(), RynthAiJsonContext.Default.LegacyUiSettings)!, old });
|
||||
Check.Eq(old.ItemInfoSettings.TextColor, "", "a profile without it: the chat type's colour");
|
||||
|
||||
// Sanitize tidies a hand-edited value; Reset all to defaults clears it.
|
||||
var s = new MagItemInfoSettings { TextColor = " ee921e " };
|
||||
s.Sanitize();
|
||||
Check.Eq(s.TextColor, "#EE921E", "a code without # is tidied");
|
||||
s.TextColor = "orange"; s.Sanitize();
|
||||
Check.Eq(s.TextColor, "", "a word that isn't a code: the chat type's colour");
|
||||
s.TextColor = "#12345"; s.Sanitize();
|
||||
Check.Eq(s.TextColor, "", "a short code: cleared");
|
||||
s.TextColor = "#3FBFFF";
|
||||
s.ResetToDefaults();
|
||||
Check.Eq(s.TextColor, "", "reset: the chat type's colour");
|
||||
|
||||
// The named colours are codes; the first is the default.
|
||||
Check.Eq(MagItemInfoCatalog.TextColors[0].Color, "", "the first choice is the chat type's own colour");
|
||||
Check.True(MagItemInfoCatalog.TextColors.Skip(1).All(c => MagItemInfoCatalog.NormalizeTextColor(c.Color) == c.Color), "every named colour is a #RRGGBB code");
|
||||
Check.Eq(MagItemInfoCatalog.TextColors.Select(c => c.Word).Distinct(StringComparer.OrdinalIgnoreCase).Count(), MagItemInfoCatalog.TextColors.Length, "names are unique");
|
||||
Check.Eq(MagItemInfoCatalog.TextColorFromRgb(MagItemInfoCatalog.TextColorRgb("#EE921E")), "#EE921E", "the colour picker round-trips");
|
||||
|
||||
// The settings map (metas: rasetsetting / ragetsetting).
|
||||
var mapSettings = new LegacyUiSettings();
|
||||
var e = ExpressionTests.Engine(settings: mapSettings);
|
||||
e.Evaluate("rasetsetting[ItemInfoTextColor, allegiance]");
|
||||
Check.Eq(mapSettings.ItemInfoSettings.TextColor, "#EE921E", "set by name through the map");
|
||||
Check.Eq(e.Evaluate("ragetsetting[ItemInfoTextColor]"), "#EE921E", "map reads it");
|
||||
e.Evaluate("rasetsetting[ItemInfoTextColor, default]");
|
||||
Check.Eq(mapSettings.ItemInfoSettings.TextColor, "", "default through the map");
|
||||
}
|
||||
|
||||
private static void Command()
|
||||
{
|
||||
Bot bot = World();
|
||||
bot.Cmd("color", "allegiance");
|
||||
Check.Eq(bot.S.ItemInfoSettings.TextColor, "#EE921E", "/ra iteminfo color allegiance");
|
||||
Check.True(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi] Item info text colour: Allegiance (orange) #EE921E in RynthCore's chat", StringComparison.Ordinal)),
|
||||
"replies with the colour: " + string.Join(" | ", FakeHost.Chat));
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("colour", "#12ab34");
|
||||
Check.Eq(bot.S.ItemInfoSettings.TextColor, "#12AB34", "/ra iteminfo colour #12ab34");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("text colour: #12AB34")), "replies: " + string.Join(" | ", FakeHost.Chat));
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("color");
|
||||
Check.Eq(bot.S.ItemInfoSettings.TextColor, "#12AB34", "no argument changes nothing");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("text colour: #12AB34")), "and says the colour now");
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("color", "plaid");
|
||||
Check.Eq(bot.S.ItemInfoSettings.TextColor, "#12AB34", "a bad word changes nothing");
|
||||
Check.True(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi] Usage: /ra iteminfo color default|allegiance|", StringComparison.Ordinal)),
|
||||
"and gets the usage: " + string.Join(" | ", FakeHost.Chat));
|
||||
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd("color", "default");
|
||||
Check.Eq(bot.S.ItemInfoSettings.TextColor, "", "/ra iteminfo color default");
|
||||
Check.True(FakeHost.Chat.Any(c => c.StartsWith("[RynthAi] Item info text colour: the chat type's own colour.", StringComparison.Ordinal)),
|
||||
"replies: " + string.Join(" | ", FakeHost.Chat));
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ using System.Collections.Generic;
|
|||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
|
|
@ -38,6 +39,8 @@ internal static class ItemToolTests
|
|||
r.Add("chest looter: combat/busy holds every send, then the run stops after the cap", ChestHoldsThenStops);
|
||||
r.Add("chest looter: can't start without a chest, a key, a loaded near chest; Stop always works and ends the loot session", ChestStartRefusalsAndStop);
|
||||
r.Add("chest looter: a key that never runs out is cut off at MaxCycles", ChestMaxCycles);
|
||||
r.Add("chest looter: the re-lock wait is the 'Chest re-lock wait (s)' setting, clamped 5..600; a change applies to the wait running", ChestRelockSetting);
|
||||
r.Add("chest looter: after a short re-lock wait the asks follow it (never under 5 s apart), bounded; a long wait still ends when the chest reads locked", ChestRelockProbes);
|
||||
// Quick give state machine
|
||||
r.Add("quick give: one give at a time, each after the last landed, paced; done when none is left", GiveOneAtATime);
|
||||
r.Add("quick give: a refused item is left out; three refusals in a row stop it", GiveRefusals);
|
||||
|
|
@ -49,6 +52,8 @@ internal static class ItemToolTests
|
|||
r.Add("item tool: Quick give hands over exactly the picked item to the picked NPC, never worn gear or other names", PluginQuickGive);
|
||||
r.Add("item tool: Quick give starts only from the panel or a typed line, never from a meta, a script or a remote line; stop works from anywhere", PluginGiveTrust);
|
||||
r.Add("item tool: Quick give targets are players or NPCs only", PluginGiveTargets);
|
||||
r.Add("item tool: /ra itemtool relock sets, clamps and saves the re-lock wait and always answers with the value; refused before the profile loads", PluginRelockCommand);
|
||||
r.Add("item tool: the re-lock wait is saved in the profile and loaded (old profiles: 125 s), sent to the engine and left alone by an engine without it", RelockSavedAndLoaded);
|
||||
}
|
||||
|
||||
// ── Fake environments ────────────────────────────────────────────────────
|
||||
|
|
@ -420,6 +425,92 @@ internal static class ItemToolTests
|
|||
Check.True(said.Contains($"{ChestKeyLooter.MaxCycles} cycles"), "says why: " + said.Substring(Math.Max(0, said.Length - 200)));
|
||||
}
|
||||
|
||||
/// <summary>Runs one cycle on two same-named keys and returns how long after the open the second key went.</summary>
|
||||
private static long NextKeyAfterOpen(int relockSec, Action<ChestEnv, ChestKeyLooter>? duringWait = null)
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12);
|
||||
Serve(env, ck);
|
||||
env.AutoLootMs = 1000;
|
||||
ck.RelockWaitSec = relockSec;
|
||||
ck.Start(out _);
|
||||
env.Run(5000, () => env.LootStarts > 0);
|
||||
env.Run(3000, () => ck.State == ChestKeyLooter.Phase.Waiting);
|
||||
Check.Eq(ck.State, ChestKeyLooter.Phase.Waiting, $"waiting for the re-lock ({relockSec} s)");
|
||||
long openedAt = env.OpenedAt;
|
||||
int sent = env.Sent.Count;
|
||||
duringWait?.Invoke(env, ck);
|
||||
env.Run(700_000, () => env.Sent.Count > sent);
|
||||
Check.True(env.Sent.Count > sent, $"the next key goes after the wait ({relockSec} s)");
|
||||
return env.T - openedAt;
|
||||
}
|
||||
|
||||
private static void ChestRelockSetting()
|
||||
{
|
||||
// The setting, clamped.
|
||||
NewChest(out var c0);
|
||||
Check.Eq(c0.RelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "default 125 s (the wait before the setting)");
|
||||
Check.Eq(ChestKeyLooter.RegenWaitMs, 125_000L, "the default is the old wait");
|
||||
c0.RelockWaitSec = 1;
|
||||
Check.Eq(c0.RelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "1 s is raised to the least, 5 s");
|
||||
c0.RelockWaitSec = -40;
|
||||
Check.Eq(c0.RelockWaitSec, 5, "a negative value too");
|
||||
c0.RelockWaitSec = 100_000;
|
||||
Check.Eq(c0.RelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "100000 s is cut to the most, 600 s");
|
||||
Check.Eq(ChestKeyLooter.ClampRelockWaitSec(45), 45, "in range: kept");
|
||||
|
||||
// The wait uses it: the next key goes that long after the open, not 125 s.
|
||||
long at = NextKeyAfterOpen(20);
|
||||
Check.True(at >= 20_000 && at < 22_000, $"20 s: the next key ~20 s after the open ({at} ms)");
|
||||
at = NextKeyAfterOpen(ChestKeyLooter.DefaultRelockWaitSec);
|
||||
Check.True(at >= 125_000 && at < 127_000, $"default: ~125 s after the open, as before ({at} ms)");
|
||||
at = NextKeyAfterOpen(5);
|
||||
Check.True(at >= 5_000 && at < 7_000, $"5 s: ~5 s after the open ({at} ms)");
|
||||
at = NextKeyAfterOpen(1);
|
||||
Check.True(at >= 5_000, $"1 s is used as 5 s ({at} ms)");
|
||||
|
||||
// Changed while the wait runs (the panel, mid-run): the running wait follows.
|
||||
at = NextKeyAfterOpen(ChestKeyLooter.DefaultRelockWaitSec, (env, ck) => { env.Run(10_000); ck.RelockWaitSec = 30; });
|
||||
Check.True(at >= 30_000 && at < 32_000, $"125 -> 30 s during the wait: the key goes ~30 s after the open ({at} ms)");
|
||||
at = NextKeyAfterOpen(20, (env, ck) => { env.Run(5_000); ck.RelockWaitSec = 60; });
|
||||
Check.True(at >= 60_000 && at < 62_000, $"20 -> 60 s during the wait: it waits the longer time ({at} ms)");
|
||||
}
|
||||
|
||||
private static void ChestRelockProbes()
|
||||
{
|
||||
foreach (int sec in new[] { 20, 5, ChestKeyLooter.DefaultRelockWaitSec })
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Unlimited = true;
|
||||
env.AutoLootMs = 1000;
|
||||
ck.RelockWaitSec = sec;
|
||||
bool unlocked = false;
|
||||
var keyAt = new List<long>();
|
||||
env.OnKey = _ => { keyAt.Add(env.T); return unlocked ? ChestKeyLooter.ErrLockAlreadyUnlocked : 0u; }; // the chest never re-locks
|
||||
ck.Start(out _);
|
||||
env.Run(3000, () => env.LootStarts > 0);
|
||||
unlocked = true;
|
||||
env.Run(2_000_000, () => !ck.Running);
|
||||
Check.False(ck.Running, $"{sec} s: gave up on a chest that never re-locks");
|
||||
long every = Math.Clamp(sec * 1000L, ChestKeyLooter.MinProbeMs, ChestKeyLooter.ProbeMs);
|
||||
int limit = (int)((ChestKeyLooter.MaxProbes * ChestKeyLooter.ProbeMs + every - 1) / every);
|
||||
Check.Eq(ck.ProbeLimit, limit, $"{sec} s: the asks fit in {ChestKeyLooter.MaxProbes * ChestKeyLooter.ProbeMs / 1000} s");
|
||||
Check.Eq(keyAt.Count, 1 + limit + 1, $"{sec} s: bounded: the first use, the one after the wait, one per ask");
|
||||
for (int i = 2; i < keyAt.Count; i++)
|
||||
Check.True(keyAt[i] - keyAt[i - 1] >= every, $"{sec} s: ask {i} came {keyAt[i] - keyAt[i - 1]} ms after the last (at least {every})");
|
||||
Check.True(keyAt.Zip(keyAt.Skip(1), (a, b) => b - a).All(d => d >= ChestKeyLooter.MinProbeMs), $"{sec} s: never two key uses under 5 s apart");
|
||||
Check.Eq(env.Sent.Count(s => s == "open"), 1, $"{sec} s: the empty chest is not opened again");
|
||||
Check.True(Said(env).Contains("hasn't re-locked"), $"{sec} s: says why: " + Said(env));
|
||||
}
|
||||
Check.Eq(new ChestKeyLooter(new ChestEnv()).ProbeLimit, ChestKeyLooter.MaxProbes, "the default wait asks MaxProbes times, as before");
|
||||
|
||||
// A long wait still ends when the client reads the chest locked again (ACE's Reset sends Locked=true).
|
||||
long at = NextKeyAfterOpen(ChestKeyLooter.MaxRelockWaitSec, (env, _) => env.Locked = true);
|
||||
Check.True(at >= ChestKeyLooter.MinRelockMs && at < ChestKeyLooter.MinRelockMs + 2000, $"600 s, the chest reads locked: the key goes at ~{ChestKeyLooter.MinRelockMs / 1000} s ({at} ms)");
|
||||
at = NextKeyAfterOpen(ChestKeyLooter.MaxRelockWaitSec, (env, _) => env.Locked = false);
|
||||
Check.True(at >= 600_000, $"600 s, the chest reads unlocked: the whole wait ({at} ms)");
|
||||
}
|
||||
|
||||
// ── Quick give state machine ─────────────────────────────────────────────
|
||||
|
||||
private sealed class GiveEnv : IQuickGiveEnv
|
||||
|
|
@ -914,4 +1005,103 @@ internal static class ItemToolTests
|
|||
Check.True(Chat().Contains("giving every 'Mana Mote'") && Chat().Contains("to Some Player"), "the start line names the player: " + Chat());
|
||||
bot.Cmd("stop"); bot.Tick();
|
||||
}
|
||||
|
||||
// ── Chest re-lock wait (the setting) ─────────────────────────────────────
|
||||
|
||||
private static void PluginRelockCommand()
|
||||
{
|
||||
BaseWorld();
|
||||
var bot = MakeBot("itemtool-relock.json");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "a new profile: 125 s");
|
||||
|
||||
string Run(string words)
|
||||
{
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd(words);
|
||||
bot.Tick();
|
||||
return Chat();
|
||||
}
|
||||
|
||||
string said = Run("relock 30");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, 30, "relock 30 sets 30 s");
|
||||
Check.True(said.Contains("re-lock wait = 30 s"), "answers with the value now: " + said);
|
||||
Check.Eq(bot.Get<ChestKeyLooter>("_chestKey").RelockWaitSec, 30, "the looter has it");
|
||||
|
||||
said = Run("relock 2");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "2 s is raised to 5 s");
|
||||
Check.True(said.Contains("re-lock wait = 5 s") && said.Contains("the least is 5 s"), "says it was clamped: " + said);
|
||||
|
||||
said = Run("chest relock 9999");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "'chest relock' works too; 9999 is cut to 600");
|
||||
Check.True(said.Contains("re-lock wait = 600 s") && said.Contains("the most is 600 s"), "says it was clamped: " + said);
|
||||
|
||||
said = Run("relock 45s");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, 45, "'45s' is read as 45");
|
||||
|
||||
said = Run("relock soon");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, 45, "not a number: unchanged");
|
||||
Check.True(said.Contains("'soon' isn't a number") && said.Contains("still 45 s") && said.Contains("/ra itemtool relock <seconds>"), "says why, the value and the usage: " + said);
|
||||
|
||||
said = Run("relock");
|
||||
Check.True(said.Contains("re-lock wait = 45 s") && said.Contains("5-600 s, default 125"), "no number: says the value and the range: " + said);
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, 45, "and changes nothing");
|
||||
|
||||
// The panel reads it.
|
||||
string json = bot.P.BuildItemToolJson();
|
||||
Check.True(json.Contains("\"relockSec\":45") && json.Contains("\"relockMin\":5") && json.Contains("\"relockMax\":600") && json.Contains("\"relockReady\":true"),
|
||||
"the Item Tool panel's data carries the setting: " + json);
|
||||
|
||||
// The wait the running looter uses is the setting's (the tick hands it over).
|
||||
bot.S.ChestRelockWaitSec = 77;
|
||||
bot.Tick();
|
||||
Check.Eq(bot.Get<ChestKeyLooter>("_chestKey").RelockWaitSec, 77, "a change made elsewhere (meta, engine) reaches the looter on the next tick");
|
||||
|
||||
// Before the character's profile loads nothing lands on the defaults.
|
||||
var dash = bot.Get<LegacyDashboardRenderer>("_dashboard");
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, false);
|
||||
said = Run("relock 40");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, 77, "refused before the profile loads");
|
||||
Check.True(said.Contains("isn't loaded yet") && said.Contains("unchanged"), "and says so: " + said);
|
||||
Check.True(bot.P.BuildItemToolJson().Contains("\"relockReady\":false"), "the panel greys the control meanwhile");
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true);
|
||||
}
|
||||
|
||||
private static void RelockSavedAndLoaded()
|
||||
{
|
||||
// The profile file (LegacyUiSettings as JSON): saved and read back; an older profile reads 125.
|
||||
var saved = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(new LegacyUiSettings { ChestRelockWaitSec = 40 }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.Eq(saved?.ChestRelockWaitSec, 40, "40 s is saved and loaded");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.Eq(old?.ChestRelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "a profile saved before the setting: 125 s");
|
||||
|
||||
// A profile load or switch (CopySettings, the hand-written field list) copies it, clamped.
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { saved!, dst });
|
||||
Check.Eq(dst.ChestRelockWaitSec, 40, "a profile with 40 s loads 40 s");
|
||||
copy.Invoke(null, new object[] { old!, dst });
|
||||
Check.Eq(dst.ChestRelockWaitSec, 125, "an old profile loads 125 s");
|
||||
var edited = JsonSerializer.Deserialize("{\"ChestRelockWaitSec\":0}", RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
copy.Invoke(null, new object[] { edited, dst });
|
||||
Check.Eq(dst.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "a hand-edited 0 loads as 5 s");
|
||||
|
||||
// The engine's settings payload: carries it; an engine that has no row for it leaves it alone.
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.ChestRelockWaitSec == null, "an engine's payload without it has no value");
|
||||
var s = new LegacyUiSettings { ChestRelockWaitSec = 33 };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", Any)!.SetValue(dash, true); // a stand-in with its profile in memory
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", Any)!.SetValue(dash, new LegacyAdvancedSettingsUi(s)); // BuildSettingsJson reads its crafting state
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.Eq(sent?.ChestRelockWaitSec, 33, "sent to the engine");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.Eq(s.ChestRelockWaitSec, 33, "a save without the field leaves it");
|
||||
dash.ApplySettingsJson("{\"ChestRelockWaitSec\":9999}");
|
||||
Check.Eq(s.ChestRelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "a save with it is clamped (600 s)");
|
||||
dash.ApplySettingsJson("{\"ChestRelockWaitSec\":20}");
|
||||
Check.Eq(s.ChestRelockWaitSec, 20, "and applied");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
217
Tools/RynthCore.RynthAiHostTests/Tests/KitUsedUpTests.cs
Normal file
217
Tools/RynthCore.RynthAiHostTests/Tests/KitUsedUpTests.cs
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// A kit its own result line calls used up ("... Your Treated Healing Kit is used up.", ACE
|
||||
// Healer.DoHealing) is skipped by every kit pick (BuffManager.KitUsedUp.cs). The picks read the client's
|
||||
// live pack walk, which drops the removed kit, but reuses a walk for up to 1 s, and the next kit goes out
|
||||
// 700 ms after the line: inside that reuse the used-up kit was picked again (checked on main: the same
|
||||
// rig picks Kit1). These rigs freeze the walk's clock (WorldObjectCache.WalkClock), so the walk is never
|
||||
// refreshed and only the skip can keep the used-up kit out. Without GetContainerContents there is no walk
|
||||
// at all, and the skip does not end.
|
||||
internal static class KitUsedUpTests
|
||||
{
|
||||
private const uint Player = 0x500000C1;
|
||||
private const uint GoneListed = 0x80088BDA; // the stack the Consumables rule was added from, long gone
|
||||
private const uint Kit1 = 0x80073C1B;
|
||||
private const uint Kit2 = 0x80073C1A;
|
||||
private const uint Gem = 0x80073C19; // something else carried, so the walk is never empty
|
||||
private const uint StamKit1 = 0x80073C18, StamKit2 = 0x80073C17;
|
||||
private const string KitName = "Treated Healing Kit";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("kit used up: its result line skips that kit inside the pack walk's reuse; the next kit goes (rule and pack picks)", UsedUpLineNextKit);
|
||||
r.Add("kit used up: a line with uses left keeps the kit (control)", UsesLeftKeepsKit);
|
||||
r.Add("kit used up: a line naming another kit marks nothing; naming the kit in flight marks it", OtherKitLineIgnored);
|
||||
r.Add("kit used up: with the pack walk the skip ends after 3 s (the BuffManager clock)", SkipExpires);
|
||||
r.Add("kit used up: without GetContainerContents the skip does not end (no walk ever drops the kit)", NoWalkSkipLasts);
|
||||
r.Add("kit used up: a stamina kit's used-up line skips it for the next stamina kit", StaminaKitUsedUp);
|
||||
}
|
||||
|
||||
private static BuffManager Rig(bool withRule, string kit1Name = KitName, bool walk = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.ContentsCalls = walk; // the client's pack walk (GetContainerContents)
|
||||
FakeHost.CombatModeValue = CombatMode.Melee;
|
||||
FakeHost.Names[Kit1] = kit1Name;
|
||||
FakeHost.Names[Kit2] = KitName;
|
||||
FakeHost.Names[Gem] = "Sapphire";
|
||||
FakeHost.Containers[Kit1] = Player;
|
||||
FakeHost.Containers[Kit2] = Player;
|
||||
FakeHost.Containers[Gem] = Player;
|
||||
FakeHost.Skills[(Player, 33)] = (10, 1); // Life Magic untrained: kits are the only heal
|
||||
var host = FakeHost.Create(Player);
|
||||
var s = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 60, TopOffHP = 60, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = false, EnableBuffing = false,
|
||||
KitMinSuccessPct = 0, PeaceModeForKits = false,
|
||||
};
|
||||
if (withRule)
|
||||
s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)GoneListed), Name = KitName, Type = "HealthKit" });
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, v);
|
||||
b.SetCharacterSkills(skills);
|
||||
b.SetWorldObjectCache(Frozen(FakeHost.MakeCache(host, Player, new[] { Kit1, Kit2, Gem })));
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>The walk's reuse clock stopped: the first walk is reused for the whole test.</summary>
|
||||
private static WorldObjectCache Frozen(WorldObjectCache cache)
|
||||
{
|
||||
var frozen = new DateTime(2026, 1, 1, 12, 0, 0);
|
||||
cache.WalkClock = () => frozen;
|
||||
return cache;
|
||||
}
|
||||
|
||||
private static uint LastKit() => FakeHost.UsesOn.Count == 0 ? 0 : FakeHost.UsesOn[^1].Source;
|
||||
|
||||
/// <summary>The server removed the kit: the client deletes it (no pack, no name); the cache never hears.</summary>
|
||||
private static void Gone(uint id) { FakeHost.Containers.Remove(id); FakeHost.Names.Remove(id); }
|
||||
|
||||
/// <summary>The kit's result line, then past KitLandGraceMs (real clock): the kit wait ends.</summary>
|
||||
private static void ResultLine(BuffManager b, string line)
|
||||
{
|
||||
b.OnChatWindowText(line, 0);
|
||||
Thread.Sleep(750);
|
||||
Check.False(b.KitPending(), "the result line and 700 ms: the kit wait ends");
|
||||
}
|
||||
|
||||
private static void UsedUpLineNextKit()
|
||||
{
|
||||
foreach (bool withRule in new[] { true, false })
|
||||
{
|
||||
string how = withRule ? "Consumables rule" : "best pack kit";
|
||||
var b = Rig(withRule);
|
||||
Check.True(b.CheckVitals(), $"{how}: 40% under Heal At 60%: acts");
|
||||
Check.Eq(LastKit(), Kit1, $"{how}: Kit1 first (the walk is read now)");
|
||||
Gone(Kit1);
|
||||
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up.");
|
||||
Check.Eq(b.KitsUsedUp, 1, $"{how}: the kit in flight is marked used up");
|
||||
Check.True(b.CheckVitals(), $"{how}: acts again");
|
||||
Check.Eq(LastKit(), Kit2, $"{how}: inside the walk's reuse the used-up kit is skipped: Kit2");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("0x80073C1B", StringComparison.Ordinal) && l.Contains("is used up", StringComparison.Ordinal)),
|
||||
$"{how}: logged with the id");
|
||||
}
|
||||
}
|
||||
|
||||
private static void UsesLeftKeepsKit()
|
||||
{
|
||||
var b = Rig(withRule: true);
|
||||
Check.True(b.CheckVitals(), "acts");
|
||||
Check.Eq(LastKit(), Kit1, "Kit1");
|
||||
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} has 3 uses left.");
|
||||
Check.Eq(b.KitsUsedUp, 0, "uses left: nothing marked");
|
||||
Check.True(b.CheckVitals(), "acts again");
|
||||
Check.Eq(LastKit(), Kit1, "the same kit again");
|
||||
}
|
||||
|
||||
// A late line from a kit that timed out can land while the next kit is in flight.
|
||||
private static void OtherKitLineIgnored()
|
||||
{
|
||||
const string Adept = "Adept Healing Kit"; // ranked ahead of Treated: the pack pick takes it
|
||||
var b = Rig(withRule: false, kit1Name: Adept);
|
||||
Check.True(b.CheckVitals(), "acts");
|
||||
Check.Eq(LastKit(), Kit1, "the Adept kit is in flight");
|
||||
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up.");
|
||||
Check.Eq(b.KitsUsedUp, 0, "the line names the Treated kit, not the one in flight: nothing marked");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("ignored", StringComparison.Ordinal)), "logged as ignored");
|
||||
Check.True(b.CheckVitals(), "acts again");
|
||||
Check.Eq(LastKit(), Kit1, "the Adept kit is used again");
|
||||
ResultLine(b, $"You heal yourself for 12 Health points. Your {Adept} is used up.");
|
||||
Check.Eq(b.KitsUsedUp, 1, "control: the line naming the kit in flight marks it");
|
||||
}
|
||||
|
||||
private static void SkipExpires()
|
||||
{
|
||||
var b = Rig(withRule: true);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 1, 0);
|
||||
DateTime now = t0;
|
||||
b.Clock = () => now;
|
||||
b.CheckVitals();
|
||||
b.OnChatWindowText($"You heal yourself for 12 Health points. Your {KitName} is used up.", 0);
|
||||
Check.True(b.KitUsedUp(unchecked((int)Kit1)), "marked");
|
||||
now = t0.AddMilliseconds(2900);
|
||||
Check.True(b.KitUsedUp(unchecked((int)Kit1)), "2.9 s later: still skipped");
|
||||
now = t0.AddMilliseconds(3000); // 3 s as a literal: the test must not follow the constant
|
||||
Check.False(b.KitUsedUp(unchecked((int)Kit1)), "3 s: no longer skipped (the walk has dropped a removed kit by now)");
|
||||
Check.False(b.KitUsedUp(unchecked((int)Kit2)), "another kit was never skipped");
|
||||
}
|
||||
|
||||
// No GetContainerContents: the inventory is the object cache's, which keeps the removed kit. A skip
|
||||
// that ended at 3 s would pick it again for good.
|
||||
private static void NoWalkSkipLasts()
|
||||
{
|
||||
var b = Rig(withRule: true, walk: false);
|
||||
var t0 = new DateTime(2026, 1, 1, 12, 2, 0);
|
||||
DateTime now = t0;
|
||||
b.Clock = () => now;
|
||||
Check.True(b.CheckVitals(), "acts");
|
||||
Check.Eq(LastKit(), Kit1, "Kit1 first");
|
||||
Gone(Kit1); // the client deletes it; the cache still lists it
|
||||
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} is used up.");
|
||||
now = t0.AddMilliseconds(800);
|
||||
Check.True(b.CheckVitals(), "acts again");
|
||||
Check.Eq(LastKit(), Kit2, "in the window: Kit2");
|
||||
ResultLine(b, $"You heal yourself for 12 Health points. Your {KitName} has 3 uses left.");
|
||||
now = t0.AddMilliseconds(3200);
|
||||
Check.True(b.CheckVitals(), "acts at +3.2 s");
|
||||
Check.Eq(LastKit(), Kit2, "past 3 s with no walk: still Kit2, never the used-up Kit1");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("from now on", StringComparison.Ordinal)), "logged as a lasting skip");
|
||||
}
|
||||
|
||||
private static void StaminaKitUsedUp()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.ContentsCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.NonCombat;
|
||||
FakeHost.Names[StamKit1] = "Greater Stamina Kit";
|
||||
FakeHost.Names[StamKit2] = "Stamina Kit";
|
||||
FakeHost.Names[Gem] = "Sapphire";
|
||||
FakeHost.Containers[StamKit1] = Player;
|
||||
FakeHost.Containers[StamKit2] = Player;
|
||||
FakeHost.Containers[Gem] = Player;
|
||||
FakeHost.Skills[(Player, 6)] = (300, 2); // Healing
|
||||
var host = FakeHost.Create(Player);
|
||||
var s = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, PeaceModeForKits = false, UseKitsInMagicMode = true,
|
||||
KitMinSuccessPct = 0, StaminaKitMinSuccessPct = 0,
|
||||
};
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.SetCharacterSkills(skills);
|
||||
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 1000, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, v);
|
||||
b.SetCharacterSkills(skills);
|
||||
b.SetWorldObjectCache(Frozen(FakeHost.MakeCache(host, Player, new[] { StamKit1, StamKit2, Gem })));
|
||||
var attempt = typeof(BuffManager).GetMethod("AttemptStaminaKitUse",
|
||||
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic, Type.EmptyTypes)!;
|
||||
Check.True((bool)attempt.Invoke(b, null)!, "the stamina kit goes out");
|
||||
Check.Eq(LastKit(), StamKit1, "the Greater one first");
|
||||
Gone(StamKit1);
|
||||
b.OnChatWindowText("You heal yourself for 300 Stamina points. Your Greater Stamina Kit is used up.", 0);
|
||||
Thread.Sleep(750);
|
||||
Check.False(b.KitPending(), "the wait ends");
|
||||
Check.True((bool)attempt.Invoke(b, null)!, "the next stamina kit goes out");
|
||||
Check.Eq(LastKit(), StamKit2, "inside the walk's reuse: the used-up Greater kit is skipped");
|
||||
}
|
||||
}
|
||||
135
Tools/RynthCore.RynthAiHostTests/Tests/LootByNameTests.cs
Normal file
135
Tools/RynthCore.RynthAiHostTests/Tests/LootByNameTests.cs
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Loot by name (2026-11-02): the list, how a name matches, the file, and the attempt bookkeeping that keeps a
|
||||
// chest from being opened over and over or an unreachable item from being chased forever.
|
||||
internal static class LootByNameTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("loot by name: a plain name is the whole name, ignoring case; * makes it a part", Matching);
|
||||
r.Add("loot by name: the list adds, removes, refuses duplicates and empties; the radius is clamped", ListEdits);
|
||||
r.Add("loot by name: the settings string round-trips, tidies what was typed, and an empty one is an empty list", SettingsString);
|
||||
r.Add("loot by name: a use is tried a few times, a gap apart, then the object is left alone for a while", Attempts);
|
||||
r.Add("loot by name: an opened object stays finished until it is gone, then a new one is looted again", DoneUntilGone);
|
||||
r.Add("meta options: /vt opt set pickupmacrooff (and lootchestsmacrooff) turn Pickup with macro off on and off", PickupMacroOffOption);
|
||||
}
|
||||
|
||||
private static void Matching()
|
||||
{
|
||||
Check.True(LootByNameList.Matches("Unearthed Cache", "Unearthed Cache"), "exact");
|
||||
Check.True(LootByNameList.Matches("unearthed cache", "Unearthed Cache"), "case");
|
||||
Check.False(LootByNameList.Matches("Cache", "Unearthed Cache"), "a plain word is not part of a longer name");
|
||||
Check.True(LootByNameList.Matches("*cache*", "Unearthed Cache"), "contains");
|
||||
Check.True(LootByNameList.Matches("Unearthed*", "Unearthed Cache"), "starts with");
|
||||
Check.True(LootByNameList.Matches("*Cache", "Unearthed Cache"), "ends with");
|
||||
Check.False(LootByNameList.Matches("*", "Unearthed Cache"), "a lone * matches nothing");
|
||||
Check.False(LootByNameList.Matches("**", "Unearthed Cache"), "** matches nothing");
|
||||
Check.False(LootByNameList.Matches("", "Unearthed Cache"), "empty pattern");
|
||||
Check.False(LootByNameList.Matches("Unearthed Cache", ""), "empty name");
|
||||
}
|
||||
|
||||
private static void ListEdits()
|
||||
{
|
||||
var l = new LootByNameList();
|
||||
Check.True(l.IsEmpty, "starts empty");
|
||||
Check.True(l.Add(" \"Unearthed Cache\" "), "added, quotes and spaces trimmed");
|
||||
Check.False(l.Add("unearthed cache"), "a duplicate in another case is refused");
|
||||
Check.False(l.Add(" "), "blank refused");
|
||||
Check.Eq(l.Names.Count, 1, "one name");
|
||||
Check.True(l.MatchesAny("Unearthed Cache"), "matches");
|
||||
Check.False(l.MatchesAny("Chest"), "other names don't");
|
||||
Check.True(l.Remove("UNEARTHED CACHE"), "removed ignoring case");
|
||||
Check.False(l.Remove("Unearthed Cache"), "removing it again says no");
|
||||
for (int i = 0; i < LootByNameList.MaxNames; i++) l.Add("Thing " + i);
|
||||
Check.False(l.Add("One too many"), "the list is full");
|
||||
l.Clear();
|
||||
Check.True(l.IsEmpty, "cleared");
|
||||
l.SetRadius(5000);
|
||||
Check.Near(l.Radius, LootByNameList.MaxRadius, 0.001, "radius capped");
|
||||
l.SetRadius(-4);
|
||||
Check.Near(l.Radius, LootByNameList.MinRadius, 0.001, "radius floored");
|
||||
}
|
||||
|
||||
private static void SettingsString()
|
||||
{
|
||||
var l = new LootByNameList();
|
||||
l.Add("Unearthed Cache");
|
||||
l.Add("*Doubloon*");
|
||||
l.SetRadius(45);
|
||||
string saved = l.ToSettingString();
|
||||
Check.Eq(saved, "Unearthed Cache | *Doubloon*", "how the settings keep the list");
|
||||
var back = LootByNameList.Parse(saved, 45);
|
||||
Check.Eq(back.Names.Count, 2, "two names back");
|
||||
Check.True(back.MatchesAny("Marae Lassel Doubloon"), "the wildcard came back");
|
||||
Check.Near(back.Radius, 45, 0.001, "the radius is what was given");
|
||||
|
||||
Check.Eq(LootByNameList.Normalize(" a |b|| A | \"c\" "), "a | b | c", "blanks, repeats (any case) and quotes tidied, order kept");
|
||||
Check.True(LootByNameList.Parse("", 30).IsEmpty, "an empty string is an empty list");
|
||||
Check.True(LootByNameList.Parse(null, 30).IsEmpty, "so is null");
|
||||
Check.Near(LootByNameList.Parse("x", 0).Radius, LootByNameList.DefaultRadius, 0.001, "a zero radius means the default");
|
||||
Check.Near(LootByNameList.Parse("x", 9999).Radius, LootByNameList.MaxRadius, 0.001, "a huge radius is capped");
|
||||
}
|
||||
|
||||
private static void Attempts()
|
||||
{
|
||||
var t = new LootNameTracker();
|
||||
const int id = 77;
|
||||
long now = 1000;
|
||||
Check.True(t.CanUse(id, now), "first use is allowed");
|
||||
t.NoteUse(id, now);
|
||||
Check.False(t.CanUse(id, now + 1000), "not again inside the gap (the client is walking there)");
|
||||
for (int i = 2; i <= LootNameTracker.MaxUses; i++)
|
||||
{
|
||||
now += LootNameTracker.UseGapMs;
|
||||
Check.True(t.CanUse(id, now), $"use {i} after the gap");
|
||||
t.NoteUse(id, now);
|
||||
}
|
||||
now += LootNameTracker.UseGapMs;
|
||||
Check.False(t.CanUse(id, now), "the budget is spent");
|
||||
Check.True(t.Exhausted(id, now), "exhausted once the last gap has passed");
|
||||
t.GiveUp(id, now);
|
||||
Check.True(t.IsBlocked(id, now + 1000), "left alone");
|
||||
Check.False(t.CanUse(id, now + 1000), "no use while left alone");
|
||||
Check.False(t.IsBlocked(id, now + LootNameTracker.GiveUpMs + 1), "tried again after the wait");
|
||||
Check.True(t.CanUse(id, now + LootNameTracker.GiveUpMs + 1), "with a fresh budget");
|
||||
}
|
||||
|
||||
private static void DoneUntilGone()
|
||||
{
|
||||
var t = new LootNameTracker();
|
||||
t.NoteUse(5, 0);
|
||||
t.MarkDone(5);
|
||||
Check.True(t.IsBlocked(5, 999_999), "finished stays finished");
|
||||
Check.False(t.CanUse(5, 999_999), "and is not used again");
|
||||
t.Prune(id => id != 5); // it left the world
|
||||
Check.False(t.IsBlocked(5, 999_999), "forgotten once gone");
|
||||
Check.True(t.CanUse(5, 999_999), "the same id coming back is looted again");
|
||||
t.MarkDone(6);
|
||||
t.Prune(id => true);
|
||||
Check.True(t.IsBlocked(6, 0), "objects still there keep their state");
|
||||
}
|
||||
|
||||
// A meta that loots a chest with Looting off (the Dreamweave dig's cache) turns this on and leaves it on.
|
||||
private static void PickupMacroOffOption()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create();
|
||||
var settings = new LegacyUiSettings();
|
||||
var meta = new MetaManager(settings, host, new PlayerVitalsCache());
|
||||
Check.True(settings.LootChestsMacroOff, "on by default");
|
||||
meta.TryHandleVtCommand("/vt opt set pickupmacrooff false");
|
||||
Check.False(settings.LootChestsMacroOff, "the option turns it off");
|
||||
meta.TryHandleVtCommand("/vt opt set pickupmacrooff true");
|
||||
Check.True(settings.LootChestsMacroOff, "and on");
|
||||
meta.TryHandleVtCommand("/vt opt set lootchestsmacrooff false");
|
||||
Check.False(settings.LootChestsMacroOff, "the long name does the same");
|
||||
}
|
||||
}
|
||||
|
|
@ -42,8 +42,30 @@ internal static class LootChatLineTests
|
|||
r.Add("loot chat: pyreals, notes, comps and other stacks print the plain line only", StackablePlain);
|
||||
r.Add("loot chat: Describe looted items off prints the plain lines", SettingOffPlain);
|
||||
r.Add("loot chat: the settings survive a profile save and load, the settings map and /ra iteminfo loot", SettingsRoundTrip);
|
||||
r.Add("loot chat: Info text colour colours the described line only, in its own chat type", DescribedLineInTextColor);
|
||||
}
|
||||
|
||||
// 2026-11-05: Item Info's "Info text colour" covers the described "Looted" line too; the plain
|
||||
// lines (salvage by default, pyreals) are not item info and never ask for a colour.
|
||||
private static void DescribedLineInTextColor() => Clocked(() =>
|
||||
{
|
||||
List<string> looted = LootCorpse(s => { s.TextColor = "#EE921E"; s.LootChatType = 18; }, pluginCommands: true);
|
||||
string line = LineFor(looted, "Blunt Crossbow");
|
||||
int at = FakeHost.Chat.IndexOf(line);
|
||||
var asks = Enumerable.Range(0, FakeHost.PluginCommands.Count).Where(i => FakeHost.PluginCommands[i].Plugin == "RynthCore.Chat").ToList();
|
||||
Check.Eq(asks.Count, 1, "one colour asked for (the described keeper): " + string.Join(" | ", FakeHost.PluginCommands));
|
||||
if (asks.Count == 1)
|
||||
{
|
||||
Check.Eq(FakeHost.PluginCommands[asks[0]], ("RynthCore.Chat", "nextcolor", "#EE921E"), "the colour");
|
||||
Check.Eq(FakeHost.PluginCommandChatCounts[asks[0]], at, "asked for just before the line is written");
|
||||
}
|
||||
Check.Eq(FakeHost.ChatTypes[at], 18, "the line keeps its loot chat type");
|
||||
Check.True(line.Contains("(rule \"Keep bows\"): Gold"), "and its text: " + line);
|
||||
|
||||
looted = LootCorpse(pluginCommands: true);
|
||||
Check.False(FakeHost.PluginCommands.Any(c => c.Plugin == "RynthCore.Chat"), "no colour set: nothing asked (as before)");
|
||||
});
|
||||
|
||||
private static long _now;
|
||||
|
||||
private static void Clocked(Action body)
|
||||
|
|
@ -146,9 +168,10 @@ internal static class LootChatLineTests
|
|||
}
|
||||
|
||||
/// <summary>Opens the corpse and loots it, each item landing in the main pack as soon as its move goes out.</summary>
|
||||
private static List<string> LootCorpse(Action<MagItemInfoSettings>? configure = null)
|
||||
private static List<string> LootCorpse(Action<MagItemInfoSettings>? configure = null, bool pluginCommands = false)
|
||||
{
|
||||
World();
|
||||
FakeHost.PluginCommandCalls = pluginCommands;
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
configure?.Invoke(bot.S.ItemInfoSettings);
|
||||
|
|
|
|||
|
|
@ -52,6 +52,10 @@ internal static class LootCorpseTests
|
|||
r.Add("boost loot: our kill holds the next target until its corpse is looted (one kill, one loot)", BoostLootOneKillOneLoot);
|
||||
r.Add("boost loot: the wait ends after BoostLootKillWaitMs, for a close monster, and with Boost Loot off", BoostLootHoldLimits);
|
||||
r.Add("boost loot: looting the kill's corpse ends the wait; an older corpse does not", BoostLootWaitEndsOnKillCorpse);
|
||||
r.Add("death wait (11-08): Looting on, our kill holds the next target for the learned death + 1 s; Looting gets the tick", DeathWaitUsesLearnedTime);
|
||||
r.Add("death wait (11-08): not learned yet: 2.5 s + 1 s; the corpse's coming is timed and learned", DeathWaitDefaultAndLearns);
|
||||
r.Add("death wait (11-08): looting the kill's corpse ends it at once; a corpse the rules don't take ends it soon after it came", DeathWaitEndsOnLoot);
|
||||
r.Add("death wait (11-08): no corpse in the time: it carries on; a close attacker is fought; Looting off changes nothing", DeathWaitLimits);
|
||||
r.Add("monster ignore: a close Priority 0 monster neither holds combat nor starves the corpse", IgnoredMonsterDoesNotHoldLoot);
|
||||
r.Add("loot gate (R-20261025 727b): a predicted kill still alive holds the corpse; after its window combat has it again", PredictedKillHoldsCorpse);
|
||||
r.Add("loot gate (R-20261025 727b): the kill notice, health 0 or a hit after the swap settle a predicted kill at once", PredictedKillSettled);
|
||||
|
|
@ -607,6 +611,180 @@ internal static class LootCorpseTests
|
|||
Check.False((bool)bot.Call("BoostLootHoldsNewTarget")!, "so combat goes on at once");
|
||||
}
|
||||
|
||||
// ── The death wait (2026-11-08, Tom: the bot ran off from its kill, then turned round and ran back
|
||||
// when the corpse came after the death animation) ──
|
||||
|
||||
private const string Elemental = "Ancient Water Elemental";
|
||||
|
||||
/// <summary>BoostWorld with Boost Loot off and combat's hold wired to both holds, on a clock the test moves.</summary>
|
||||
private static Bot DeathWorld(float monsterMeters, out CombatManager combat, Func<long> clock)
|
||||
{
|
||||
RynthAiPlugin.CorpseClock = clock;
|
||||
var bot = BoostWorld(monsterMeters, withCorpse: false, out combat, boost: false);
|
||||
combat.HoldNewTarget = () => (bool)bot.Call("LootHoldsNewTarget")!;
|
||||
combat.HoldNewTargetWhy = () => (string)bot.Call("LootHoldWhy")!;
|
||||
return bot;
|
||||
}
|
||||
|
||||
private static void RestoreCorpseClock() => RynthAiPlugin.CorpseClock = static () => Environment.TickCount64;
|
||||
|
||||
private static BotActivity Arbiter(Bot bot, CombatManager combat)
|
||||
{
|
||||
bool wantLoot = bot.HasLootWork();
|
||||
var inputs = new ArbiterInputs(true, false, combat.HasEngageableTarget, wantLoot, false, true,
|
||||
combatEngaged: combat.IsUnderCloseAttack, deathWait: wantLoot && bot.Get<bool>("_deathWaitHeld"));
|
||||
return ActivityArbiter.Decide(in inputs);
|
||||
}
|
||||
|
||||
private static void DeathWaitUsesLearnedTime()
|
||||
{
|
||||
long now = 1_000_000;
|
||||
try
|
||||
{
|
||||
var bot = DeathWorld(15f, out var combat, () => now);
|
||||
bot.P.XpTableForTests.RecordDeath(Elemental, 1500);
|
||||
bot.Call("StartDeathWait", Elemental);
|
||||
Check.Eq(bot.Get<long>("_deathWaitMs"), 2500L, "the learned 1.5 s and 1 s more");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("waiting up to 2.5 s for the corpse of 'Ancient Water Elemental'") && l.Contains("learned over 1 kill")),
|
||||
"said once, plainly: " + FakeHost.Logs.LastOrDefault());
|
||||
combat.HandleCombatTrigger();
|
||||
Check.Eq(combat.activeTargetId, 0, "the next monster (15 m) is not locked while the corpse comes");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] next target waits: the kill's corpse comes first")), "combat says why");
|
||||
Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "Looting has the tick (no nav, no hunt walk)");
|
||||
now += 2400;
|
||||
Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "still at 2.4 s");
|
||||
now += 200;
|
||||
Check.Eq(Arbiter(bot, combat), BotActivity.Combat, "at 2.6 s, no corpse: it carries on");
|
||||
combat.HandleCombatTrigger();
|
||||
Check.Eq(combat.activeTargetId, unchecked((int)Monster), "and the next monster is locked");
|
||||
}
|
||||
finally { RestoreCorpseClock(); }
|
||||
}
|
||||
|
||||
private static void DeathWaitDefaultAndLearns()
|
||||
{
|
||||
long now = 2_000_000;
|
||||
try
|
||||
{
|
||||
var bot = DeathWorld(15f, out var combat, () => now);
|
||||
bot.Set("_loginComplete", true);
|
||||
string? killed = (string?)bot.Call("NoteMonsterStatsKill", $"You killed {Elemental}!");
|
||||
Check.Eq(killed, Elemental, "the kill notice names it");
|
||||
bot.Call("StartDeathWait", killed!);
|
||||
Check.Eq(bot.Get<long>("_deathWaitMs"), RynthAiPlugin.DeathWaitDefaultMs + RynthAiPlugin.DeathWaitExtraMs, "not learned: 2.5 s + 1 s");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("isn't learned yet")), "and says so");
|
||||
now += 2100;
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.Tick();
|
||||
bot.Call("NoteCorpseCreated", Corpse);
|
||||
Check.Eq(bot.Get<int>("_deathCorpseId"), unchecked((int)Corpse), "the kill's corpse is known");
|
||||
Check.Near(bot.P.XpTableForTests.DeathMs(Elemental) ?? 0, 2100, 1e-9, "its death learned: 2.1 s");
|
||||
Check.Eq(bot.P.MonsterStatsForTests.Get(Elemental)!.CorpseKills, 1, "and on the session's row");
|
||||
Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "the corpse is here and lootable: Looting");
|
||||
bot.Set("_targetCorpseId", unchecked((int)Corpse)); // the looter claims it
|
||||
now += 5000; // past the 3.5 s: the corpse is being looted, so it still holds
|
||||
Check.Eq(Arbiter(bot, combat), BotActivity.Looting, "while its corpse is claimed the wait goes on");
|
||||
}
|
||||
finally { RestoreCorpseClock(); }
|
||||
}
|
||||
|
||||
private static void DeathWaitEndsOnLoot()
|
||||
{
|
||||
long now = 3_000_000;
|
||||
try
|
||||
{
|
||||
var bot = DeathWorld(15f, out var combat, () => now);
|
||||
bot.Call("StartDeathWait", Elemental);
|
||||
now += 1500;
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.Tick();
|
||||
bot.Call("NoteCorpseCreated", Corpse);
|
||||
bot.HasLootWork();
|
||||
bot.Call("MarkCorpseCompleted", unchecked((int)Corpse));
|
||||
Check.Eq(bot.Get<long>("_deathWaitAt"), 0L, "looted: the wait is over at once");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("done waiting for the corpse of 'Ancient Water Elemental' after 1.5 s: its corpse is looted")),
|
||||
"said once: " + FakeHost.Logs.LastOrDefault());
|
||||
combat.HandleCombatTrigger();
|
||||
Check.Eq(combat.activeTargetId, unchecked((int)Monster), "and combat goes on");
|
||||
|
||||
// A corpse the rules don't take (another player's kill, My Kills Only): no longer than its coming and the look.
|
||||
var other = DeathWorld(15f, out var combat2, () => now);
|
||||
FakeHost.Strings[(Corpse, LongDescKey)] = "Killed by Someone Else.";
|
||||
other.Call("StartDeathWait", Elemental);
|
||||
now += 1500;
|
||||
other.Cache.OnCreateObject(Corpse);
|
||||
other.Cache.Tick();
|
||||
other.Call("NoteCorpseCreated", Corpse);
|
||||
Check.Eq(Arbiter(other, combat2), BotActivity.Looting, "just came: the loot rules get their look");
|
||||
now += RynthAiPlugin.DeathWaitDecideMs + 1;
|
||||
Check.Eq(Arbiter(other, combat2), BotActivity.Combat, "not ours: it carries on");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the loot rules don't take it")), "and says why");
|
||||
|
||||
// Ours and lootable, but the looter leaves it for the fight (monsters in range): no stand-off.
|
||||
// 2026-11-08: the wait held combat's next target while looting waited for combat; the
|
||||
// character stood 7.8 s, then the whole loot held it (16 s for a 1.2 s death).
|
||||
var standoff = DeathWorld(15f, out var combat3, () => now);
|
||||
FakeHost.Strings.Remove((Corpse, LongDescKey));
|
||||
standoff.Call("StartDeathWait", Elemental);
|
||||
now += 1200;
|
||||
standoff.Cache.OnCreateObject(Corpse);
|
||||
standoff.Cache.Tick();
|
||||
standoff.Call("NoteCorpseCreated", Corpse);
|
||||
Check.Eq(Arbiter(standoff, combat3), BotActivity.Looting, "just came: the looter gets its moment to claim it");
|
||||
Check.True(standoff.Get<List<int>>("_lootableInRange").Contains(unchecked((int)Corpse)), "it is lootable in range");
|
||||
Check.Eq(standoff.Get<int>("_targetCorpseId"), 0, "but not claimed");
|
||||
now += RynthAiPlugin.DeathWaitDecideMs + 1;
|
||||
Check.Eq(Arbiter(standoff, combat3), BotActivity.Combat, "unclaimed a second after it came: the fight goes on");
|
||||
combat3.HandleCombatTrigger();
|
||||
Check.Eq(combat3.activeTargetId, unchecked((int)Monster), "and the next monster is locked");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the looter leaves it for the fight")), "says why: " + FakeHost.Logs.LastOrDefault());
|
||||
}
|
||||
finally { RestoreCorpseClock(); }
|
||||
}
|
||||
|
||||
private static void DeathWaitLimits()
|
||||
{
|
||||
long now = 4_000_000;
|
||||
try
|
||||
{
|
||||
// No corpse ever: the wait ends at its time, once.
|
||||
var bot = DeathWorld(15f, out var combat, () => now);
|
||||
bot.Call("StartDeathWait", Elemental);
|
||||
Check.True((bool)bot.Call("LootHoldsNewTarget")!, "holding");
|
||||
now += RynthAiPlugin.DeathWaitDefaultMs + RynthAiPlugin.DeathWaitExtraMs;
|
||||
Check.False((bool)bot.Call("LootHoldsNewTarget")!, "past the time: no hold");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("no corpse came in 3.5 s")), 1, "said once");
|
||||
combat.HandleCombatTrigger();
|
||||
Check.Eq(combat.activeTargetId, unchecked((int)Monster), "the next monster is locked");
|
||||
bot.HasLootWork();
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("done waiting")), 1, "and not again");
|
||||
|
||||
// A monster 2 m away is fought whatever the wait.
|
||||
var close = DeathWorld(2f, out var combat2, () => now);
|
||||
close.Call("StartDeathWait", Elemental);
|
||||
combat2.HandleCombatTrigger();
|
||||
Check.Eq(combat2.activeTargetId, unchecked((int)Monster), "a monster at 2 m: locked");
|
||||
Check.Eq(Arbiter(close, combat2), BotActivity.Combat, "and fought");
|
||||
|
||||
// Looting off: nothing changes.
|
||||
var off = DeathWorld(15f, out var combat3, () => now);
|
||||
off.S.EnableLooting = false;
|
||||
off.Call("StartDeathWait", Elemental);
|
||||
Check.Eq(off.Get<long>("_deathWaitAt"), 0L, "no wait");
|
||||
Check.False(off.HasLootWork(), "no loot work");
|
||||
combat3.HandleCombatTrigger();
|
||||
Check.Eq(combat3.activeTargetId, unchecked((int)Monster), "the next monster is locked at once");
|
||||
Check.Eq(Arbiter(off, combat3), BotActivity.Combat, "combat as before");
|
||||
|
||||
// Rare-only looting: as Boost Loot, nothing to wait for.
|
||||
var rare = DeathWorld(15f, out _, () => now);
|
||||
rare.S.LootOnlyRareCorpses = true;
|
||||
rare.Call("StartDeathWait", Elemental);
|
||||
Check.Eq(rare.Get<long>("_deathWaitAt"), 0L, "Loot Only Rare Corpses: no wait");
|
||||
}
|
||||
finally { RestoreCorpseClock(); }
|
||||
}
|
||||
|
||||
private static void HeldByCombatLoggedOnce()
|
||||
{
|
||||
var bot = StarvationWorld(15f, out _);
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ using System.Runtime.CompilerServices;
|
|||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
|
|
@ -24,6 +25,11 @@ internal static class LootJumpTests
|
|||
private const uint CorpseA = 0x80263100;
|
||||
private const uint GemA = 0x80263101;
|
||||
private const uint GemA2 = 0x80263102;
|
||||
private const uint GemA3 = 0x80263103;
|
||||
private const uint PackStack = 0x80263120;
|
||||
private const uint KeyMaxStack = 11, KeyStack = 12;
|
||||
private const uint CorpseB = 0x80263110;
|
||||
private const uint GemB = 0x80263111;
|
||||
private const uint ItemTypeContainer = 0x200, ItemTypeGem = 0x800;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Test Looter";
|
||||
|
|
@ -36,6 +42,29 @@ internal static class LootJumpTests
|
|||
r.Add("jump loot: a corpse's only match jumps too (one tap jump)", SingleItemJumps);
|
||||
r.Add("jump loot: the setting off sends no jump", SettingOffNoJump);
|
||||
r.Add("jump loot: stamina of 5 or less sends no jump", LowStaminaNoJump);
|
||||
r.Add("jump loot: health under Heal At sends no jump (the flight would hold the heal)", LowHealthNoJump);
|
||||
r.Add("jump loot: a pickup answered with no bend-down releases the corpse at once; the next corpse is opened while still in the air", NoReturnNextCorpseInAir);
|
||||
r.Add("jump loot: after a pickup answered with no bend-down, the next item goes out at once in the air with no second jump (not queued); after the landing the next one jumps again", NoReturnNextItemJumps);
|
||||
r.Add("jump loot: a jump pickup answered only after a bend-down's time still waits for its Return before the corpse is released", SlowAnswerKeepsReturnWait);
|
||||
r.Add("jump loot: a bend-down answer inside an earlier jump's flight ends it: the next item is queued behind that Return, with no jump", SlowAnswerEndsAirWindow);
|
||||
r.Add("jump loot: a jump send's answer at 150 ms is confirmed then, and the next corpse opened then, not at 500 ms", JumpAnswerConfirmedOnArrival);
|
||||
r.Add("jump loot: a jump send merged into a pack stack keeps the floor (the client's request slot stays held for a merged-away object)", JumpMergeKeepsAnswerFloor);
|
||||
r.Add("jump loot: the no-bend-down window after an in-air send that rode an earlier jump is anchored to that jump", AirWindowAnchoredToTheInAirJump);
|
||||
r.Add("jump loot: a fast refusal that is not 'too busy' (a code-0 save-failed) does not turn the no-bend-down call off", NonBusyRefusalKeepsNoMotion);
|
||||
r.Add("jump loot: a send with no jump still waits PickupAnswerMinMs before its answer is believed", NoJumpKeepsAnswerFloor);
|
||||
r.Add("jump loot: a jump send's weak sign (an unowned stack, no pack stack grown) still waits PickupAnswerMinMs", JumpWeakSignKeepsAnswerFloor);
|
||||
r.Add("jump loot: a send with no jump answered at 100 ms still waits its Return before the next corpse", NoJumpFastAnswerWaitsReturn);
|
||||
r.Add("jump loot: a jump send refused, then resent (no jump), answered at 100 ms still waits its Return", ResentFastAnswerWaitsReturn);
|
||||
r.Add("jump loot: a move sent on a no-bend-down call and refused 'too busy' turns the call off: the next fast jump answer waits its Return", BusyRefusalTurnsNoMotionOff);
|
||||
r.Add("jump loot: an open sent on a no-bend-down call and refused 'too busy' turns the call off too", BusyOpenTurnsNoMotionOff);
|
||||
r.Add("jump loot: dropping the corpse claim (macro off) ends the no-bend-down window", ResetEndsAirWindow);
|
||||
r.Add("jump loot: a pickup sent while still in the air from the last loot jump takes no second jump; after the landing the next one jumps", NoSecondJumpInTheAir);
|
||||
r.Add("jump loot: the pickup's jump puts combat and buffs on hold until the landing (or the cap); loot never", JumpHoldsCombatNotLoot);
|
||||
r.Add("jump loot: portal space and a death drop the combat hold (no landing is coming)", PortalAndDeathEndJumpHold);
|
||||
r.Add("jump loot cadence: one move in flight at a time (the client's one inventory request), the next sent on the tick the answer shows", OneInFlightNextOnAnswerTick);
|
||||
r.Add("jump loot: the flight budget lets an early in-air send through with no new jump", FlightBudgetLetsEarlySendThrough);
|
||||
r.Add("jump loot: the flight budget holds a late in-air send until the landing, then jumps again", FlightBudgetHoldsLateSend);
|
||||
r.Add("jump loot: ResetCurrentLootItem clears the flight hold's logged flag", ResetClearsFlightHoldLogged);
|
||||
}
|
||||
|
||||
private static long _now;
|
||||
|
|
@ -43,45 +72,81 @@ internal static class LootJumpTests
|
|||
private static void Clocked(Action body)
|
||||
{
|
||||
var old = RynthAiPlugin.CorpseClock;
|
||||
var oldPace = ActionPacer.NowMs;
|
||||
_now = 50_000_000;
|
||||
RynthAiPlugin.CorpseClock = () => _now;
|
||||
ActionPacer.NowMs = () => _now; // the loot jump's air hold (ActionPacer.LootJumpAirborne) on the same clock
|
||||
ActionPacer.ForgetLootJump();
|
||||
try { body(); }
|
||||
finally { RynthAiPlugin.CorpseClock = old; }
|
||||
finally { RynthAiPlugin.CorpseClock = old; ActionPacer.NowMs = oldPace; ActionPacer.ForgetLootJump(); }
|
||||
}
|
||||
|
||||
private static void Gem(uint id)
|
||||
private static RynthAiPlugin _bot = null!; // the bot LootUntilFirstMove made
|
||||
private static RynthCoreHost _host; // and its host
|
||||
private static T Field<T>(string name) => (T)typeof(RynthAiPlugin).GetField(name, Any)!.GetValue(_bot)!;
|
||||
private static void SetField(string name, object v) => typeof(RynthAiPlugin).GetField(name, Any)!.SetValue(_bot, v);
|
||||
|
||||
/// <summary>The character's height: up in the air, or back on the ground (ActionPacer's landing check reads it).</summary>
|
||||
private static void Air(bool up) => FakeHost.PlayerPose = (Me0.Cell, Me0.X, Me0.Y, up ? Me0.Z + 1.0f : Me0.Z);
|
||||
|
||||
private static void Gem(uint id, uint container = CorpseA)
|
||||
{
|
||||
FakeHost.Names[id] = "Black Opal";
|
||||
FakeHost.ItemTypes[id] = ItemTypeGem;
|
||||
FakeHost.Containers[id] = CorpseA;
|
||||
FakeHost.Containers[id] = container;
|
||||
FakeHost.Appraised.Add(id);
|
||||
}
|
||||
|
||||
private static void World(bool secondGem)
|
||||
private static void Corpse(uint id, float dx)
|
||||
{
|
||||
FakeHost.Names[id] = "Corpse of Olthoi Swarm Drone";
|
||||
FakeHost.ItemTypes[id] = ItemTypeContainer;
|
||||
FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(id);
|
||||
FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z);
|
||||
}
|
||||
|
||||
private static void World(bool secondGem, bool secondCorpse, bool serverGates, bool thirdGem = false, bool packStack = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData
|
||||
FakeHost.CloseContainerCalls = true; // CloseContainer + GetGroundContainerId
|
||||
FakeHost.TapJumpCalls = true;
|
||||
FakeHost.ServerGates = serverGates; // GetCastBusyState: the client's motion queue
|
||||
FakeHost.LastUseDoneCalls = serverGates; // GetLastUseDone: the open's answer
|
||||
FakeHost.WeenieErrorCalls = true; // GetLastWeenieError: "You're too busy"
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
FakeHost.Names[CorpseA] = "Corpse of Olthoi Swarm Drone";
|
||||
FakeHost.ItemTypes[CorpseA] = ItemTypeContainer;
|
||||
FakeHost.Strings[(CorpseA, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(CorpseA);
|
||||
FakeHost.Positions[CorpseA] = (Me0.Cell, Me0.X + 1.0f, Me0.Y, Me0.Z);
|
||||
Corpse(CorpseA, 1.0f);
|
||||
Gem(GemA);
|
||||
if (secondGem) Gem(GemA2);
|
||||
if (thirdGem) Gem(GemA3);
|
||||
if (secondCorpse)
|
||||
{
|
||||
Corpse(CorpseB, 1.5f);
|
||||
Gem(GemB, CorpseB);
|
||||
}
|
||||
if (packStack)
|
||||
{
|
||||
// GemA is a stack of 1, and the pack holds a same-name stack of 3 it can merge into.
|
||||
FakeHost.Ints[(GemA, KeyMaxStack)] = 100;
|
||||
FakeHost.Ints[(GemA, KeyStack)] = 1;
|
||||
Gem(PackStack, Player);
|
||||
FakeHost.Ints[(PackStack, KeyMaxStack)] = 100;
|
||||
FakeHost.Ints[(PackStack, KeyStack)] = 3;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Opens the corpse and ticks until the first pickup's move has gone out.</summary>
|
||||
private static void LootUntilFirstMove(bool jumpEnabled, bool secondGem, uint stamina)
|
||||
/// <summary>Opens the corpse and ticks until the first pickup's move has gone out. Returns the tick.</summary>
|
||||
private static Action LootUntilFirstMove(bool jumpEnabled, bool secondGem, uint stamina, bool secondCorpse = false, bool serverGates = false, bool thirdGem = false, bool packStack = false, uint health = 100)
|
||||
{
|
||||
World(secondGem);
|
||||
World(secondGem, secondCorpse, serverGates, thirdGem, packStack);
|
||||
var host = FakeHost.Create(Player);
|
||||
_host = host;
|
||||
var bot = new RynthAiPlugin();
|
||||
_bot = bot;
|
||||
var s = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
|
||||
|
|
@ -98,7 +163,7 @@ internal static class LootJumpTests
|
|||
cache.SetPlayerId(Player);
|
||||
Set("_objectCache", cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = stamina, MaxMana = 100, CurrentMana = 100 });
|
||||
Set("_vitals", new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = health, MaxStamina = 100, CurrentStamina = stamina, MaxMana = 100, CurrentMana = 100 });
|
||||
|
||||
string profile = Path.Combine(Program.TempRoot, "loot-jump-test.json");
|
||||
var p = new LootProfile { Name = "gems" };
|
||||
|
|
@ -113,17 +178,512 @@ internal static class LootJumpTests
|
|||
Set("_activity", BotActivity.Looting);
|
||||
typeof(RynthAiPlugin).GetMethod("TickCorpseOpening", Any)!.Invoke(bot, null);
|
||||
}
|
||||
foreach (uint id in secondGem ? new[] { CorpseA, GemA, GemA2 } : new[] { CorpseA, GemA }) cache.OnCreateObject(id);
|
||||
cache.Tick();
|
||||
var ids = new List<uint> { CorpseA, GemA };
|
||||
if (secondGem) ids.Add(GemA2);
|
||||
if (thirdGem) ids.Add(GemA3);
|
||||
if (packStack) ids.Add(PackStack);
|
||||
if (secondCorpse) { ids.Add(CorpseB); ids.Add(GemB); }
|
||||
foreach (uint id in ids) cache.OnCreateObject(id);
|
||||
for (int i = 0; i < 50; i++) cache.Tick();
|
||||
Tick();
|
||||
Check.True(FakeHost.Uses.Contains(CorpseA), "the corpse is opened");
|
||||
FakeHost.UseDone(0);
|
||||
FakeHost.GroundContainer = CorpseA;
|
||||
bot.OnViewObjectContents(CorpseA);
|
||||
_openedAt = _now;
|
||||
for (int i = 0; i < 200 && FakeHost.ExternalMoves.Count == 0; i++) { _now += 20; Tick(); }
|
||||
Check.True(FakeHost.ExternalMoves.Count > 0, "a gem's move is sent");
|
||||
return Tick;
|
||||
}
|
||||
|
||||
private const long TickMs = 20;
|
||||
|
||||
private static long _openedAt; // CorpseA's contents arrived (LootUntilFirstMove)
|
||||
|
||||
/// <summary>
|
||||
/// The latest tick the next corpse's open may go out after the last item's confirm at
|
||||
/// <paramref name="confirmed"/>: at once, except that a corpse emptied sooner than the
|
||||
/// Loot Empty Corpse floor (max(200 ms, LootEmptyCorpseMs) from its open, a user setting, not
|
||||
/// a landing wait) is completed only then; a tick or two of slack.
|
||||
/// </summary>
|
||||
private static long NextOpenDue(long confirmed) => Math.Max(confirmed, _openedAt + 200) + 3 * TickMs;
|
||||
|
||||
private static bool Confirmed(uint id) => FakeHost.Logs.Any(l => l.Contains($"pickup confirmed for 0x{id:X8}"));
|
||||
|
||||
/// <summary>Ticks (TickMs each) until <paramref name="done"/> or <paramref name="maxMs"/> has passed.</summary>
|
||||
private static void TickUntil(Action tick, Func<bool> done, long maxMs)
|
||||
{
|
||||
long end = _now + maxMs;
|
||||
while (_now < end && !done()) { _now += TickMs; tick(); }
|
||||
}
|
||||
|
||||
private static void TickFor(Action tick, long ms)
|
||||
{
|
||||
long end = _now + ms;
|
||||
while (_now < end) { _now += TickMs; tick(); }
|
||||
}
|
||||
|
||||
// ACE with allow_jump_loot (Player_Inventory.GetPickupMotion): the move reaches the server while
|
||||
// the character is in the air, the pickup motion is Invalid, so the item moves at once (about the
|
||||
// round trip) and EnqueuePickupDone has no Return to play (IsBusy clears at once). What the
|
||||
// client's motion queue (GetCastBusyState) reads in the air is not known, so both readings are
|
||||
// run: busy (the jump's own motion for the whole flight) and idle.
|
||||
private static void NoReturnNextCorpseInAir() => Clocked(() =>
|
||||
{
|
||||
foreach (int airQueue in new[] { 1, 0 })
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true);
|
||||
Check.Eq(FakeHost.ExternalMoves[0].Id, GemA, $"[air queue {airQueue}] corpse A's gem goes first");
|
||||
long sent = _now;
|
||||
FakeHost.CastBusy = airQueue;
|
||||
TickFor(tick, 100);
|
||||
FakeHost.Containers[GemA] = Player; // the answer, no bend-down
|
||||
TickUntil(tick, () => Confirmed(GemA), 1000);
|
||||
Check.True(Confirmed(GemA), $"[air queue {airQueue}] the pickup is confirmed");
|
||||
long confirmed = _now;
|
||||
TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1500);
|
||||
Check.True(FakeHost.Uses.Contains(CorpseB), $"[air queue {airQueue}] the next corpse is opened");
|
||||
Check.True(_now <= NextOpenDue(confirmed),
|
||||
$"[air queue {airQueue}] the next corpse is opened at the confirm, not after a landing / Return wait: {_now - confirmed} ms after the confirm, {_now - sent} ms after the send");
|
||||
}
|
||||
});
|
||||
|
||||
// The second item goes out at once, still in the air, with no second jump (an air jump costs
|
||||
// stamina on ACE and does nothing for the pickup); once the character has landed, the next one
|
||||
// jumps again.
|
||||
private static void NoReturnNextItemJumps() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true);
|
||||
uint first = FakeHost.ExternalMoves[0].Id;
|
||||
Check.Eq(FakeHost.TapJumps, 1, "the first pickup jumps");
|
||||
Air(up: true);
|
||||
FakeHost.CastBusy = 1; // the jump's motion plays
|
||||
TickFor(tick, 100);
|
||||
FakeHost.Containers[first] = Player; // the answer, no bend-down
|
||||
TickUntil(tick, () => Confirmed(first), 1000);
|
||||
Check.True(Confirmed(first), "the first pickup is confirmed");
|
||||
long confirmed = _now;
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1500);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 2, "the second move is sent");
|
||||
uint second = FakeHost.ExternalMoves[1].Id;
|
||||
Check.True(_now - confirmed <= 3 * TickMs, $"at the confirm, not after the landing: {_now - confirmed} ms");
|
||||
Check.Eq(FakeHost.TapJumps, 1, "no jump in the air: " + Order());
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("queuing 0x")), "not queued behind a Return that ACE never plays for it");
|
||||
|
||||
// The second, sent in the air, answered with no bend-down; the character has landed by now.
|
||||
Air(up: false);
|
||||
TickFor(tick, ActionPacer.JumpLandMinMs);
|
||||
FakeHost.Containers[second] = Player;
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 3, 1500);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 3, "the third move is sent");
|
||||
int at = FakeHost.Order.IndexOf($"move:{FakeHost.ExternalMoves[2].Id:X8}");
|
||||
Check.True(at > 0 && FakeHost.Order[at - 1] == "tapjump", "landed: the third jumps again: " + Order());
|
||||
Check.Eq(FakeHost.TapJumps, 2, "two jumps in all");
|
||||
});
|
||||
|
||||
// The jump went out, but the answer took a bend-down's time (the server turned the character
|
||||
// first and it landed, so ACE played the pickup motion and its Return): that Return is waited out.
|
||||
private static void SlowAnswerKeepsReturnWait() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true);
|
||||
FakeHost.CastBusy = 1;
|
||||
TickFor(tick, 800);
|
||||
FakeHost.Containers[GemA] = Player; // answered after the bend-down; the Return plays
|
||||
TickUntil(tick, () => Confirmed(GemA), 1000);
|
||||
Check.True(Confirmed(GemA), "the pickup is confirmed");
|
||||
TickFor(tick, 600);
|
||||
Check.False(FakeHost.Uses.Contains(CorpseB), "no next open while the Return plays");
|
||||
FakeHost.CastBusy = 0;
|
||||
TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1000);
|
||||
Check.True(FakeHost.Uses.Contains(CorpseB), "the next corpse is opened once the character stands still");
|
||||
});
|
||||
|
||||
// First pickup in the air with no bend-down; the second, sent at once, is answered only after a
|
||||
// bend-down (the character had landed), so its Return plays: the third is queued behind that
|
||||
// Return (ACE NextPickup) and gets no jump, which would disturb the queue - the first jump's
|
||||
// flight window no longer counts.
|
||||
private static void SlowAnswerEndsAirWindow() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true);
|
||||
uint first = FakeHost.ExternalMoves[0].Id;
|
||||
FakeHost.CastBusy = 1;
|
||||
TickFor(tick, 100);
|
||||
FakeHost.Containers[first] = Player; // no bend-down
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1000);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 2, "the second move goes out at the first's confirm");
|
||||
uint second = FakeHost.ExternalMoves[1].Id;
|
||||
long secondSent = _now;
|
||||
TickFor(tick, 700);
|
||||
FakeHost.Containers[second] = Player; // answered after a bend-down: its Return plays
|
||||
TickUntil(tick, () => Confirmed(second), 1000);
|
||||
Check.True(Confirmed(second), "the second pickup is confirmed");
|
||||
Check.True(_now - secondSent < 1500 - 100, $"(still inside the first jump's flight window: {_now - secondSent} ms after the second send)");
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 3, 300);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 3, "the third move goes out during the Return");
|
||||
uint third = FakeHost.ExternalMoves[2].Id;
|
||||
int at = FakeHost.Order.IndexOf($"move:{third:X8}");
|
||||
Check.True(at > 0 && FakeHost.Order[at - 1] != "tapjump", "with no jump into the Return: " + Order());
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains($"queuing 0x{third:X8}")), "queued behind the second's Return");
|
||||
});
|
||||
|
||||
// -- The PickupAnswerMinMs floor --
|
||||
// The floor is ACE's pickup motion time. A jump send has no motion: its server-only answer
|
||||
// (the item in a pack, a pack stack grown, the object gone from the client) is believed on
|
||||
// arrival. Every other send, and a jump send's weak sign (an unowned stack the client still has),
|
||||
// keep the floor.
|
||||
|
||||
private const long AnswerAtMs = 150;
|
||||
|
||||
/// <summary>The ms from <paramref name="sent"/> to the tick the pickup of <paramref name="id"/> is confirmed (-1: never, in 1.5 s).</summary>
|
||||
private static long ConfirmAfter(Action tick, uint id, long sent)
|
||||
{
|
||||
TickUntil(tick, () => Confirmed(id), 1500);
|
||||
return Confirmed(id) ? _now - sent : -1;
|
||||
}
|
||||
|
||||
private static void JumpAnswerConfirmedOnArrival() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true);
|
||||
long sent = _now;
|
||||
TickFor(tick, AnswerAtMs - TickMs);
|
||||
FakeHost.Containers[GemA] = Player; // ACE's answer, no bend-down
|
||||
long confirmedAfter = ConfirmAfter(tick, GemA, sent);
|
||||
Check.True(confirmedAfter >= 0 && confirmedAfter <= AnswerAtMs + TickMs,
|
||||
$"confirmed on the tick the answer shows ({AnswerAtMs} ms), not at PickupAnswerMinMs: {confirmedAfter} ms after the send");
|
||||
long confirmed = _now;
|
||||
TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1000);
|
||||
Check.True(FakeHost.Uses.Contains(CorpseB) && _now <= NextOpenDue(confirmed),
|
||||
$"the next corpse is opened then too (or at the empty-corpse floor, 200 ms from the open): {_now - sent} ms after the send, {_now - _openedAt} ms after the open");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("no bend-down or Return to wait for")), "classed as a pickup with no bend-down");
|
||||
});
|
||||
|
||||
private static void JumpMergeKeepsAnswerFloor() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true, packStack: true);
|
||||
Check.Eq(FakeHost.ExternalMoves[0].Id, GemA, "the corpse gem goes");
|
||||
long sent = _now;
|
||||
TickFor(tick, AnswerAtMs - TickMs);
|
||||
// ACE StackableMerge: the corpse item is removed (gone from the client) and the pack stack grows.
|
||||
FakeHost.Containers.Remove(GemA);
|
||||
FakeHost.Names.Remove(GemA);
|
||||
FakeHost.Positions.Remove(GemA);
|
||||
FakeHost.Ints[(PackStack, KeyStack)] = 4;
|
||||
// The client's one-request slot is emptied only by an answer about that same object, and a
|
||||
// merged-away object is gone (RynthCore ClientActionGates): the slot can stay held, and a move
|
||||
// sent now would be dropped by the client. The floor is kept.
|
||||
long confirmedAfter = ConfirmAfter(tick, GemA, sent);
|
||||
Check.True(confirmedAfter >= RynthAiPlugin.PickupAnswerMinMs, $"a merge keeps the floor: confirmed {confirmedAfter} ms after the send");
|
||||
// (By the floor the gem is gone from the client, which names no stack: either merge wording.)
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("pickup confirmed") && l.Contains("merged into")), "as a merge into the pack stack: "
|
||||
+ (FakeHost.Logs.LastOrDefault(l => l.Contains("pickup confirmed")) ?? "(none)"));
|
||||
});
|
||||
|
||||
// The no-bend-down window after a pickup is anchored to the JUMP (it ends JumpLandMaxMs after
|
||||
// it), not to the send that confirmed: a second send that rode the first jump, in the air, must
|
||||
// not stretch it.
|
||||
private static void AirWindowAnchoredToTheInAirJump() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true);
|
||||
long jumpAt = _now;
|
||||
uint first = FakeHost.ExternalMoves[0].Id;
|
||||
Air(up: true);
|
||||
TickFor(tick, 100);
|
||||
FakeHost.Containers[first] = Player; // no bend-down
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 500);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 2, "the second goes out in the air");
|
||||
Check.Eq(FakeHost.TapJumps, 1, "riding the first jump");
|
||||
uint second = FakeHost.ExternalMoves[1].Id;
|
||||
long secondAt = _now;
|
||||
TickFor(tick, 100);
|
||||
FakeHost.Containers[second] = Player; // no bend-down
|
||||
TickUntil(tick, () => Confirmed(second), 500);
|
||||
Check.True(Confirmed(second), "the second is confirmed");
|
||||
Check.True(FakeHost.Logs.Count(l => l.Contains("no bend-down or Return to wait for")) == 2, "both as no-bend-down pickups");
|
||||
long until = Field<long>("_jumpPickupAirUntil");
|
||||
Check.True(Math.Abs(until - (jumpAt + ActionPacer.JumpLandMaxMs)) <= TickMs,
|
||||
$"the window ends JumpLandMaxMs after the jump: {until - jumpAt} ms from it (the second send was {secondAt - jumpAt} ms in)");
|
||||
});
|
||||
|
||||
// Only "You're too busy" (0x1D) proves the no-bend-down call wrong. A save-failed with
|
||||
// no code (a full pack, or anything else) that comes fast is not that evidence.
|
||||
private static void NonBusyRefusalKeepsNoMotion() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true);
|
||||
uint first = FakeHost.ExternalMoves[0].Id;
|
||||
TickFor(tick, 100 - TickMs);
|
||||
FakeHost.Containers[first] = Player; // no bend-down: the window opens
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1000);
|
||||
Check.True(Field<long>("_jumpPickupAirUntil") > _now, "the window is open");
|
||||
uint second = FakeHost.ExternalMoves[1].Id;
|
||||
Check.True(Field<bool>("_currentLootItemSentInAirWindow"), "the second went out in it");
|
||||
TickFor(tick, 100);
|
||||
FakeHost.WeenieError(0, 0x00A0, second); // InventoryServerSaveFailed, no code, 100 ms after the send
|
||||
TickFor(tick, 3 * TickMs);
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("the server played a bend-down after all")), "no distrust line");
|
||||
Check.Eq(Field<long>("_jumpNoMotionOffUntil"), 0L, "the call stays on");
|
||||
});
|
||||
|
||||
private static void NoJumpKeepsAnswerFloor() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: false, secondGem: false, stamina: 100u, serverGates: true);
|
||||
Check.Eq(FakeHost.TapJumps, 0, "no jump went out");
|
||||
long sent = _now;
|
||||
TickFor(tick, AnswerAtMs - TickMs);
|
||||
FakeHost.Containers[GemA] = Player;
|
||||
long confirmedAfter = ConfirmAfter(tick, GemA, sent);
|
||||
Check.True(confirmedAfter >= RynthAiPlugin.PickupAnswerMinMs,
|
||||
$"not believed before PickupAnswerMinMs ({RynthAiPlugin.PickupAnswerMinMs} ms): confirmed {confirmedAfter} ms after the send");
|
||||
});
|
||||
|
||||
// -- What JumpPickupHadNoMotion must not take for a no-bend-down pickup --
|
||||
|
||||
/// <summary>
|
||||
/// After the last item's confirm: the next corpse is not opened while the Return plays
|
||||
/// (CastBusy 1 for <paramref name="returnMs"/>), and is opened once it ends.
|
||||
/// </summary>
|
||||
private static void NextOpenWaitsReturn(Action tick, uint item, long returnMs, string what)
|
||||
{
|
||||
TickUntil(tick, () => Confirmed(item), 1500);
|
||||
Check.True(Confirmed(item), what + ": the pickup is confirmed");
|
||||
TickFor(tick, returnMs);
|
||||
Check.False(FakeHost.Uses.Contains(CorpseB), what + ": no next open while the Return plays");
|
||||
FakeHost.CastBusy = 0;
|
||||
TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1500);
|
||||
Check.True(FakeHost.Uses.Contains(CorpseB), what + ": the next corpse is opened once the character stands still");
|
||||
}
|
||||
|
||||
private static void NoJumpFastAnswerWaitsReturn() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: false, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true);
|
||||
TickFor(tick, 100 - TickMs);
|
||||
FakeHost.Containers[GemA] = Player;
|
||||
FakeHost.CastBusy = 1; // its Return
|
||||
NextOpenWaitsReturn(tick, GemA, 300, "no jump");
|
||||
});
|
||||
|
||||
private static void ResentFastAnswerWaitsReturn() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true);
|
||||
Check.Eq(FakeHost.TapJumps, 1, "the first send jumps");
|
||||
TickFor(tick, 40);
|
||||
FakeHost.WeenieError(0x1D); // YoureTooBusy
|
||||
FakeHost.WeenieError(0, 0x00A0, GemA); // InventoryServerSaveFailed(item)
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1000);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 2, "resent");
|
||||
Check.Eq(FakeHost.TapJumps, 1, "the resend goes without a jump");
|
||||
TickFor(tick, 100 - TickMs);
|
||||
FakeHost.Containers[GemA] = Player;
|
||||
FakeHost.CastBusy = 1;
|
||||
NextOpenWaitsReturn(tick, GemA, 300, "resent");
|
||||
});
|
||||
|
||||
// On a fast server a real bend-down can be 0.25-0.4 s, inside PickupAnswerMinMs.
|
||||
// A move sent on the no-bend-down call and refused 'too busy' proves the call wrong: it is off.
|
||||
private static void BusyRefusalTurnsNoMotionOff() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, secondCorpse: true, serverGates: true, thirdGem: true);
|
||||
uint first = FakeHost.ExternalMoves[0].Id;
|
||||
FakeHost.CastBusy = 1; // a fast real bend-down, then its Return
|
||||
TickFor(tick, 300 - TickMs);
|
||||
FakeHost.Containers[first] = Player; // answered at 300 ms: taken for no bend-down
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1000);
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("no bend-down or Return to wait for")), "the first is (wrongly) called no bend-down");
|
||||
uint second = FakeHost.ExternalMoves[1].Id;
|
||||
TickFor(tick, 40);
|
||||
FakeHost.WeenieError(0x1D); // the Return is playing: too busy
|
||||
FakeHost.WeenieError(0, 0x00A0, second);
|
||||
TickFor(tick, 2 * TickMs);
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the server played a bend-down after all")), "the call is turned off");
|
||||
Check.Eq(Field<long>("_jumpPickupAirUntil"), 0L, "and the window ended");
|
||||
|
||||
TickFor(tick, 400);
|
||||
FakeHost.CastBusy = 0; // the Return ends: the refused move goes again
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 3, 1000);
|
||||
Check.Eq(FakeHost.ExternalMoves[2].Id, second, "the refused move is resent");
|
||||
TickFor(tick, 150);
|
||||
FakeHost.Containers[second] = Player;
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 4, 1500);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 4, "the third goes");
|
||||
uint third = FakeHost.ExternalMoves[3].Id;
|
||||
int at = FakeHost.Order.IndexOf($"move:{third:X8}");
|
||||
Check.True(at > 0 && FakeHost.Order[at - 1] == "tapjump", "with a jump (landed by now): " + Order());
|
||||
|
||||
// Answered at 300 ms again: with the call off it waits its Return.
|
||||
FakeHost.CastBusy = 1;
|
||||
TickFor(tick, 300 - TickMs);
|
||||
FakeHost.Containers[third] = Player;
|
||||
NextOpenWaitsReturn(tick, third, 300, "after the call was turned off");
|
||||
});
|
||||
|
||||
private static void BusyOpenTurnsNoMotionOff() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, secondCorpse: true, serverGates: true);
|
||||
TickFor(tick, 300 - TickMs);
|
||||
FakeHost.Containers[GemA] = Player; // taken for no bend-down
|
||||
TickUntil(tick, () => FakeHost.Uses.Contains(CorpseB), 1000);
|
||||
Check.True(FakeHost.Uses.Contains(CorpseB), "the next corpse is opened on the call");
|
||||
Check.True(Field<int>("_openInAirWindowSeq") >= 0, "its answer is watched");
|
||||
FakeHost.UseDone(0x1D); // too busy: the Return was playing
|
||||
TickFor(tick, 2 * TickMs);
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the next corpse's open, sent on it, was refused as too busy")), "the call is turned off");
|
||||
Check.True(Field<long>("_jumpNoMotionOffUntil") > _now, "for a while");
|
||||
});
|
||||
|
||||
// The fastest cadence there is. The acclient holds ONE pending inventory request and refuses
|
||||
// every other move until the server's answer about that object ("You can only move or use one
|
||||
// item at a time", RynthCore ClientActionGates), and on a FastTick character ACE cancels a pickup
|
||||
// whose turn is still pending when the next one arrives (Player_Move2.CreateMoveToChain2 ->
|
||||
// CheckMoveToParams -> ActionCancelled). So never two at once: the next goes on the very tick
|
||||
// the last one's answer shows, with no tick lost in between.
|
||||
private static void OneInFlightNextOnAnswerTick() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true);
|
||||
Air(up: true);
|
||||
var answered = new HashSet<uint>();
|
||||
int maxInFlight = 1;
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, k + 1, $"move {k + 1} is out");
|
||||
uint id = FakeHost.ExternalMoves[k].Id;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
_now += TickMs; tick();
|
||||
maxInFlight = Math.Max(maxInFlight, FakeHost.ExternalMoves.Count - answered.Count);
|
||||
}
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, k + 1, $"nothing more while move {k + 1} is unanswered");
|
||||
FakeHost.Containers[id] = Player; // the answer arrives
|
||||
answered.Add(id);
|
||||
_now += TickMs; tick(); // the one tick that sees it
|
||||
Check.True(Confirmed(id), $"move {k + 1} confirmed on the tick its answer shows");
|
||||
if (k < 2)
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, k + 2, $"and move {k + 2} goes on that same tick");
|
||||
}
|
||||
Check.Eq(maxInFlight, 1, "never two moves in flight");
|
||||
});
|
||||
|
||||
// Dropping the corpse claim ends the no-bend-down window and the open watch.
|
||||
private static void ResetEndsAirWindow() => Clocked(() =>
|
||||
{
|
||||
LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true);
|
||||
SetField("_jumpPickupAirUntil", _now + 1000);
|
||||
SetField("_openInAirWindowSeq", 3);
|
||||
typeof(RynthAiPlugin).GetMethod("ResetCorpseTarget", Any)!.Invoke(_bot, null);
|
||||
Check.Eq(Field<long>("_jumpPickupAirUntil"), 0L, "the window is gone");
|
||||
Check.Eq(Field<int>("_openInAirWindowSeq"), -1, "and the open watch");
|
||||
});
|
||||
|
||||
// A pickup sent while the character is still in the air from the last loot jump takes no second
|
||||
// jump: the move arrives in the air anyway, and ACE HandleActionJump has no ground check, so an
|
||||
// air jump only costs stamina. Once the character has landed, the next pickup jumps again.
|
||||
private static void NoSecondJumpInTheAir() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true);
|
||||
long jumpAt = _now;
|
||||
uint first = FakeHost.ExternalMoves[0].Id;
|
||||
Check.Eq(FakeHost.TapJumps, 1, "the first pickup jumps");
|
||||
Air(up: true); // and stays up: no landing is seen
|
||||
TickFor(tick, 100);
|
||||
FakeHost.Containers[first] = Player; // the answer
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, ActionPacer.JumpLandMaxMs);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 2, "the second move is sent");
|
||||
Check.True(_now - jumpAt < ActionPacer.JumpLandMaxMs, $"(inside the first jump's flight: {_now - jumpAt} ms after it)");
|
||||
Check.True(ActionPacer.LootJumpAirborne(_host, out _), "(still in the air at the second send)");
|
||||
Check.Eq(FakeHost.TapJumps, 1, "no second jump in the air: " + Order());
|
||||
|
||||
uint second = FakeHost.ExternalMoves[1].Id;
|
||||
Air(up: false); // landed
|
||||
TickFor(tick, ActionPacer.JumpLandMinMs); // the landing check looks from JumpLandMinMs on
|
||||
FakeHost.Containers[second] = Player;
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 3, 3000);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 3, "the third move is sent");
|
||||
int at = FakeHost.Order.IndexOf($"move:{FakeHost.ExternalMoves[2].Id:X8}");
|
||||
Check.True(at > 0 && FakeHost.Order[at - 1] == "tapjump", "landed: the third jumps again: " + Order());
|
||||
Check.Eq(FakeHost.TapJumps, 2, "two jumps in all");
|
||||
});
|
||||
|
||||
// The loot half: the pickup's jump is what holds combat and buffs (ActionPacer); loot is not held.
|
||||
// CombatHookTests has the combat half (Think sends no attack while it holds).
|
||||
private static void JumpHoldsCombatNotLoot() => Clocked(() =>
|
||||
{
|
||||
bool pacer = ActionPacer.Enabled;
|
||||
try
|
||||
{
|
||||
LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true);
|
||||
Check.Eq(FakeHost.TapJumps, 1, "the pickup jumped");
|
||||
Check.True(ActionPacer.LootJumpAirborne(_host, out _), "and the loot code noted the jump for combat and buffs");
|
||||
// The pacer from here on, on this clock, with nothing of other tests' left in it
|
||||
// (CorpseCloseTests.PacerOn): only the jump can hold anything.
|
||||
ActionPacer.Reset(); ActionPacer.Enabled = true;
|
||||
MoveAudit.Reset(); MoveAudit.NowMs = () => _now;
|
||||
UseAudit.NowMs = () => _now;
|
||||
ActionPacer.NoteLootJump(_host); // (Reset dropped the pickup's; the same jump, noted again)
|
||||
var host = _host;
|
||||
Air(up: true);
|
||||
Check.True(ActionPacer.LootJumpAirborne(host, out string why), "in the air after the pickup's jump: " + why);
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff or heal waits");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "an emergency heal too (ACE refuses it in the air)");
|
||||
Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "loot does not");
|
||||
_now += ActionPacer.JumpLandMinMs;
|
||||
Check.True(ActionPacer.LootJumpAirborne(host, out _), "still up at the height check");
|
||||
Air(up: false);
|
||||
Check.False(ActionPacer.LootJumpAirborne(host, out _), "landed: the hold ends");
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "the buff goes");
|
||||
|
||||
// The cap: a landing never seen still ends the hold at JumpLandMaxMs.
|
||||
ActionPacer.NoteLootJump(host);
|
||||
Air(up: true);
|
||||
_now += ActionPacer.JumpLandMaxMs - 1;
|
||||
Check.True(ActionPacer.LootJumpAirborne(host, out _), "up, under the cap");
|
||||
_now += 1;
|
||||
Check.False(ActionPacer.LootJumpAirborne(host, out _), "the cap ends it");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ActionPacer.Enabled = pacer; ActionPacer.Reset();
|
||||
MoveAudit.Reset(); MoveAudit.NowMs = () => Environment.TickCount64;
|
||||
UseAudit.NowMs = () => Environment.TickCount64;
|
||||
}
|
||||
});
|
||||
|
||||
// The plugin's portal-space and death paths drop the hold: no landing is coming to end it.
|
||||
private static void PortalAndDeathEndJumpHold() => Clocked(() =>
|
||||
{
|
||||
var oldVitals = FakeHost.Vitals;
|
||||
try
|
||||
{
|
||||
LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true);
|
||||
var host = _host;
|
||||
const System.Reflection.BindingFlags Inst = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
||||
|
||||
Air(up: true);
|
||||
Check.True(ActionPacer.LootJumpAirborne(host, out _), "the pickup's jump holds combat");
|
||||
FakeHost.Portaling = true;
|
||||
typeof(RynthAiPlugin).GetMethod("NotePortalForPacer", Inst)!.Invoke(_bot, null);
|
||||
Check.False(ActionPacer.LootJumpAirborne(host, out _), "portal space ends the hold");
|
||||
FakeHost.Portaling = false;
|
||||
typeof(RynthAiPlugin).GetMethod("NotePortalForPacer", Inst)!.Invoke(_bot, null);
|
||||
|
||||
ActionPacer.NoteLootJump(host);
|
||||
Check.True(ActionPacer.LootJumpAirborne(host, out _), "a second jump holds again");
|
||||
FakeHost.Vitals = (0, 100, 0, 100, 0, 100);
|
||||
typeof(RynthAiPlugin).GetMethod("HoldForDeath", Inst)!.Invoke(_bot, null);
|
||||
Check.False(ActionPacer.LootJumpAirborne(host, out _), "the death ends the hold");
|
||||
}
|
||||
finally { FakeHost.Vitals = oldVitals; FakeHost.Portaling = false; Air(up: false); }
|
||||
});
|
||||
|
||||
private static void JumpWeakSignKeepsAnswerFloor() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true, packStack: true);
|
||||
Check.Eq(FakeHost.TapJumps, 1, "the jump went out");
|
||||
long sent = _now;
|
||||
TickFor(tick, AnswerAtMs - TickMs);
|
||||
FakeHost.Containers[GemA] = 0; // an unowned stack; the pack stack has not grown
|
||||
long confirmedAfter = ConfirmAfter(tick, GemA, sent);
|
||||
Check.True(confirmedAfter >= RynthAiPlugin.PickupAnswerMinMs,
|
||||
$"a weak sign keeps the floor ({RynthAiPlugin.PickupAnswerMinMs} ms): confirmed {confirmedAfter} ms after the send");
|
||||
});
|
||||
|
||||
private static string Order() => string.Join(",", FakeHost.Order);
|
||||
|
||||
private static void TwoItemJumpsBeforeMove() => Clocked(() =>
|
||||
|
|
@ -154,4 +714,63 @@ internal static class LootJumpTests
|
|||
LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 5u);
|
||||
Check.Eq(FakeHost.TapJumps + FakeHost.Jumps, 0, "stamina 5: no jump: " + Order());
|
||||
});
|
||||
|
||||
// The flight holds heals (ACE refuses them in the air), so health under Heal At (60 by
|
||||
// default) picks up with a bend-down; at Heal At the jump goes.
|
||||
private static void LowHealthNoJump() => Clocked(() =>
|
||||
{
|
||||
LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, health: 59u);
|
||||
Check.Eq(FakeHost.TapJumps + FakeHost.Jumps, 0, "health 59 (Heal At 60): no jump: " + Order());
|
||||
Check.False(ActionPacer.LootJumpAirborne(_host, out _), "nothing held for a landing");
|
||||
LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, health: 60u);
|
||||
Check.Eq(FakeHost.TapJumps, 1, "health 60: the jump goes: " + Order());
|
||||
});
|
||||
|
||||
// The flight budget (RynthAiPlugin.LootJumpFlightBudgetMs): a send in the air with no fresh jump
|
||||
// is predicted by jumpAge + the recent no-bend-down answer time.
|
||||
private static void FlightBudgetLetsEarlySendThrough() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true);
|
||||
uint first = FakeHost.ExternalMoves[0].Id;
|
||||
Air(up: true);
|
||||
TickFor(tick, 100);
|
||||
FakeHost.Containers[first] = Player; // answered 100 ms in, no bend-down
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 500);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 2, "the next send goes out at the confirm: " + Order());
|
||||
Check.Eq(FakeHost.TapJumps, 1, "in the air, with no new jump");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("holding 0x")), "no hold logged");
|
||||
});
|
||||
|
||||
private static void FlightBudgetHoldsLateSend() => Clocked(() =>
|
||||
{
|
||||
var tick = LootUntilFirstMove(jumpEnabled: true, secondGem: true, stamina: 100u, serverGates: true, thirdGem: true);
|
||||
uint first = FakeHost.ExternalMoves[0].Id;
|
||||
Air(up: true);
|
||||
TickFor(tick, 460);
|
||||
FakeHost.Containers[first] = Player; // answered ~480 ms in, still no bend-down (under the 500 ms mark)
|
||||
TickUntil(tick, () => Confirmed(first), 300);
|
||||
Check.True(Confirmed(first), "the first is confirmed");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("no bend-down or Return to wait for")), "as a no-bend-down pickup");
|
||||
// jumpAge ~500 plus an answer that took ~480 ms is over the budget: the next one waits for the landing.
|
||||
TickFor(tick, 400);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 1, "no send into the rest of the flight: " + Order());
|
||||
Check.Eq(FakeHost.TapJumps, 1, "no jump yet");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("holding 0x")), 1, "the hold is logged once");
|
||||
string hold = FakeHost.Logs.FirstOrDefault(l => l.Contains("holding 0x")) ?? "(none)";
|
||||
Check.True(hold.Contains("ms into the flight") && hold.Contains("takes about 4"), "naming jumpAge and the expected answer: " + hold);
|
||||
Air(up: false); // landed
|
||||
TickUntil(tick, () => FakeHost.ExternalMoves.Count >= 2, 1500);
|
||||
Check.Eq(FakeHost.ExternalMoves.Count, 2, "after the landing the next goes");
|
||||
int at = FakeHost.Order.IndexOf($"move:{FakeHost.ExternalMoves[1].Id:X8}");
|
||||
Check.True(at > 0 && FakeHost.Order[at - 1] == "tapjump", "with a fresh jump: " + Order());
|
||||
Check.Eq(FakeHost.TapJumps, 2, "two jumps in all");
|
||||
});
|
||||
|
||||
private static void ResetClearsFlightHoldLogged() => Clocked(() =>
|
||||
{
|
||||
LootUntilFirstMove(jumpEnabled: true, secondGem: false, stamina: 100u, serverGates: true);
|
||||
SetField("_flightHoldLogged", true);
|
||||
typeof(RynthAiPlugin).GetMethod("ResetCurrentLootItem", Any)!.Invoke(_bot, null);
|
||||
Check.False(Field<bool>("_flightHoldLogged"), "hold-logged flag cleared");
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,10 +40,43 @@ internal static class ManaStoneChoiceTests
|
|||
r.Add("mana tapping: a stone that failed two drains stays parked though it reads empty", FailedStoneStaysParked);
|
||||
r.Add("mana tapping: in a fight the drain waits (holding no loot, taking no second item); after it, the drain goes", DrainWaitsForFight);
|
||||
r.Add("mana stones: in a fight, worn gear that runs low is still refilled (armor without mana drops its spells)", RefillInFight);
|
||||
r.Add("eternal charge: tapping is ignored while it is in the pack, and applies again when it leaves", EternalIgnoresTapping);
|
||||
r.Add("eternal charge: a use with no answer is tried again in 20 s, not 5 minutes", EternalRetriesSoon);
|
||||
}
|
||||
|
||||
private const uint ChargeA = 0x80400031, ChargeB = 0x80400032, ChargeC = 0x80400033;
|
||||
private const string ManaCharge = "Great Mana Charge";
|
||||
private const string EternalCharge = "Eternal Mana Charge";
|
||||
|
||||
private static void EternalIgnoresTapping()
|
||||
{
|
||||
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (ChargeA, null) }, ringToDrain: true, maceMana: 5000, contents: true,
|
||||
before: _ => FakeHost.Names[ChargeA] = EternalCharge);
|
||||
rig.Run(3000);
|
||||
Check.True(rig.M.HasEternalChargeCached(), "the charge is seen");
|
||||
Check.Eq(rig.OnRing.Count, 0, "no drain, with an empty stone and an item waiting");
|
||||
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "nothing looted to tap");
|
||||
Check.False(rig.M.HoldsLootForDrain(), "the looter isn't held");
|
||||
Check.True(rig.S.EnableManaTapping, "the setting itself is left alone");
|
||||
|
||||
rig.Destroy(ChargeA);
|
||||
// The pack walk keeps its answer for a real second, and this test's clock runs faster than that.
|
||||
System.Threading.Thread.Sleep(1100);
|
||||
rig.Run(3000);
|
||||
Check.False(rig.M.HasEternalChargeCached(), "the charge is gone");
|
||||
Check.Eq(rig.OnRing.Count, 1, "tapping applies again: the item is drained");
|
||||
}
|
||||
|
||||
private static void EternalRetriesSoon()
|
||||
{
|
||||
using var rig = new Rig(tapping: false, new (uint, int?)[] { (ChargeA, null) }, stoneName: EternalCharge, maceMana: 0);
|
||||
rig.Run(1000);
|
||||
Check.Eq(rig.OnPlayer.Count, 1, "the charge goes on the gear");
|
||||
rig.Run(9000); // no answer: the action times out at 8 s
|
||||
Check.Eq(rig.OnPlayer.Count, 1, "parked after the timeout");
|
||||
rig.Run(21_000);
|
||||
Check.Eq(rig.OnPlayer.Count, 2, "tried again within 20 s of the timeout");
|
||||
}
|
||||
private const string NeedMore = "The Mana Stone gives 1,000 points of mana to the following items: Khanda-handled Mace.\nYou need 2,000 more mana to fully charge your items.";
|
||||
|
||||
// 2026-10-11 report: armor ran dry overnight with Mana Charges in the pack. The prime suspect
|
||||
|
|
|
|||
|
|
@ -25,10 +25,53 @@ internal static class MeleeStallTests
|
|||
r.Add("ghost: skipped until the server updates or creates it, it moves, or the landblock changes", GhostTrackerClears);
|
||||
r.Add("ghost: combat skips a marked ghost, counts it in the lock line, and takes it back when the server updates it", GhostSkippedByCombat);
|
||||
r.Add("melee interval: the first swing at a new target doesn't wait out the old 1000 ms", PhysicalNewTargetInterval);
|
||||
r.Add("melee reach: no closer after the re-issue = out of reach, left longer each time", ReachVerdict);
|
||||
r.Add("melee reach: walking closer, next to it, or another target is not out of reach", ReachWorking);
|
||||
r.Add("melee reach: after 5 in a row with no swing the ladder gets its turn (a wedged client); a swing starts over", ReachGivesWayToLadder);
|
||||
}
|
||||
|
||||
private static readonly DateTime T0 = new(2026, 10, 12, 20, 47, 35);
|
||||
|
||||
private static void ReachVerdict()
|
||||
{
|
||||
var w = new MeleeReachWatch();
|
||||
w.NoteReissue(1, 4.5);
|
||||
Check.True(w.CantReach(1, 4.6, DateTime.MinValue), "3 s later still 4.6 m off (the 2026-11-06 Olthoi behind a wall)");
|
||||
Check.Eq(w.NoteFailure(1, T0), 60, "first time: 60 s");
|
||||
w.NoteReissue(1, 4.5);
|
||||
Check.True(w.CantReach(1, 4.5, DateTime.MinValue), "again");
|
||||
Check.Eq(w.NoteFailure(1, T0), 120, "second time: longer");
|
||||
Check.Eq(w.NoteFailure(1, T0), 240, "third");
|
||||
Check.Eq(w.NoteFailure(1, T0), 300, "capped at 5 minutes");
|
||||
w.Forget(1);
|
||||
Check.Eq(w.NoteFailure(1, T0), 60, "forgotten: from the start");
|
||||
}
|
||||
|
||||
private static void ReachWorking()
|
||||
{
|
||||
var w = new MeleeReachWatch();
|
||||
Check.False(w.CantReach(1, 4.5, DateTime.MinValue), "no re-issue yet: nothing measured");
|
||||
w.NoteReissue(1, 9.0);
|
||||
Check.False(w.CantReach(1, 5.0, DateTime.MinValue), "closed 4 m: the walk is working");
|
||||
Check.False(w.CantReach(2, 9.0, DateTime.MinValue), "another target than the one measured");
|
||||
w.NoteReissue(1, 1.8);
|
||||
Check.False(w.CantReach(1, 1.8, DateTime.MinValue), "next to it: a stall here isn't about walking, the ladder keeps it");
|
||||
}
|
||||
|
||||
private static void ReachGivesWayToLadder()
|
||||
{
|
||||
var w = new MeleeReachWatch();
|
||||
for (int id = 1; id <= MeleeReachWatch.MaxStreak; id++)
|
||||
{
|
||||
w.NoteReissue(id, 4.5);
|
||||
Check.True(w.CantReach(id, 4.5, DateTime.MinValue), $"target {id} of the streak");
|
||||
w.NoteFailure(id, T0);
|
||||
}
|
||||
w.NoteReissue(9, 4.5);
|
||||
Check.False(w.CantReach(9, 4.5, DateTime.MinValue), "5 in a row and nothing swung: maybe the client, the ladder goes on");
|
||||
Check.True(w.CantReach(9, 4.5, T0.AddSeconds(1)), "a swing since: that streak is over");
|
||||
}
|
||||
|
||||
private static void EarlyStepWhenQuiet()
|
||||
{
|
||||
// Quiet (the caller's read: attacks sent, nothing animating, standing still).
|
||||
|
|
|
|||
294
Tools/RynthCore.RynthAiHostTests/Tests/MetaResumeTests.cs
Normal file
294
Tools/RynthCore.RynthAiHostTests/Tests/MetaResumeTests.cs
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType;
|
||||
using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Resume Meta After Reload (2026-11-07, Meta/MetaResume.cs). Tom: the meta should "restart in that state so
|
||||
// Drakkon doesn't recall back every time", and "there might be some variables set in default of other
|
||||
// states". A hot reload is modelled as what it is: the old MetaManager's runtime exported, then a NEW
|
||||
// LegacyUiSettings + MetaManager built the way OnLoginComplete builds them (state Default, macro off, the
|
||||
// meta's rules freshly loaded, no route), and the runtime restored into it.
|
||||
internal static class MetaResumeTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 11, 7, 20, 0, 0);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("meta resume: without it, a reload starts Default again and recalls (the reported problem)", WithoutResumeRecalls);
|
||||
r.Add("meta resume: a reload carries on in the state, with Default's variables, no second recall, the route at its waypoint", ResumeCarriesOn);
|
||||
r.Add("meta resume: after resuming, the meta runs on as before (timers continue, later states enter normally)", ResumedMetaRunsOn);
|
||||
r.Add("meta resume: call stack, watchdog and dictionaries come back", StackWatchdogDicts);
|
||||
r.Add("meta resume: stopwatches come back with their time (a map cooldown on a stopwatch fires again)", Stopwatches);
|
||||
r.Add("meta resume: a state entered but not yet applied is entered afresh", EntryPending);
|
||||
r.Add("meta resume: the file round-trips anything a variable holds; a torn file is nothing", FileFormat);
|
||||
r.Add("meta resume: only this client, this character, recently, with the same meta", WhyNotChecks);
|
||||
}
|
||||
|
||||
private static List<string> Loop() => new()
|
||||
{
|
||||
"uTank2 NAV 1.2", "1", "4",
|
||||
"0", "10", "20", "0", "0",
|
||||
"0", "10.1", "20", "0", "0",
|
||||
"0", "10.1", "20.1", "0", "0",
|
||||
"0", "10", "20.1", "0", "0",
|
||||
};
|
||||
|
||||
// A meta shaped like the reported one: Default sets the run up and recalls, then the hunt runs a route.
|
||||
private static List<MetaRule> Meta() => new()
|
||||
{
|
||||
new() { State = "Default", Condition = C.Always, Action = A.ExpressionAction, ActionData = "setvar[mode, hunt]" },
|
||||
new() { State = "Default", Condition = C.Always, Action = A.ChatCommand, ActionData = "/lifestone" },
|
||||
new() { State = "Default", Condition = C.SecondsInState_GE, ConditionData = "5", Action = A.SetMetaState, ActionData = "Hunt" },
|
||||
new() { State = "Hunt", Condition = C.Always, Action = A.EmbeddedNavRoute, ActionData = "Loop" },
|
||||
new() { State = "Hunt", Condition = C.Expression, ConditionData = "getvar[mode]==`hunt`", Action = A.ExpressionAction, ActionData = "setvar[seen, getvar[seen]+1]" },
|
||||
new() { State = "Hunt", Condition = C.SecondsInState_GE, ConditionData = "100", Action = A.SetMetaState, ActionData = "Default" },
|
||||
};
|
||||
|
||||
private sealed class Client
|
||||
{
|
||||
public LegacyUiSettings S = null!;
|
||||
public MetaManager M = null!;
|
||||
public DateTime Now = T0;
|
||||
private readonly RynthCoreHost _host;
|
||||
|
||||
public Client(RynthCoreHost host) { _host = host; Login(running: true); }
|
||||
|
||||
/// <summary>What OnLoginComplete builds: a new settings object and manager, Default, the meta loaded.</summary>
|
||||
public void Login(bool running)
|
||||
{
|
||||
S = new LegacyUiSettings { IsMacroRunning = running, EnableMeta = true, CurrentState = "Default" };
|
||||
S.MetaRules = Meta();
|
||||
S.EmbeddedNavs["Loop"] = Loop();
|
||||
S.CurrentMetaPath = @"C:\Games\RynthSuite\RynthAi\MetaFiles\Hunt.af";
|
||||
M = new MetaManager(S, _host, new PlayerVitalsCache()) { Clock = () => Now };
|
||||
// Stopwatches on the same fake clock. A new copy's tick count has nothing to do with the old one's.
|
||||
long reloadBase = ++_logins * 7_000_000L;
|
||||
M.Expressions.TickMs = () => reloadBase + (long)(Now - T0).TotalMilliseconds;
|
||||
}
|
||||
|
||||
private int _logins;
|
||||
|
||||
public void Tick(double seconds = 0) { Now = Now.AddSeconds(seconds); M.Think(); }
|
||||
|
||||
public MetaResumeState Export()
|
||||
{
|
||||
var s = new MetaResumeState { ProcessId = 1, ProcessStartUtcTicks = 2, CharacterId = 3, SavedUtcTicks = T0.Ticks };
|
||||
M.ExportRuntime(s);
|
||||
// Through the file format, as the plugin does.
|
||||
Check.True(MetaResumeStore.TryParse(MetaResumeStore.Serialize(s), out MetaResumeState back), "the save parses");
|
||||
return back;
|
||||
}
|
||||
|
||||
public string Var(string name) => M.Expressions.Variables.TryGetValue(name, out string? v) ? v : "(unset)";
|
||||
}
|
||||
|
||||
private static int Recalls() => FakeHost.ChatCommands.Count(c => c == "/lifestone");
|
||||
|
||||
/// <summary>Runs Default, moves to Hunt, loads the route and walks it to waypoint 2.</summary>
|
||||
private static Client Hunting()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var c = new Client(FakeHost.Create(playerId: 0x50000A01));
|
||||
c.Tick(); // Default: mode=hunt, /lifestone
|
||||
c.Tick(6); // 5 s in Default: -> Hunt
|
||||
c.Tick(); // Hunt: route loaded, seen=1
|
||||
c.S.ActiveNavIndex = 2; // nav walked on
|
||||
c.Tick(3);
|
||||
Check.Eq(c.S.CurrentState, "Hunt", "hunting");
|
||||
Check.Eq(Recalls(), 1, "one recall at the start");
|
||||
Check.Eq(c.Var("seen"), "1", "Hunt's rule ran once");
|
||||
return c;
|
||||
}
|
||||
|
||||
private static void WithoutResumeRecalls()
|
||||
{
|
||||
Client c = Hunting();
|
||||
c.Login(running: true); // a reload without resume: Default again
|
||||
c.Tick();
|
||||
Check.Eq(c.S.CurrentState, "Default", "back in Default");
|
||||
Check.Eq(Recalls(), 2, "and it recalls again");
|
||||
Check.Eq(c.S.CurrentRoute.Points.Count, 0, "the route is gone until Hunt loads it again");
|
||||
}
|
||||
|
||||
private static void ResumeCarriesOn()
|
||||
{
|
||||
Client c = Hunting();
|
||||
int pointsBefore = c.S.CurrentRoute.Points.Count;
|
||||
Check.Eq(pointsBefore, 4, "the route has its four waypoints");
|
||||
MetaResumeState saved = c.Export();
|
||||
c.Login(running: false); // the new copy: Default, macro off (Start Macro On Login off)
|
||||
c.M.RestoreRuntime(saved);
|
||||
for (int i = 0; i < 5; i++) c.Tick(1);
|
||||
|
||||
Check.Eq(c.S.CurrentState, "Hunt", "still hunting");
|
||||
Check.True(c.S.IsMacroRunning, "the macro runs as it did");
|
||||
Check.Eq(Recalls(), 1, "no second recall");
|
||||
Check.Eq(c.Var("mode"), "hunt", "Default's variable is there");
|
||||
Check.Eq(c.Var("seen"), "1", "Hunt's rules that had fired don't fire again");
|
||||
Check.Eq(c.S.CurrentRoute.Points.Count, pointsBefore, "the route is back");
|
||||
Check.Eq(c.S.ActiveNavIndex, 2, "at the same waypoint");
|
||||
Check.Eq(c.S.CurrentNavPath, "<embedded:Loop>", "the same route");
|
||||
Check.True(c.S.EnableNavigation, "nav on");
|
||||
}
|
||||
|
||||
private static void ResumedMetaRunsOn()
|
||||
{
|
||||
Client c = Hunting(); // 3 s into Hunt
|
||||
MetaResumeState saved = c.Export();
|
||||
Check.True(saved.SecondsInState >= 3 && saved.SecondsInState < 4, "seconds in state saved: " + saved.SecondsInState.ToString(CultureInfo.InvariantCulture));
|
||||
c.Login(running: false);
|
||||
c.M.RestoreRuntime(saved);
|
||||
c.Tick(90);
|
||||
Check.Eq(c.S.CurrentState, "Hunt", "93 s in: still Hunt");
|
||||
c.Tick(8); // 101 s in Hunt, counting from before the reload
|
||||
Check.Eq(c.S.CurrentState, "Default", "the 100 s timer counted across the reload");
|
||||
c.Tick();
|
||||
Check.Eq(Recalls(), 2, "entering Default for real runs it as always");
|
||||
}
|
||||
|
||||
// 2026-11-07: a reload kept $MapSW ("SW:4") but not the stopwatch, which then read 0 s for ever, so the
|
||||
// meta's "testvar[MapSW]==0||stopwatchelapsedseconds[$MapSW]>=$MapCool" never held and a treasure map
|
||||
// sat in the pack unused.
|
||||
private static void Stopwatches()
|
||||
{
|
||||
Client c = Hunting();
|
||||
string Eval(string e) => c.M.Expressions.Evaluate(e).ToString() ?? "";
|
||||
const string Cooldown = "testvar[MapSW]==0||stopwatchelapsedseconds[$MapSW]>=30";
|
||||
Eval("setvar[MapSW, stopwatchcreate[]];stopwatchstart[$MapSW]");
|
||||
Eval("setvar[Held, stopwatchcreate[]];stopwatchstart[$Held]");
|
||||
Eval("setvar[Idle, stopwatchcreate[]]");
|
||||
c.Tick(4);
|
||||
Eval("stopwatchstop[$Held]");
|
||||
c.Tick(6); // MapSW 10 s, Held stopped at 4 s, Idle never started
|
||||
Check.Eq(Eval("stopwatchelapsedseconds[$MapSW]"), "10", "10 s before the reload");
|
||||
Check.Eq(Eval(Cooldown), "0", "map cooldown still running");
|
||||
|
||||
MetaResumeState saved = c.Export();
|
||||
Check.Eq(saved.Stopwatches.Count, 3, "three stopwatches saved");
|
||||
c.Login(running: false);
|
||||
Check.Eq(Eval("stopwatchelapsedseconds[$MapSW]"), "0", "(a new copy knows no stopwatches)");
|
||||
c.M.RestoreRuntime(saved);
|
||||
|
||||
Check.Eq(Eval("stopwatchelapsedseconds[$MapSW]"), "10", "the stopwatch is back at 10 s");
|
||||
Check.Eq(Eval("stopwatchelapsedseconds[$Held]"), "4", "a stopped one keeps its time");
|
||||
Check.Eq(Eval("stopwatchelapsedseconds[$Idle]"), "0", "one never started is still at 0");
|
||||
c.Tick(21);
|
||||
Check.Eq(Eval("stopwatchelapsedseconds[$MapSW]"), "31", "it runs on after the reload");
|
||||
Check.Eq(Eval("stopwatchelapsedseconds[$Held]"), "4", "the stopped one doesn't");
|
||||
Check.Eq(Eval(Cooldown), "1", "the map cooldown ends (it never did before)");
|
||||
Eval("stopwatchstart[$Held]");
|
||||
c.Tick(2);
|
||||
Check.Eq(Eval("stopwatchelapsedseconds[$Held]"), "6", "a restored stopwatch starts again from its time");
|
||||
string fresh = Eval("stopwatchcreate[]");
|
||||
Check.True(!saved.Stopwatches.ContainsKey(fresh), "a new stopwatch never reuses a saved handle: " + fresh);
|
||||
|
||||
string text = MetaResumeStore.Serialize(saved);
|
||||
Check.False(MetaResumeStore.TryParse(text.Replace("sw=SW%3A0|", "sw=SW%3A0|x"), out _), "a bad stopwatch time is nothing");
|
||||
Check.True(MetaResumeStore.TryParse(text.Replace("sw=", "zz="), out MetaResumeState old), "an older save without stopwatches still parses");
|
||||
Check.Eq(old.Stopwatches.Count, 0, "(and has none)");
|
||||
}
|
||||
|
||||
private static void StackWatchdogDicts()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var c = new Client(FakeHost.Create(playerId: 0x50000A01));
|
||||
c.S.MetaRules = new List<MetaRule>
|
||||
{
|
||||
new() { State = "Default", Condition = C.Always, Action = A.ExpressionAction, ActionData = "setvar[d, dictcreate[]]" },
|
||||
new() { State = "Default", Condition = C.Always, Action = A.ExpressionAction, ActionData = "dictadditem[getvar[d], loot, 7]" },
|
||||
new() { State = "Default", Condition = C.Always, Action = A.CallMetaState, ActionData = "Buff" },
|
||||
new() { State = "Buff", Condition = C.Always, Action = A.SetWatchdog, ActionData = "Stuck;5;60" },
|
||||
new() { State = "Buff", Condition = C.SecondsInState_GE, ConditionData = "30", Action = A.ReturnFromCall },
|
||||
};
|
||||
c.Tick();
|
||||
c.Tick();
|
||||
c.Tick(2);
|
||||
Check.Eq(c.S.CurrentState, "Buff", "called into Buff");
|
||||
MetaResumeState saved = c.Export();
|
||||
Check.Eq(saved.CallStack.Count, 1, "one call deep");
|
||||
Check.True(saved.WatchdogActive, "watchdog armed: " + saved.WatchdogState);
|
||||
|
||||
var rules = c.S.MetaRules;
|
||||
c.Login(running: false);
|
||||
c.S.MetaRules = rules.Select(r => new MetaRule { State = r.State, Condition = r.Condition, ConditionData = r.ConditionData, Action = r.Action, ActionData = r.ActionData }).ToList();
|
||||
c.M.RestoreRuntime(saved);
|
||||
Check.Eq(c.M.Expressions.Evaluate("dictgetitem[getvar[d], loot]").ToString(), "7", "the dictionary behind the handle is back");
|
||||
c.Tick(29);
|
||||
Check.Eq(c.S.CurrentState, "Default", "the Return pops the restored stack");
|
||||
}
|
||||
|
||||
private static void EntryPending()
|
||||
{
|
||||
Client c = Hunting();
|
||||
c.M.Expressions.Evaluate("setmetastate[Default]"); // asked for, not applied by a tick yet
|
||||
MetaResumeState saved = c.Export();
|
||||
Check.True(saved.EntryPending, "pending entry saved");
|
||||
Check.Eq(saved.FiredRules.Count, 0, "the old state's fired marks aren't carried");
|
||||
c.Login(running: false);
|
||||
c.M.RestoreRuntime(saved);
|
||||
c.Tick();
|
||||
Check.Eq(c.S.CurrentState, "Default", "Default entered");
|
||||
Check.Eq(Recalls(), 2, "entered for real, as the tick would have");
|
||||
}
|
||||
|
||||
private static void FileFormat()
|
||||
{
|
||||
var s = new MetaResumeState
|
||||
{
|
||||
ProcessId = 4321, ProcessStartUtcTicks = 638_000_000_000_000_000, CharacterId = 0x50000A01, SavedUtcTicks = T0.Ticks,
|
||||
MetaPath = @"C:\Metas\Odd|name,with:colons.af", RulesSignature = "6:ABCDEF", MacroRunning = true,
|
||||
State = "Hunt | 2", SecondsInState = 12.5, SecondsInStateP = 40.25, EntryPending = false,
|
||||
WatchdogActive = true, WatchdogState = "Stuck", WatchdogMeters = 5, WatchdogSeconds = 60, WatchdogSecondsLeft = 41.5,
|
||||
NextDictId = 9, NavPath = "<embedded:Loop>", NavIndex = 3, NavEnabled = true,
|
||||
};
|
||||
s.CallStack.Add(("Default", 3.5));
|
||||
s.CallStack.Add(("Buff", null));
|
||||
s.FiredRules.AddRange(new[] { 0, 4, 7 });
|
||||
s.Variables["note"] = "line one\nline two | with, commas: and =";
|
||||
s.Variables["empty"] = "";
|
||||
s.Dicts["D:3"] = new Dictionary<string, string> { ["k:1"] = "v,1", ["k2"] = "" };
|
||||
s.RouteLines.AddRange(Loop());
|
||||
|
||||
string text = MetaResumeStore.Serialize(s);
|
||||
Check.True(MetaResumeStore.TryParse(text, out MetaResumeState b), "parses");
|
||||
Check.Eq(b.MetaPath, s.MetaPath, "path");
|
||||
Check.Eq(b.State, s.State, "state");
|
||||
Check.Eq(b.Variables["note"], s.Variables["note"], "a variable with newlines and separators");
|
||||
Check.Eq(b.Variables["empty"], "", "an empty variable");
|
||||
Check.Eq(b.Dicts["D:3"]["k:1"], "v,1", "a dictionary");
|
||||
Check.Eq(string.Join(";", b.CallStack.Select(x => x.State + "=" + (x.PSeconds?.ToString(CultureInfo.InvariantCulture) ?? "-"))), "Default=3.5;Buff=-", "call stack, bottom first");
|
||||
Check.Eq(string.Join(",", b.FiredRules), "0,4,7", "fired rules");
|
||||
Check.Eq(b.RouteLines.Count, s.RouteLines.Count, "route lines");
|
||||
Check.Eq(b.WatchdogSecondsLeft, 41.5, "watchdog time left");
|
||||
Check.False(MetaResumeStore.TryParse(text.Replace("end=1\n", ""), out _), "a torn file (no end) is nothing");
|
||||
Check.False(MetaResumeStore.TryParse("something else\n" + text, out _), "another header is nothing");
|
||||
Check.False(MetaResumeStore.TryParse(text.Replace("secs=12.5", "secs=abc"), out _), "a bad number is nothing");
|
||||
}
|
||||
|
||||
private static void WhyNotChecks()
|
||||
{
|
||||
List<MetaRule> rules = Meta();
|
||||
string sig = MetaResumeStore.Signature(rules);
|
||||
var s = new MetaResumeState { ProcessId = 10, ProcessStartUtcTicks = 20, CharacterId = 30, SavedUtcTicks = T0.Ticks, MetaPath = @"C:\M\a.af", RulesSignature = sig };
|
||||
DateTime now = T0.AddMinutes(1);
|
||||
Check.Null(MetaResumeStore.WhyNot(s, 10, 20, 30, @"c:\m\A.af", sig, now), "same client, character and meta (path case ignored)");
|
||||
Check.NotNull(MetaResumeStore.WhyNot(s, 11, 20, 30, @"C:\M\a.af", sig, now), "another client");
|
||||
Check.NotNull(MetaResumeStore.WhyNot(s, 10, 21, 30, @"C:\M\a.af", sig, now), "a restarted client with the same pid");
|
||||
Check.NotNull(MetaResumeStore.WhyNot(s, 10, 20, 31, @"C:\M\a.af", sig, now), "another character");
|
||||
Check.NotNull(MetaResumeStore.WhyNot(s, 10, 20, 30, @"C:\M\b.af", sig, now), "another meta");
|
||||
Check.NotNull(MetaResumeStore.WhyNot(s, 10, 20, 30, @"C:\M\a.af", sig, T0.AddMinutes(11)), "too old");
|
||||
rules[1].ActionData = "/recall";
|
||||
Check.NotNull(MetaResumeStore.WhyNot(s, 10, 20, 30, @"C:\M\a.af", MetaResumeStore.Signature(rules), now), "the meta's rules were edited");
|
||||
Check.Eq(MetaResumeStore.Signature(Meta()), sig, "the same rules sign the same");
|
||||
}
|
||||
}
|
||||
658
Tools/RynthCore.RynthAiHostTests/Tests/MissileAmmoSwapTests.cs
Normal file
658
Tools/RynthCore.RynthAiHostTests/Tests/MissileAmmoSwapTests.cs
Normal file
|
|
@ -0,0 +1,658 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.CreatureData;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The owner's report, 2026-11-07: "if you swap from bow to crossbow, it unwields your bow and your
|
||||
// infinite arrows and wields your crossbow, but not your infinite quarrels. So you dry fire."
|
||||
// Servers make their own infinite ammo: a single item that doesn't stack, UnlimitedUse (known once
|
||||
// appraised), names with no arrow/quarrel in them, sometimes no AmmoType at all. Combat wielded the
|
||||
// new ammo only right after its own launcher swap (30 s, and only when a fitting stack was found when
|
||||
// the swap began); any other empty quiver was left to ammo crafting, which knows ammo by name only.
|
||||
//
|
||||
// The fights here run against a small simulated ACE (Player_Inventory.CheckWeaponCollision): a
|
||||
// launcher is refused while ammo of another type (or of none) is on, ammo is refused when both it
|
||||
// and the launcher in hand have a type and they differ, taking ammo off in Missile mode drops to
|
||||
// peace, and Missile mode is refused with a launcher and nothing it can shoot.
|
||||
internal static class MissileAmmoSwapTests
|
||||
{
|
||||
private const uint Player = 0x50000F01;
|
||||
private const uint Monster = 0x80001F01;
|
||||
private const uint Wcid = 515151;
|
||||
private const uint Bow = 0x80000F01, Crossbow = 0x80000F02, Axe = 0x80000F03, Wand = 0x80000F04;
|
||||
private const uint InfArrows = 0x80000F11, InfQuarrels = 0x80000F12, DeadlyQuarrels = 0x80000F13, Arrows = 0x80000F14;
|
||||
private const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000, MissileSlot = 0x00400000, AmmoSlot = 0x00800000,
|
||||
HeldSlot = 0x01000000, TwoHandedSlot = 0x02000000;
|
||||
private const int MainSlots = MeleeSlot | MissileSlot | HeldSlot | TwoHandedSlot;
|
||||
private static int I(uint id) => unchecked((int)id);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("missile ammo (owner 2026-11-07): the rules - infinite, ammo of no type, the pick order", Rules);
|
||||
r.Add("missile ammo: the owner's report - bow + infinite arrows -> crossbow: arrows off, crossbow on, infinite quarrels on, then Missile", OwnersReport);
|
||||
r.Add("missile ammo: infinite ammo of no AmmoType and an odd name: off before the crossbow, the crossbow's own goes on (not the bow's)", UntypedInfinite);
|
||||
r.Add("missile ammo: UnlimitedUse on a stack (read after the appraisal) beats a better finite stack", UnlimitedUseWins);
|
||||
r.Add("missile ammo: a crossbow in hand with an empty quiver that combat didn't swap gets its quarrels (was left to crafting)", EmptyQuiverNotOurSwap);
|
||||
r.Add("missile ammo: the ammo still goes on when the crossbow lands after the 30 s swap window", AfterTheWindow);
|
||||
r.Add("missile ammo: arrows on with a crossbow in hand - no shot; the arrows off, then quarrels", WrongAmmoInHand);
|
||||
r.Add("missile ammo: no ammo the launcher can shoot - one chat line, no wield, no shot; quarrels found later go on", NoAmmoSaysOnce);
|
||||
r.Add("missile ammo: bow -> thrown weapon puts the arrows away first and wields no ammo for it; back to the bow, the arrows go on", ThrownWeapon);
|
||||
r.Add("missile ammo: Fast Weapon Swap from the wand (a monster while healing): arrows off, the crossbow, then quarrels, then Missile", FastSwapFromWand);
|
||||
r.Add("missile ammo: weapons back after heals puts the bow back with its arrows in the pack: they go on when the fight starts (Fast Weapon Swap on and off)", WeaponsBackAfterHeals);
|
||||
r.Add("missile ammo: a launcher named for bolts is not its own ammo (no dry fire)", LauncherNotItsOwnAmmo);
|
||||
r.Add("missile crafting: a crossbow not named so, with its odd-named quarrels on, is left alone (no arrows at it)", CraftingKnowsTypes);
|
||||
r.Add("missile crafting: odd-named quarrels in the pack are wielded for that crossbow", CraftingWieldsOddNamed);
|
||||
}
|
||||
|
||||
// ── Pure rules ────────────────────────────────────────────────────────────
|
||||
|
||||
private static void Rules()
|
||||
{
|
||||
Check.True(MissileAmmo.LooksInfinite(true, 50, 250, "Arrow"), "UnlimitedUse: infinite, stack or not");
|
||||
Check.True(MissileAmmo.LooksInfinite(false, 0, 0, "Stormcaller's Sheaf"), "a single item with no stack: infinite");
|
||||
Check.True(MissileAmmo.LooksInfinite(false, 1, 1, "Sheaf"), "a stack of 1 that can't grow: infinite");
|
||||
Check.False(MissileAmmo.LooksInfinite(false, 1, 250, "Arrow"), "the last arrow of a stack is not infinite");
|
||||
Check.True(MissileAmmo.LooksInfinite(false, 40, 250, "Infinite Deadly Prismatic Arrow"), "named so");
|
||||
|
||||
Check.True(MissileAmmo.CanShoot(2, 2), "quarrels in a crossbow");
|
||||
Check.True(MissileAmmo.CanShoot(2, 0), "ammo of no type: the server lets it on with any launcher");
|
||||
Check.False(MissileAmmo.CanShoot(2, 1), "arrows in a crossbow: no");
|
||||
Check.False(MissileAmmo.CanShoot(0, 0), "no launcher type: no");
|
||||
Check.False(MissileAmmo.Fits(2, 0), "but ammo of no type must come off before a launcher is wielded");
|
||||
|
||||
var rank = MissileAmmo.RankBy("", null);
|
||||
var deadly = new AmmoCandidate(1, "Deadly Quarrel", 2, "Pierce", false, 300, -1, false);
|
||||
var inf = new AmmoCandidate(2, "Stormcaller's Sheaf", 2, "", false, 1, -1, false, Infinite: true);
|
||||
var untypedInf = new AmmoCandidate(3, "Quiver of Echoes", 0, "", false, 1, -1, false, Infinite: true);
|
||||
var untypedInf2 = new AmmoCandidate(4, "Sylvan Volley", 0, "", false, 1, -1, false, Infinite: true);
|
||||
var arrows = new AmmoCandidate(5, "Arrow", 1, "", false, 1, -1, false);
|
||||
Check.Eq(MissileAmmo.Choose(2, "", new List<AmmoCandidate> { deadly, inf }, rank)?.Id, 2, "infinite beats a better finite stack (it never runs out)");
|
||||
Check.Eq(MissileAmmo.Choose(2, "", new List<AmmoCandidate> { deadly, inf with { Infinite = false } }, rank)?.Id, 1, "a single item flagged not infinite: quality decides as before");
|
||||
Check.Eq(MissileAmmo.Choose(2, "", new List<AmmoCandidate> { untypedInf, inf }, rank)?.Id, 2, "the launcher's own type before ammo of no type");
|
||||
Check.Eq(MissileAmmo.Choose(2, "", new List<AmmoCandidate> { arrows, untypedInf }, rank)?.Id, 3, "ammo of no type is still a pick");
|
||||
Check.Eq(MissileAmmo.Choose(2, "", new List<AmmoCandidate> { untypedInf2, untypedInf }, rank, demoteId: 4)?.Id, 3, "not the stack just taken off the other launcher");
|
||||
Check.Eq(MissileAmmo.Choose(2, "", new List<AmmoCandidate> { deadly with { ListIndex = 2 }, inf }, rank)?.Id, 1, "a listed stack still comes first");
|
||||
Check.Null(MissileAmmo.Choose(2, "", new List<AmmoCandidate> { arrows }, rank), "only arrows: nothing for a crossbow");
|
||||
}
|
||||
|
||||
// ── The simulated server ────────────────────────────────────────────────────
|
||||
|
||||
private static int SlotOf(uint id) => FakeHost.Ints.TryGetValue((id, 9), out int s) ? s : 0;
|
||||
private static int TypeOf(uint id) => FakeHost.Ints.TryGetValue((id, 50), out int t) ? t : 0;
|
||||
private static bool On(uint id, int slot) => FakeHost.Equipped.TryGetValue(id, out uint at) && (at & slot) != 0;
|
||||
private static uint InSlot(int slot) => FakeHost.Equipped.Where(kv => (kv.Value & slot) != 0).Select(kv => kv.Key).FirstOrDefault();
|
||||
private static bool IsThrown(uint id) => FakeHost.Ints.TryGetValue((id, 11), out int max) && max > 1 && SlotOf(id) == MissileSlot;
|
||||
private static bool IsLauncher(uint id) => SlotOf(id) == MissileSlot && !IsThrown(id);
|
||||
|
||||
private static void Wield(uint id, int slot)
|
||||
{
|
||||
FakeHost.Equipped[id] = (uint)slot;
|
||||
FakeHost.Ints[(id, 10)] = slot;
|
||||
EquippedState.Invalidate();
|
||||
}
|
||||
|
||||
private static void Unwield(uint id)
|
||||
{
|
||||
FakeHost.Equipped.Remove(id);
|
||||
FakeHost.Ints.Remove((id, 10));
|
||||
EquippedState.Invalidate();
|
||||
}
|
||||
|
||||
/// <summary>The fake server's view: can the character shoot now (a launcher and ammo it takes, or a thrown weapon)?</summary>
|
||||
private static bool ServerCanShoot()
|
||||
{
|
||||
uint main = InSlot(MissileSlot);
|
||||
if (main == 0) return false;
|
||||
if (IsThrown(main)) return true;
|
||||
uint ammo = InSlot(AmmoSlot);
|
||||
return ammo != 0 && (TypeOf(ammo) == 0 || TypeOf(main) == 0 || TypeOf(ammo) == TypeOf(main));
|
||||
}
|
||||
|
||||
private sealed class Server
|
||||
{
|
||||
public double AnswerMs = 80, StanceMs = 400;
|
||||
/// <summary>Extra time before the server answers a use of this item (a slow server).</summary>
|
||||
public readonly Dictionary<uint, double> SlowUse = new();
|
||||
public readonly List<string> Refusals = new();
|
||||
private readonly List<(double At, Action Do)> _due = new();
|
||||
private int _moves, _wields, _uses, _modes;
|
||||
|
||||
public void Observe(double now)
|
||||
{
|
||||
while (FakeHost.CombatModeRequests.Count > _modes)
|
||||
{
|
||||
int mode = FakeHost.CombatModeRequests[_modes++];
|
||||
_due.Add((now + StanceMs, () =>
|
||||
{
|
||||
// ACE: a launcher with nothing it can shoot can't enter Missile mode.
|
||||
if (mode == CombatMode.Missile && !ServerCanShoot()) { Refusals.Add("Missile mode with nothing to shoot"); return; }
|
||||
FakeHost.CombatModeValue = mode;
|
||||
}));
|
||||
}
|
||||
while (FakeHost.Moves.Count > _moves)
|
||||
{
|
||||
uint id = FakeHost.Moves[_moves++].Id;
|
||||
_due.Add((now + AnswerMs, () =>
|
||||
{
|
||||
bool wasAmmo = On(id, AmmoSlot);
|
||||
Unwield(id);
|
||||
// ACE TryDequipObjectWithNetworking: ammo off in Missile mode drops to peace (a thrown weapon keeps Missile).
|
||||
if (wasAmmo && FakeHost.CombatModeValue == CombatMode.Missile && !IsThrown(InSlot(MissileSlot)))
|
||||
FakeHost.CombatModeValue = CombatMode.NonCombat;
|
||||
}));
|
||||
}
|
||||
while (FakeHost.Wields.Count > _wields)
|
||||
{
|
||||
var w = FakeHost.Wields[_wields++];
|
||||
_due.Add((now + AnswerMs, () => TryWield(w.Id, (int)w.Mask, clientUse: false)));
|
||||
}
|
||||
while (FakeHost.Uses.Count > _uses)
|
||||
{
|
||||
uint id = FakeHost.Uses[_uses++];
|
||||
double extra = SlowUse.TryGetValue(id, out double x) ? x : 0;
|
||||
_due.Add((now + AnswerMs * 2 + extra, () => TryWield(id, SlotOf(id), clientUse: true)));
|
||||
}
|
||||
}
|
||||
|
||||
public void Answer(double now)
|
||||
{
|
||||
foreach (var d in _due.Where(d => d.At <= now).ToList()) { d.Do(); _due.Remove(d); }
|
||||
}
|
||||
|
||||
private void TryWield(uint id, int slot, bool clientUse)
|
||||
{
|
||||
if (slot == 0) return;
|
||||
// The client's own use takes off what's in the way in the hands (never the ammo: ACE's check below).
|
||||
if (clientUse && (slot & MainSlots) != 0)
|
||||
foreach (uint other in FakeHost.Equipped.Where(kv => kv.Key != id && (kv.Value & MainSlots) != 0).Select(kv => kv.Key).ToList()) Unwield(other);
|
||||
if (clientUse && slot == AmmoSlot && InSlot(AmmoSlot) is uint old && old != 0 && old != id)
|
||||
Unwield(old);
|
||||
if (slot == MissileSlot && IsLauncher(id))
|
||||
{
|
||||
uint ammo = InSlot(AmmoSlot);
|
||||
if (TypeOf(id) != 0 && ammo != 0 && TypeOf(ammo) != TypeOf(id)) { Refuse(id, $"launcher 0x{id:X8} with ammo 0x{ammo:X8} of type {TypeOf(ammo)} on"); return; }
|
||||
}
|
||||
if (slot == AmmoSlot)
|
||||
{
|
||||
uint main = InSlot(MissileSlot);
|
||||
if (main != 0 && TypeOf(main) != 0 && TypeOf(id) != 0 && TypeOf(main) != TypeOf(id)) { Refuse(id, $"ammo 0x{id:X8} of type {TypeOf(id)} at launcher type {TypeOf(main)}"); return; }
|
||||
}
|
||||
if (slot == HeldSlot && FakeHost.Equipped.Any(kv => kv.Key != id && (kv.Value & (MeleeSlot | ShieldSlot | MissileSlot | TwoHandedSlot)) != 0))
|
||||
{ Refuse(id, "a caster with a hand full"); return; }
|
||||
if ((slot & MainSlots) != 0 && FakeHost.Equipped.Any(kv => kv.Key != id && (kv.Value & MainSlots) != 0))
|
||||
{ Refuse(id, $"0x{id:X8} with the main hand full"); return; }
|
||||
Wield(id, slot);
|
||||
}
|
||||
|
||||
private void Refuse(uint id, string why)
|
||||
{
|
||||
Refusals.Add(why);
|
||||
FakeHost.WeenieError(0x0029, 0x00A0, id);
|
||||
}
|
||||
}
|
||||
|
||||
// ── The rig ───────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Sim : IDisposable
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly CombatManager C;
|
||||
public readonly MonsterDamageStore Store = new();
|
||||
public readonly Server Sv = new();
|
||||
public readonly WeaponSwapGate Gate;
|
||||
public readonly WorldObject Target = new(I(Monster), "Drudge Skulker", AcObjectClass.Monster);
|
||||
public double SimMs;
|
||||
private static readonly DateTime T0 = new(2026, 11, 7, 20, 0, 0);
|
||||
public DateTime Now => T0.AddMilliseconds(SimMs);
|
||||
public readonly List<string> Trace = new();
|
||||
/// <summary>Times combat said "ready to attack" while the fake server had nothing to shoot.</summary>
|
||||
public int DryReady;
|
||||
private const BindingFlags NP = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
private readonly MethodInfo _equip = typeof(CombatManager).GetMethod("EquipWeaponAndSetStance", NP)!;
|
||||
private readonly MethodInfo _tickSwap = typeof(CombatManager).GetMethod("TickRearmSwap", NP)!;
|
||||
|
||||
/// <param name="arrange">The items and what is on, before the host and cache read them.</param>
|
||||
public Sim(Action arrange, uint[] listed, int mode = CombatMode.Missile, bool fastSwap = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.WieldCalls = true;
|
||||
FakeHost.EquippedCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.WeenieErrorCalls = true;
|
||||
FakeHost.CombatModeValue = mode;
|
||||
RynthClock.TestNow = () => Now;
|
||||
EquippedState.Clock = () => (long)SimMs + 100_000;
|
||||
ActionPacer.Enabled = false;
|
||||
|
||||
Item(Bow, "Longbow", 0x100, MissileSlot, ammoType: 1);
|
||||
Item(Crossbow, "Heavy Crossbow", 0x100, MissileSlot, ammoType: 2);
|
||||
Item(Wand, "Wand", 0x8000, HeldSlot);
|
||||
arrange();
|
||||
FakeHost.Wcids[Monster] = Wcid;
|
||||
|
||||
S = new LegacyUiSettings { IsMacroRunning = true, FastWeaponSwap = fastSwap, PeaceModeWhenIdle = false, WieldUnlistedWandWhenNoneListed = false };
|
||||
S.ItemRules = listed.Select(i => new ItemRule { Id = I(i), Name = FakeHost.Names[i], Element = "", ElementSource = "", Action = "Weapon" }).ToList();
|
||||
var host = FakeHost.Create(Player);
|
||||
var ids = new[] { Bow, Crossbow, Axe, Wand, InfArrows, InfQuarrels, DeadlyQuarrels, Arrows }.Where(FakeHost.Names.ContainsKey).ToList();
|
||||
var cache = FakeHost.MakeCache(host, Player, ids);
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
C.SetDamageStores(null, Store);
|
||||
C.CanCastOverride = _ => false;
|
||||
C.OpenPackOverride = () => I(Player);
|
||||
C.OffhandReadMs = 0;
|
||||
C.SwapTracker.MinDwellMs = 0;
|
||||
C.LastVitalCastAt = () => DateTime.MinValue;
|
||||
C.BuffingWantsTick = () => false;
|
||||
C.SwapBurstEnabled = () => false;
|
||||
Gate = new WeaponSwapGate { MinIntervalMs = 0, NowMs = () => (long)SimMs + 100_000 };
|
||||
C.SetWeaponSwapGate(Gate);
|
||||
typeof(CombatManager).GetField("_activeTargetId", NP)!.SetValue(C, I(Monster));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
RynthClock.TestNow = null;
|
||||
EquippedState.Clock = null;
|
||||
EquippedState.Invalidate();
|
||||
ActionPacer.Enabled = false;
|
||||
ActionPacer.Reset();
|
||||
}
|
||||
|
||||
public static void Item(uint id, string name, uint itemType, int validSlots, int ammoType = 0, int stack = 0, int maxStack = 0)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = itemType;
|
||||
FakeHost.Ints[(id, 9)] = validSlots;
|
||||
if (ammoType != 0) FakeHost.Ints[(id, 50)] = ammoType;
|
||||
if (stack != 0) FakeHost.Ints[(id, 12)] = stack;
|
||||
if (maxStack != 0) FakeHost.Ints[(id, 11)] = maxStack;
|
||||
}
|
||||
|
||||
/// <summary>The Damage tab's weapon for this monster.</summary>
|
||||
public void Wants(uint weapon) => Store.SetManualWeapon(Wcid, weapon);
|
||||
|
||||
/// <summary>One plugin tick (25 ms): the server's answers, the hands-swap heartbeat, combat's equip.</summary>
|
||||
public bool Tick()
|
||||
{
|
||||
Sv.Answer(SimMs);
|
||||
_tickSwap.Invoke(C, null);
|
||||
bool ready = (bool)_equip.Invoke(C, new object[] { Target, "Auto" })!;
|
||||
if (ready && !ServerCanShoot()) DryReady++;
|
||||
Sv.Observe(SimMs);
|
||||
string line = $"mode={FakeHost.CombatModeValue} on={string.Join(",", FakeHost.Equipped.Keys.Select(k => FakeHost.Names[k]))} ready={ready}";
|
||||
if (Trace.Count == 0 || !Trace[^1].EndsWith(line, StringComparison.Ordinal)) Trace.Add($"{SimMs:0} {line}");
|
||||
SimMs += 25;
|
||||
return ready;
|
||||
}
|
||||
|
||||
/// <summary>Ticks until combat is ready to attack in Missile mode (true) or <paramref name="maxMs"/> pass.</summary>
|
||||
public bool RunUntilShooting(double maxMs)
|
||||
{
|
||||
double end = SimMs + maxMs;
|
||||
while (SimMs <= end)
|
||||
if (Tick() && FakeHost.CombatModeValue == CombatMode.Missile) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Run(double ms) { double end = SimMs + ms; while (SimMs <= end) Tick(); }
|
||||
|
||||
public string Why() =>
|
||||
Environment.NewLine + string.Join(Environment.NewLine, Trace.TakeLast(20)) + Environment.NewLine +
|
||||
string.Join(Environment.NewLine, FakeHost.Logs.Where(l => l.Contains("[EquipDiag]")).TakeLast(20)) +
|
||||
(Sv.Refusals.Count > 0 ? Environment.NewLine + "refused: " + string.Join("; ", Sv.Refusals) : "");
|
||||
}
|
||||
|
||||
// ── The fights ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Infinite ammo as a custom server makes it: one item, no stack, a name of its own, its AmmoType set.</summary>
|
||||
private static void CustomInfinite()
|
||||
{
|
||||
Sim.Item(InfArrows, "Sylvan Volley", 0x100, AmmoSlot, ammoType: 1);
|
||||
Sim.Item(InfQuarrels, "Stormcaller's Sheaf", 0x100, AmmoSlot, ammoType: 2);
|
||||
Sim.Item(DeadlyQuarrels, "Deadly Quarrel", 0x100, AmmoSlot, ammoType: 2, stack: 80, maxStack: 250);
|
||||
}
|
||||
|
||||
private static void OwnersReport()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
CustomInfinite();
|
||||
Wield(Bow, MissileSlot);
|
||||
Wield(InfArrows, AmmoSlot);
|
||||
}, new[] { Bow, Crossbow });
|
||||
sim.Wants(Crossbow);
|
||||
|
||||
Check.True(sim.RunUntilShooting(6000), "shooting with the crossbow within 6 s:" + sim.Why());
|
||||
Check.True(On(Crossbow, MissileSlot), "the crossbow in hand");
|
||||
Check.True(On(InfQuarrels, AmmoSlot), "the infinite quarrels on (over the Deadly finite ones):" + sim.Why());
|
||||
Check.False(On(InfArrows, AmmoSlot), "the infinite arrows off");
|
||||
Check.True(FakeHost.Moves.Count >= 1 && FakeHost.Moves[0].Id == InfArrows, "the arrows went into the pack first");
|
||||
int crossbowUse = FakeHost.Uses.IndexOf(Crossbow), quarrelUse = FakeHost.Uses.IndexOf(InfQuarrels);
|
||||
Check.True(crossbowUse >= 0 && quarrelUse > crossbowUse, "the crossbow, then its quarrels: " + string.Join(",", FakeHost.Uses.Select(u => FakeHost.Names[u])));
|
||||
Check.False(FakeHost.Uses.Contains(DeadlyQuarrels), "the finite quarrels were never wielded");
|
||||
Check.Eq(sim.Sv.Refusals.Count, 0, "the server refused nothing: " + string.Join("; ", sim.Sv.Refusals));
|
||||
Check.Eq(sim.DryReady, 0, "never ready to shoot with nothing to shoot");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("ammo in:") && l.Contains("Stormcaller")), "the ammo landing is logged");
|
||||
Check.False(sim.C.AmmoSwapInProgress, "crafting may run again");
|
||||
}
|
||||
|
||||
private static void UntypedInfinite()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
// Neither has an AmmoType or an ammo name: the ammunition slot is all that says what they are.
|
||||
Sim.Item(InfArrows, "Sylvan Volley", 0x100, AmmoSlot);
|
||||
Sim.Item(InfQuarrels, "Quiver of Echoes", 0x100, AmmoSlot);
|
||||
Wield(Bow, MissileSlot);
|
||||
Wield(InfArrows, AmmoSlot);
|
||||
}, new[] { Bow, Crossbow });
|
||||
sim.Wants(Crossbow);
|
||||
|
||||
var pack = sim.C.PackAmmo();
|
||||
Check.Eq(pack.Count, 2, "both are ammo (the ammunition slot), no name or AmmoType needed");
|
||||
Check.True(pack.All(a => a.Untyped && a.Infinite), "of no type, and infinite (single items)");
|
||||
|
||||
Check.True(sim.RunUntilShooting(6000), "shooting with the crossbow:" + sim.Why());
|
||||
Check.True(FakeHost.Moves.Any(m => m.Id == InfArrows), "the bow's ammo came off before the crossbow (ACE refuses a launcher with ammo of no type on)");
|
||||
Check.True(On(InfQuarrels, AmmoSlot), "the other one went on, not the one just taken off the bow:" + sim.Why());
|
||||
Check.False(FakeHost.Uses.Contains(InfArrows), "the bow's ammo was not put back on");
|
||||
Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused: " + string.Join("; ", sim.Sv.Refusals));
|
||||
Check.Eq(sim.DryReady, 0, "no dry fire");
|
||||
}
|
||||
|
||||
private static void UnlimitedUseWins()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
Sim.Item(InfQuarrels, "Quarrel", 0x100, AmmoSlot, ammoType: 2, stack: 50, maxStack: 250);
|
||||
Sim.Item(DeadlyQuarrels, "Deadly Quarrel", 0x100, AmmoSlot, ammoType: 2, stack: 80, maxStack: 250);
|
||||
Wield(Crossbow, MissileSlot);
|
||||
}, new[] { Crossbow });
|
||||
sim.Wants(Crossbow);
|
||||
|
||||
var before = sim.C.PackAmmo();
|
||||
Check.False(before.Any(a => a.Infinite), "not appraised yet: two plain stacks");
|
||||
FakeHost.Bools[(InfQuarrels, 63)] = true; // the appraisal: UnlimitedUse
|
||||
var after = sim.C.PackAmmo();
|
||||
Check.True(after.First(a => a.Id == I(InfQuarrels)).Infinite, "UnlimitedUse read: infinite");
|
||||
|
||||
Check.True(sim.RunUntilShooting(4000), "shooting:" + sim.Why());
|
||||
Check.True(On(InfQuarrels, AmmoSlot), "the UnlimitedUse quarrels went on, over the Deadly ones");
|
||||
}
|
||||
|
||||
private static void EmptyQuiverNotOurSwap()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
CustomInfinite();
|
||||
Wield(Crossbow, MissileSlot); // put in hand by the player, or a meta: no ammo on
|
||||
}, new[] { Bow, Crossbow }, mode: CombatMode.NonCombat);
|
||||
sim.Wants(Crossbow);
|
||||
|
||||
Check.True(sim.RunUntilShooting(4000), "shooting:" + sim.Why());
|
||||
Check.True(On(InfQuarrels, AmmoSlot), "combat wielded the quarrels itself");
|
||||
Check.Eq(FakeHost.Uses.Count(u => u == InfQuarrels), 1, "once");
|
||||
Check.Eq(FakeHost.CombatModeRequests.FirstOrDefault(), CombatMode.Missile, "Missile asked for only after the ammo");
|
||||
Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused: " + string.Join("; ", sim.Sv.Refusals));
|
||||
Check.Eq(sim.DryReady, 0, "no dry fire");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("none it can shoot was on")), "the log says why");
|
||||
}
|
||||
|
||||
private static void AfterTheWindow()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
CustomInfinite();
|
||||
Wield(Bow, MissileSlot);
|
||||
Wield(InfArrows, AmmoSlot);
|
||||
}, new[] { Bow, Crossbow });
|
||||
sim.Wants(Crossbow);
|
||||
// The server holds the crossbow's wield for 31 s (slow, not refusing: no resend meanwhile).
|
||||
sim.Sv.SlowUse[Crossbow] = 31_000;
|
||||
sim.C.SwapTracker.ResolveMs = 60_000;
|
||||
|
||||
Check.True(RunUntil(sim, () => FakeHost.Uses.Contains(Crossbow), 4000), "the crossbow wield goes out:" + sim.Why());
|
||||
Check.True(RunUntil(sim, () => On(Crossbow, MissileSlot), 33_000), "the crossbow lands 31 s later:" + sim.Why());
|
||||
var until = (DateTime)typeof(CombatManager).GetField("_ammoFollowUpUntil", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(sim.C)!;
|
||||
Check.True(until < sim.Now, "the 30 s swap window is over");
|
||||
Check.Eq(FakeHost.Uses.Count(u => u == InfQuarrels), 0, "no quarrels before the crossbow landed");
|
||||
Check.True(sim.RunUntilShooting(4000), "its quarrels still go on, and it shoots:" + sim.Why());
|
||||
Check.True(On(InfQuarrels, AmmoSlot), "the infinite quarrels");
|
||||
Check.Eq(sim.DryReady, 0, "no dry fire");
|
||||
}
|
||||
|
||||
private static bool RunUntil(Sim sim, Func<bool> until, double maxMs)
|
||||
{
|
||||
double end = sim.SimMs + maxMs;
|
||||
while (sim.SimMs <= end) { sim.Tick(); if (until()) return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void WrongAmmoInHand()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
CustomInfinite();
|
||||
Wield(Crossbow, MissileSlot);
|
||||
Wield(InfArrows, AmmoSlot); // a hand swap on a server that let it be
|
||||
}, new[] { Bow, Crossbow }, mode: CombatMode.NonCombat);
|
||||
sim.Wants(Crossbow);
|
||||
|
||||
var has = typeof(CombatManager).GetMethod("HasWieldedAmmo", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
Check.False((bool)has.Invoke(sim.C, null)!, "arrows with a crossbow in hand are not ammo to shoot (a dry fire before)");
|
||||
|
||||
Check.True(sim.RunUntilShooting(5000), "shooting:" + sim.Why());
|
||||
Check.True(FakeHost.Moves.Any(m => m.Id == InfArrows), "the arrows into the pack");
|
||||
Check.True(On(InfQuarrels, AmmoSlot), "then the quarrels");
|
||||
Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused: " + string.Join("; ", sim.Sv.Refusals));
|
||||
Check.Eq(sim.DryReady, 0, "no dry fire");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Missile), 1, "one Missile request, after the quarrels");
|
||||
}
|
||||
|
||||
private static void NoAmmoSaysOnce()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
Sim.Item(Arrows, "Arrow", 0x100, AmmoSlot, ammoType: 1, stack: 100, maxStack: 250);
|
||||
Wield(Crossbow, MissileSlot);
|
||||
}, new[] { Crossbow }, mode: CombatMode.NonCombat);
|
||||
sim.Wants(Crossbow);
|
||||
sim.S.EnableMissileCrafting = false;
|
||||
|
||||
sim.Run(3000);
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("No quarrels for Heavy Crossbow")), 1, "said in chat once: " + string.Join(" | ", FakeHost.Chat));
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "no wield (arrows don't fit a crossbow)");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no Missile request");
|
||||
Check.Eq(sim.DryReady, 0, "never ready to shoot");
|
||||
Check.Eq(sim.C.LastCombatSkipReason, "no-ammo", "the hold is the no-ammo one (not a stall)");
|
||||
|
||||
// Quarrels turn up (looted, bought, given): they go on.
|
||||
Sim.Item(InfQuarrels, "Stormcaller's Sheaf", 0x100, AmmoSlot, ammoType: 2);
|
||||
var cache = (WorldObjectCache)typeof(CombatManager).GetField("_worldFilter", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(sim.C)!;
|
||||
_ = cache[I(InfQuarrels)];
|
||||
ForceRescan(cache);
|
||||
Check.True(sim.RunUntilShooting(4000), "the new quarrels go on and it shoots:" + sim.Why());
|
||||
Check.True(On(InfQuarrels, AmmoSlot), "on");
|
||||
|
||||
// Gone again: said again, once.
|
||||
Unwield(InfQuarrels);
|
||||
FakeHost.Names.Remove(InfQuarrels);
|
||||
FakeHost.Ints.Remove((InfQuarrels, 9));
|
||||
FakeHost.Ints.Remove((InfQuarrels, 50));
|
||||
ForceRescan(cache);
|
||||
sim.Run(2000);
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("No quarrels for Heavy Crossbow")), 2, "said again after it ran out, once");
|
||||
}
|
||||
|
||||
private static void ForceRescan(WorldObjectCache cache) =>
|
||||
typeof(WorldObjectCache).GetField("_lastDirectInventoryScan", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(cache, DateTime.MinValue);
|
||||
|
||||
private static void ThrownWeapon()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
Sim.Item(Arrows, "Arrow", 0x100, AmmoSlot, ammoType: 1, stack: 100, maxStack: 250);
|
||||
Sim.Item(Axe, "Throwing Axe", 0x100, MissileSlot, stack: 30, maxStack: 50);
|
||||
Wield(Bow, MissileSlot);
|
||||
Wield(Arrows, AmmoSlot);
|
||||
}, new[] { Bow, Axe });
|
||||
sim.Wants(Axe);
|
||||
|
||||
Check.True(sim.RunUntilShooting(5000), "throwing with the axe:" + sim.Why());
|
||||
Check.True(On(Axe, MissileSlot), "the axe in hand");
|
||||
Check.False(On(Arrows, AmmoSlot), "the arrows are not left on");
|
||||
Check.True(FakeHost.Moves.Any(m => m.Id == Arrows), "the arrows went into the pack");
|
||||
Check.True(FakeHost.Uses.IndexOf(Axe) >= 0, "the axe was wielded");
|
||||
Check.False(FakeHost.Uses.Contains(Arrows), "no ammo wielded for the thrown weapon");
|
||||
Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused: " + string.Join("; ", sim.Sv.Refusals));
|
||||
Check.Eq(sim.DryReady, 0, "no dry fire");
|
||||
|
||||
// Back to the bow: the arrows go on after it.
|
||||
sim.Wants(Bow);
|
||||
Check.True(RunUntil(sim, () => On(Bow, MissileSlot) && On(Arrows, AmmoSlot), 5000), "the bow and its arrows:" + sim.Why());
|
||||
Check.True(sim.RunUntilShooting(3000), "shooting with the bow again:" + sim.Why());
|
||||
Check.True(FakeHost.Uses.LastIndexOf(Arrows) > FakeHost.Uses.LastIndexOf(Bow), "the bow, then the arrows");
|
||||
Check.Eq(sim.DryReady, 0, "no dry fire");
|
||||
}
|
||||
|
||||
private static void FastSwapFromWand()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
CustomInfinite();
|
||||
Wield(Wand, HeldSlot); // healing: the wand in hand, the bow's arrows still on
|
||||
Wield(InfArrows, AmmoSlot);
|
||||
}, new[] { Bow, Crossbow }, mode: CombatMode.Magic);
|
||||
sim.Wants(Crossbow);
|
||||
|
||||
Check.True(sim.RunUntilShooting(6000), "shooting with the crossbow:" + sim.Why());
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("weapons for the fight")), "Fast Weapon Swap's hands swap ran:" + sim.Why());
|
||||
Check.True(FakeHost.Moves.Any(m => m.Id == InfArrows), "the arrows into the pack");
|
||||
Check.True(FakeHost.Moves.Any(m => m.Id == Wand), "the wand into the pack");
|
||||
Check.True(FakeHost.Wields.Any(w => w.Id == Crossbow && w.Mask == (uint)MissileSlot), "the crossbow wielded into the missile slot:" + sim.Why());
|
||||
Check.True(On(InfQuarrels, AmmoSlot), "then its infinite quarrels");
|
||||
Check.Eq(sim.Sv.Refusals.Count, 0, "nothing refused (no crossbow with the arrows on): " + string.Join("; ", sim.Sv.Refusals));
|
||||
Check.Eq(sim.DryReady, 0, "no dry fire");
|
||||
Check.Eq(sim.Gate.HeldBy, "", "the swap gate is free");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A bow -> crossbow swap was cut short by a heal (the arrows already in the pack, the wand on), and
|
||||
/// weapons back after heals put the last fight's bow back: that swap moves hands only, never ammo,
|
||||
/// and no launcher swap of combat's armed an ammo step, so the bow stood with an empty quiver.
|
||||
/// </summary>
|
||||
private static void WeaponsBackAfterHeals()
|
||||
{
|
||||
foreach (bool fast in new[] { true, false })
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
Sim.Item(Arrows, "Arrow", 0x100, AmmoSlot, ammoType: 1, stack: 100, maxStack: 250);
|
||||
Wield(Wand, HeldSlot);
|
||||
}, new[] { Bow, Crossbow, Wand }, mode: CombatMode.Magic, fastSwap: fast);
|
||||
const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
sim.S.RearmAfterVitals = true;
|
||||
typeof(CombatManager).GetField("_fightMainId", F)!.SetValue(sim.C, I(Bow));
|
||||
DateTime heal = sim.Now.AddSeconds(-2);
|
||||
sim.C.LastVitalCastAt = () => heal;
|
||||
typeof(CombatManager).GetField("_activeTargetId", F)!.SetValue(sim.C, 0);
|
||||
var step = typeof(CombatManager).GetMethod("RearmAfterVitalsStep", F)!;
|
||||
var tick = typeof(CombatManager).GetMethod("TickRearmSwap", F)!;
|
||||
for (int i = 0; i < 200 && !On(Bow, MissileSlot); i++)
|
||||
{
|
||||
sim.Sv.Answer(sim.SimMs);
|
||||
tick.Invoke(sim.C, null);
|
||||
step.Invoke(sim.C, null);
|
||||
sim.Sv.Observe(sim.SimMs);
|
||||
sim.SimMs += 25;
|
||||
}
|
||||
string label = fast ? "Fast Weapon Swap on" : "Fast Weapon Swap off";
|
||||
Check.True(On(Bow, MissileSlot), $"{label}: weapons back put the bow in hand:" + sim.Why());
|
||||
Check.False(On(Arrows, AmmoSlot), $"{label}: its arrows are still in the pack (weapons back moves hands only)");
|
||||
|
||||
// A monster: combat's equip finds the bow with nothing to shoot, and puts the arrows on.
|
||||
typeof(CombatManager).GetField("_activeTargetId", F)!.SetValue(sim.C, I(Monster));
|
||||
sim.Wants(Bow);
|
||||
Check.True(sim.RunUntilShooting(4000), $"{label}: shooting with the bow:" + sim.Why());
|
||||
Check.True(On(Arrows, AmmoSlot), $"{label}: the arrows went on");
|
||||
Check.Eq(sim.DryReady, 0, $"{label}: no dry fire");
|
||||
}
|
||||
}
|
||||
|
||||
private static void LauncherNotItsOwnAmmo()
|
||||
{
|
||||
using var sim = new Sim(() =>
|
||||
{
|
||||
Sim.Item(Crossbow, "Thunderbolt Arbalest", 0x100, MissileSlot, ammoType: 2);
|
||||
Wield(Crossbow, MissileSlot);
|
||||
}, new[] { Crossbow });
|
||||
var has = typeof(CombatManager).GetMethod("HasWieldedAmmo", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
Check.False((bool)has.Invoke(sim.C, null)!, "an empty quiver, whatever the launcher's name says");
|
||||
sim.Wants(Crossbow);
|
||||
sim.Run(1500);
|
||||
Check.Eq(sim.DryReady, 0, "no shot");
|
||||
}
|
||||
|
||||
// ── Ammo crafting ─────────────────────────────────────────────────────────
|
||||
|
||||
private static MissileCraftingManager CraftRig(bool sheafOn, out WorldObjectCache cache)
|
||||
{
|
||||
ActionPacer.Enabled = false;
|
||||
ActionPacer.Reset();
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.SalvageCalls = true; // GetObjectWielderInfo (answers from Wielded)
|
||||
FakeHost.Names[Player] = "Archer";
|
||||
Sim.Item(Crossbow, "Siege Arbalest", 0x100, MissileSlot, ammoType: 2); // no "crossbow" in the name
|
||||
Sim.Item(InfQuarrels, "Stormcaller's Sheaf", 0x100, AmmoSlot, ammoType: 2);
|
||||
Sim.Item(Arrows, "Arrow", 0x100, AmmoSlot, ammoType: 1, stack: 100, maxStack: 250);
|
||||
FakeHost.Wielded[Crossbow] = MissileSlot;
|
||||
FakeHost.Containers[Arrows] = Player;
|
||||
if (sheafOn) FakeHost.Wielded[InfQuarrels] = AmmoSlot;
|
||||
else FakeHost.Containers[InfQuarrels] = Player;
|
||||
var host = FakeHost.Create(Player);
|
||||
cache = FakeHost.MakeCache(host, Player, new[] { Crossbow, InfQuarrels, Arrows });
|
||||
var cm = new MissileCraftingManager(host, new LegacyUiSettings { EnableMissileCrafting = true });
|
||||
cm.SetObjectCache(cache);
|
||||
return cm;
|
||||
}
|
||||
|
||||
private static void CraftStep(MissileCraftingManager cm, WorldObjectCache cache)
|
||||
{
|
||||
const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
if (cm.State == MissileCraftingManager.CraftState.Idle) typeof(MissileCraftingManager).GetField("_lastAmmoCheck", F)!.SetValue(cm, DateTime.MinValue);
|
||||
else typeof(MissileCraftingManager).GetField("_phaseStart", F)!.SetValue(cm, DateTime.Now.AddSeconds(-1));
|
||||
ForceRescan(cache);
|
||||
EquippedState.Invalidate();
|
||||
cm.ProcessCrafting();
|
||||
}
|
||||
|
||||
private static void CraftingKnowsTypes()
|
||||
{
|
||||
var cm = CraftRig(sheafOn: true, out var cache);
|
||||
for (int i = 0; i < 3; i++) CraftStep(cm, cache);
|
||||
Check.Eq(cm.State, MissileCraftingManager.CraftState.Idle, "quarrels on: nothing to do");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "no arrows wielded at the arbalest (read as a bow by its name before)");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no")), "no evaluation every 5 s");
|
||||
}
|
||||
|
||||
private static void CraftingWieldsOddNamed()
|
||||
{
|
||||
var cm = CraftRig(sheafOn: false, out var cache);
|
||||
for (int i = 0; i < 3 && !FakeHost.Uses.Any(); i++) CraftStep(cm, cache);
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("MissileCraft: no Quarrel") && l.Contains("'Siege Arbalest'")), "the arbalest is a crossbow (its AmmoType): " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("MissileCraft"))));
|
||||
Check.Eq(FakeHost.Uses.LastOrDefault(), InfQuarrels, "the odd-named quarrels are wielded, not the arrows");
|
||||
Check.True(cm.LastAmmoEquipAt != DateTime.MinValue, "the wield time is kept (combat waits a moment after it)");
|
||||
}
|
||||
}
|
||||
|
|
@ -48,6 +48,239 @@ internal static class MonsterStatsTests
|
|||
r.Add("monster stats: /ra mstats prints a monster's numbers, lists, resets, and says why not with the usage", Command);
|
||||
r.Add("monster stats: the Monster Stats window is in RynthAi's manifest and passes the engine's parser", ManifestWindow);
|
||||
r.Add("monster stats: the window's view is published at login and while the window is on screen", WindowView);
|
||||
r.Add("kill XP (11-08): a rise after the kill, a rise before it, a quest's rise ignored, two kills two rises", XpMatcher);
|
||||
r.Add("kill XP (11-08): the session rows count XP and XP kills; the save keeps them and reads an older save", XpInRowsAndSave);
|
||||
r.Add("kill XP (11-08): the learned table averages the last kills and round-trips through its file", XpTableRoundTrip);
|
||||
r.Add("kill XP (11-08): through the plugin - kill notice + TotalExperience rise -> the row's xp/xk, /ra mstats, the learned table", XpPluginWiring);
|
||||
r.Add("death time (11-08): a kill's corpse is timed; another monster's, a late one, or another object isn't", CorpseTimerPairs);
|
||||
r.Add("death time (11-08): rows carry it (cd, cn, 'corpse after 2.1 s'); the save keeps it and reads older saves; the table keeps it", CorpseTimeInRowsAndTable);
|
||||
}
|
||||
|
||||
// ── Death animation (2026-11-08) ─────────────────────────────────────
|
||||
|
||||
private static void CorpseTimerPairs()
|
||||
{
|
||||
Check.Eq(CorpseTimer.KilledName("Corpse of Drudge Skulker"), "Drudge Skulker", "the name in a corpse's");
|
||||
Check.Null(CorpseTimer.KilledName("Drudge Skulker"), "not a corpse");
|
||||
Check.Null(CorpseTimer.KilledName("Corpse of "), "no name");
|
||||
var t = new CorpseTimer();
|
||||
t.OnKill("Drudge Skulker", 1000);
|
||||
Check.Null(t.OnCorpse("Corpse of Mosswart Worshipper", 2000), "another monster's corpse");
|
||||
Check.Null(t.OnCorpse("Black Opal", 2000), "not a corpse");
|
||||
Check.True(t.OnCorpse("Corpse of drudge skulker", 3100) is ("Drudge Skulker", 2100), "the kill's corpse 2.1 s later (any case)");
|
||||
Check.Eq(t.Waiting, 0, "and the kill is done");
|
||||
t.OnKill("Drudge Skulker", 10_000);
|
||||
t.OnKill("Drudge Skulker", 10_200); // a ring: two of them
|
||||
Check.True(t.OnCorpse("Corpse of Drudge Skulker", 12_000) is (_, 2000), "the first corpse to the first kill");
|
||||
Check.True(t.OnCorpse("Corpse of Drudge Skulker", 12_300) is (_, 2100), "the second to the second");
|
||||
t.OnKill("Drudge Skulker", 20_000);
|
||||
Check.Null(t.OnCorpse("Corpse of Drudge Skulker", 20_000 + t.WindowMs + 1), "past the window: not its death");
|
||||
Check.Eq(t.Waiting, 0, "dropped");
|
||||
t.OnKill(" ", 1);
|
||||
Check.Eq(t.Waiting, 0, "no name: nothing waits");
|
||||
}
|
||||
|
||||
private static void CorpseTimeInRowsAndTable()
|
||||
{
|
||||
var s = new MonsterCombatStats();
|
||||
s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0, _ => "Drudge Skulker");
|
||||
s.OnCorpseTime("Drudge Skulker", 2000, T0);
|
||||
s.OnCorpseTime("Drudge Skulker", 2200, T0);
|
||||
MonsterStatsRow r = s.Get("Drudge Skulker")!;
|
||||
Check.Eq((r.CorpseMs, r.CorpseKills), (4200L, 2), "summed and counted");
|
||||
Check.Near(r.CorpseAvgMs ?? 0, 2100, 1e-9, "2.1 s on average");
|
||||
string json = RynthAiPlugin.MonsterStatsJson(r);
|
||||
Check.True(json.Contains("\"cd\":2100") && json.Contains("\"cn\":2"), "mstats has cd (ms) and cn: " + json);
|
||||
Check.True(MonsterStatsText.ChatLines(r)[0].Contains("corpse after 2.1 s"), "/ra mstats: " + MonsterStatsText.ChatLines(r)[0]);
|
||||
Check.True(MonsterStatsText.ListLine(r).Contains("corpse after 2.1 s"), "the list line");
|
||||
Check.True(MonsterStatsText.DetailRows(r).Any(d => d.Label == "Death" && d.Mine.Contains("corpse after 2.1 s")), "the window's detail");
|
||||
|
||||
var save = new MonsterStatsSave { ProcessId = 1, ProcessStartUtcTicks = 2, CharacterId = 3, SavedUtcTicks = T0.Ticks, SinceUtcTicks = T0.Ticks, Rows = s.Snapshot().ToList() };
|
||||
string text = MonsterStatsStore.Serialize(save);
|
||||
Check.True(MonsterStatsStore.TryParse(text, out MonsterStatsSave back) && back.Rows.Single() == r, "the save keeps it");
|
||||
string withXpOnly = string.Join("\n", text.Split('\n').Select(l => l.StartsWith("m=") ? string.Join("\t", l.Split('\t').Take(18)) : l));
|
||||
Check.True(MonsterStatsStore.TryParse(withXpOnly, out MonsterStatsSave mid) && mid.Rows.Single().CorpseKills == 0, "a save with XP but no corpse times reads");
|
||||
|
||||
string dir = TempDir("ms-deathtable");
|
||||
try
|
||||
{
|
||||
var t = new MonsterXpTable();
|
||||
t.SetCharacter(dir);
|
||||
t.RecordDeath("Drudge Skulker", 2000);
|
||||
t.RecordDeath("Drudge Skulker", 2400);
|
||||
t.Record("Drudge Skulker", 500);
|
||||
Check.Near(t.DeathMs("Drudge Skulker") ?? 0, 2200, 1e-9, "learned death");
|
||||
Check.Null(t.DeathMs("Mosswart"), "none known");
|
||||
t.SaveIfDirty();
|
||||
var next = new MonsterXpTable();
|
||||
next.SetCharacter(dir);
|
||||
Check.True(next.DeathMs("Drudge Skulker") is double dm && Math.Abs(dm - 2200) < 1 && next.DeathsTimed("Drudge Skulker") == 2
|
||||
&& next.XpPerKill("Drudge Skulker") == 500, "both kept across logins in one file");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(dir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Experience per kill (2026-11-08) ─────────────────────────────────
|
||||
|
||||
private static void XpMatcher()
|
||||
{
|
||||
var m = new KillXpMatcher();
|
||||
Check.Eq(m.OnTotal(1_000_000, T0).Count, 0, "the first value read is the starting point");
|
||||
Check.Eq(m.OnTotal(1_000_000, T0.AddSeconds(0.1)).Count, 0, "no change");
|
||||
|
||||
// A rise after the kill.
|
||||
Check.Eq(m.OnKill("Drudge Skulker", T0.AddSeconds(1)).Count, 0, "a kill waits for its rise");
|
||||
var got = m.OnTotal(1_000_500, T0.AddSeconds(1.4));
|
||||
Check.True(got.Count == 1 && got[0].Name == "Drudge Skulker" && got[0].Xp == 500, "the rise 0.4 s later is its XP");
|
||||
|
||||
// A rise before the kill notice (the server's order can be either).
|
||||
Check.Eq(m.OnTotal(1_001_300, T0.AddSeconds(5)).Count, 0, "a rise waits for a kill");
|
||||
got = m.OnKill("Mosswart Worshipper", T0.AddSeconds(5.6));
|
||||
Check.True(got.Count == 1 && got[0].Name == "Mosswart Worshipper" && got[0].Xp == 800, "the kill 0.6 s later takes it");
|
||||
|
||||
// A quest's rise: no kill near it.
|
||||
Check.Eq(m.OnTotal(1_101_300, T0.AddSeconds(10)).Count, 0, "a quest turn-in");
|
||||
Check.Eq(m.OnTotal(1_101_300, T0.AddSeconds(11.5)).Count, 0, "waited past RiseWaitSec");
|
||||
Check.Eq(m.WaitingRises, 0, "and dropped");
|
||||
Check.Eq(m.OnKill("Drudge Skulker", T0.AddSeconds(12)).Count, 0, "a later kill doesn't take the quest's XP");
|
||||
|
||||
// That kill gave nothing seen: past KillWaitSec it goes, and a later rise isn't its.
|
||||
Check.Eq(m.OnTotal(1_101_300, T0.AddSeconds(15.5)).Count, 0, "no rise in KillWaitSec");
|
||||
Check.Eq(m.WaitingKills, 0, "the kill stopped waiting");
|
||||
Check.Eq(m.OnTotal(1_102_000, T0.AddSeconds(16)).Count, 0, "a rise after that is no kill's");
|
||||
|
||||
// Two kills (a ring spell), two rises.
|
||||
m.OnKill("Drudge Skulker", T0.AddSeconds(20));
|
||||
m.OnKill("Drudge Ravener", T0.AddSeconds(20.1));
|
||||
var a = m.OnTotal(1_102_400, T0.AddSeconds(20.3));
|
||||
var b = m.OnTotal(1_103_100, T0.AddSeconds(20.5));
|
||||
Check.True(a.Count == 1 && a[0].Name == "Drudge Skulker" && a[0].Xp == 400, "the first rise to the first kill");
|
||||
Check.True(b.Count == 1 && b[0].Name == "Drudge Ravener" && b[0].Xp == 700, "the second to the second");
|
||||
|
||||
// A lower total (another character): a new starting point, no rise.
|
||||
Check.Eq(m.OnTotal(50, T0.AddSeconds(30)).Count, 0, "lower: starts over");
|
||||
m.OnKill("Drudge Skulker", T0.AddSeconds(31));
|
||||
Check.True(m.OnTotal(80, T0.AddSeconds(31.2)) is { Count: 1 } r && r[0].Xp == 30, "and counts from there");
|
||||
m.Reset();
|
||||
Check.Eq(m.OnTotal(999, T0.AddSeconds(40)).Count, 0, "after a reset the first value is the start again");
|
||||
Check.Eq(m.OnKill(" ", T0).Count + m.WaitingKills, 0, "no name: nothing waits");
|
||||
}
|
||||
|
||||
private static void XpInRowsAndSave()
|
||||
{
|
||||
var s = new MonsterCombatStats();
|
||||
s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0, _ => "Drudge Skulker");
|
||||
s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0);
|
||||
s.OnKill("You killed Drudge Skulker!", KillBlow.Physical, T0);
|
||||
int v = s.Version;
|
||||
s.OnKillXp("Drudge Skulker", 1_000_000, T0);
|
||||
s.OnKillXp("Drudge Skulker", 1_469_134, T0);
|
||||
s.OnKillXp("Drudge Skulker", 0, T0); // nothing
|
||||
Check.True(s.Version > v, "the version moves");
|
||||
MonsterStatsRow r = s.Get("Drudge Skulker")!;
|
||||
Check.Eq((r.Kills, r.Xp, r.XpKills), (3, 2_469_134L, 2), "3 kills, 2 with XP seen");
|
||||
Check.Near(r.XpPerKill ?? 0, 1_234_567, 1e-9, "XP/kill over the kills with XP seen");
|
||||
Check.Null(new MonsterStatsRow("x", 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0).XpPerKill, "none seen: no XP/kill");
|
||||
|
||||
string json = RynthAiPlugin.MonsterStatsJson(r);
|
||||
Check.True(json.Contains("\"xp\":2469134") && json.Contains("\"xk\":2"), "mstats has xp and xk: " + json);
|
||||
Check.True(MonsterStatsText.ChatLines(r)[0].Contains("XP/kill 1,234,567"), "/ra mstats: " + MonsterStatsText.ChatLines(r)[0]);
|
||||
Check.True(MonsterStatsText.ListLine(r).Contains("XP/kill 1,234,567"), "the list line: " + MonsterStatsText.ListLine(r));
|
||||
Check.Eq(MonsterStatsText.XpCell(r), "1,234,567", "the window's cell");
|
||||
Check.True(MonsterStatsText.DetailRows(r).Any(d => d.Label == "XP" && d.Mine.Contains("XP/kill 1,234,567")), "the window's detail");
|
||||
|
||||
var save = new MonsterStatsSave { ProcessId = 1, ProcessStartUtcTicks = 2, CharacterId = 3, SavedUtcTicks = T0.Ticks, SinceUtcTicks = T0.Ticks, Rows = s.Snapshot().ToList() };
|
||||
string text = MonsterStatsStore.Serialize(save);
|
||||
Check.True(MonsterStatsStore.TryParse(text, out MonsterStatsSave back) && back.Rows.Single() == r, "the save keeps XP and XP kills");
|
||||
// A save from before 11-08: 16 fields a row.
|
||||
string older = string.Join("\n", text.Split('\n').Select(l => l.StartsWith("m=") ? string.Join("\t", l.Split('\t').Take(16)) : l));
|
||||
Check.True(MonsterStatsStore.TryParse(older, out MonsterStatsSave old) && old.Rows.Single().Kills == 3 && old.Rows.Single().XpKills == 0,
|
||||
"an older save reads, with no XP");
|
||||
var loaded = new MonsterCombatStats();
|
||||
loaded.Load(back.Rows);
|
||||
Check.Eq(loaded.Get("Drudge Skulker")!.Xp, 2_469_134L, "Load keeps the XP");
|
||||
}
|
||||
|
||||
private static void XpTableRoundTrip()
|
||||
{
|
||||
string dir = TempDir("ms-xptable");
|
||||
try
|
||||
{
|
||||
var t = new MonsterXpTable();
|
||||
t.Record("Drudge Skulker", 1000); // no character yet: kept in memory
|
||||
t.SaveIfDirty();
|
||||
Check.False(Directory.Exists(dir), "no character, no file");
|
||||
t.SetCharacter(dir);
|
||||
Check.Eq(t.FilePath, Path.Combine(dir, MonsterXpTable.FileName), "next to the character's settings: " + t.FilePath);
|
||||
Check.Null(t.XpPerKill("Drudge Skulker"), "a character's table starts from its file (none yet)");
|
||||
t.Record("Drudge Skulker", 1000);
|
||||
t.Record("Drudge Skulker", 2000);
|
||||
Check.Near(t.XpPerKill("drudge skulker") ?? 0, 1500, 1e-9, "the first kills count fully (any case)");
|
||||
for (int i = 0; i < 200; i++) t.Record("Olthoi Slayer", 100);
|
||||
for (int i = 0; i < 100; i++) t.Record("Olthoi Slayer", 300);
|
||||
Check.Near(t.XpPerKill("Olthoi Slayer") ?? 0, 300, 3, "follows the last ~20 kills (a new level, a bonus weekend)");
|
||||
t.Record("Zero", 0);
|
||||
t.Record("", 50);
|
||||
Check.Eq(t.Count, 2, "no zero XP or empty name");
|
||||
t.SaveIfDirty();
|
||||
Check.True(File.Exists(t.FilePath), "saved");
|
||||
|
||||
var next = new MonsterXpTable(); // the next login
|
||||
next.SetCharacter(dir);
|
||||
Check.Near(next.XpPerKill("Drudge Skulker") ?? 0, 1500, 0.01, "loaded at login");
|
||||
Check.Eq(next.KillsCounted("Drudge Skulker"), 2, "with its count");
|
||||
Check.Eq(next.KillsCounted("Olthoi Slayer"), 300, "every kill counted");
|
||||
File.AppendAllText(next.FilePath, "X|Bad|abc|3\nY|later|1|2\nX|Neg|-5|3\n");
|
||||
var odd = new MonsterXpTable();
|
||||
odd.SetCharacter(dir);
|
||||
Check.Eq(odd.Count, 2, "bad lines and a later version's lines are skipped");
|
||||
odd.SetCharacter("");
|
||||
Check.True(odd.Count == 0 && odd.FilePath.Length == 0, "detached: empty");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(dir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static void XpPluginWiring()
|
||||
{
|
||||
string dir = TempDir("ms-xpwire"), charDir = TempDir("ms-xpchar");
|
||||
try
|
||||
{
|
||||
var rig = new Rig(dir);
|
||||
rig.Call("SetXpTableCharacter", charDir);
|
||||
FakeHost.Quads[(Player, 1)] = 5_000_000;
|
||||
rig.Call("TickMonsterStats"); // the starting point
|
||||
rig.Set("_currentCombatMode", CombatMode.Melee);
|
||||
rig.P.NoteCombatEvent(CombatEvents.AttackerNotification, AttackerBody("Drudge Skulker", 30));
|
||||
rig.Call("NoteMonsterStatsKill", "You killed Drudge Skulker!");
|
||||
FakeHost.Quads[(Player, 1)] = 5_250_000;
|
||||
rig.Call("TickMonsterStats");
|
||||
MonsterStatsRow r = rig.Stats.Get("Drudge Skulker")!;
|
||||
Check.Eq((r.Kills, r.Xp, r.XpKills), (1, 250_000L, 1), "the kill's XP on its row");
|
||||
Check.Near(rig.P.XpPerKill("Drudge Skulker") ?? 0, 250_000, 1e-9, "and in the learned table");
|
||||
|
||||
FakeHost.Quads[(Player, 1)] = 5_400_000; // a quest: no kill
|
||||
rig.Call("TickMonsterStats");
|
||||
Check.Eq(rig.Stats.Get("Drudge Skulker")!.Xp, 250_000L, "a rise with no kill isn't a monster's");
|
||||
|
||||
var lines = rig.Typed("/ra mstats Drudge Skulker");
|
||||
Check.True(lines.Count == 3 && lines[0].Text.Contains("XP/kill 250,000"), "/ra mstats says it: " + Show(lines));
|
||||
rig.Call("ShutdownMonsterStats");
|
||||
Check.True(File.Exists(Path.Combine(charDir, MonsterXpTable.FileName)), "the table is saved at unload");
|
||||
rig.Call("OnLogoutMonsterStats");
|
||||
Check.Eq(rig.Stats.Count, 0, "logout clears the session's rows");
|
||||
Check.Near(rig.P.XpPerKill("Drudge Skulker") ?? 0, 250_000, 1e-9, "the learned table stays");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(dir, true); } catch { }
|
||||
try { Directory.Delete(charDir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly DateTime T0 = new(2026, 10, 30, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
|
@ -734,7 +967,9 @@ internal static class MonsterStatsTests
|
|||
Check.Eq((I("sw"), I("ev"), I("sp"), I("rs"), I("ne")), (5, 1, 3, 1, 1), "your side: 3 hits + the killing blow, 1 evaded; 3 spells, 1 resisted, 1 no effect");
|
||||
Check.Eq((I("at"), I("yev"), I("ysp"), I("yrs"), I("yne")), (2, 1, 2, 1, 0), "its side");
|
||||
Check.Eq((I("k"), I("dd"), I("dt")), (1, 70, 16), "kill and damage (30 + 40 dealt, 7 + 9 taken)");
|
||||
Check.Eq(m.EnumerateObject().Count(), 13, "the thirteen fields");
|
||||
Check.Eq((I("xp"), I("xk")), (0, 0), "no XP seen yet (2026-11-08 fields)");
|
||||
Check.Eq((I("cd"), I("cn")), (0, 0), "no corpse timed yet (2026-11-08 fields)");
|
||||
Check.Eq(m.EnumerateObject().Count(), 17, "the seventeen fields");
|
||||
}
|
||||
Check.False(rows["Mosswart Worshipper"].TryGetProperty("mstats", out _), "a monster without numbers has none");
|
||||
Check.True(rows["Drudge Skulker"].TryGetProperty("key", out _) && rows["Drudge Skulker"].TryGetProperty("kills", out _), "the row's own fields are all still there");
|
||||
|
|
|
|||
228
Tools/RynthCore.RynthAiHostTests/Tests/NativeAttackTests.cs
Normal file
228
Tools/RynthCore.RynthAiHostTests/Tests/NativeAttackTests.cs
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The native attack wedge (2026-11-06, DreamWeave, a melee character dual-wielding two Hand
|
||||
// Wraps): a buff-wand swap came 0.5 s after a native attack, and from then on every native
|
||||
// attack was queued by the client behind its attack-in-progress flag, which no AttackDone would
|
||||
// ever clear (the client "attacked" in Peace, sending nothing). 37 minutes of no swings;
|
||||
// turning Use Native Attack off fought at once. Now:
|
||||
// * a stance change mid-fight: the first swing back is the regular attack (its AttackDone
|
||||
// resets the client), native from the next one;
|
||||
// * native attacks with no hit, miss or kill for 10 s: the regular attack for that fight,
|
||||
// native again from the next target, logged once each way; the setting is never changed;
|
||||
// * Use Native Attack off: nothing of this.
|
||||
internal static class NativeAttackTests
|
||||
{
|
||||
private const uint Player = 0x50000180;
|
||||
private const uint Lb = 0x11BA0000;
|
||||
private const uint Mob = 0x802307B1, Mob2 = 0x802307B2;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("native attack: a buff-wand swap mid-fight and back: the first swing back is the regular attack, then native again", SwapMidFightResets);
|
||||
r.Add("native attack: a stance change long after the last swing (between fights): native straight away", SwapBetweenFightsStaysNative);
|
||||
r.Add("native attack: 10 s of native attacks with no hit, miss or kill: the regular attack for this fight, native again next fight", StallFallsBackThenNativeNextFight);
|
||||
r.Add("native attack: hits keep it native (the quiet clock starts over on every hit, miss or kill)", EvidenceKeepsNative);
|
||||
r.Add("native attack off: regular attacks only, a swap changes nothing, nothing logged", NonNativeUnchanged);
|
||||
}
|
||||
|
||||
// ── A melee rig with native attack, ticked the way OnTick ticks it ────────
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly CombatManager C;
|
||||
|
||||
public Rig(bool native = true)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.AttackSendCalls = true;
|
||||
FakeHost.NativeAttackCalls = true;
|
||||
FakeHost.CancelAttackCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Melee;
|
||||
Place(Player, "Me", 96, 96, creature: false);
|
||||
Place(Mob, "Drumtaken Kithless Siraluun", 96, 98.2f);
|
||||
Place(Mob2, "Drumtaken Rabid Carenzi", 96, 99.8f);
|
||||
FakeHost.PlayerPose = (Lb | 0x36, 96f, 96f, 0f);
|
||||
FakeHost.HeadingDeg = 0;
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
MonsterRange = 50, IsMacroRunning = true, EnableCombat = true,
|
||||
UseNativeAttack = native,
|
||||
MonsterRules = new List<MonsterRule> { new() { Name = "Default" } },
|
||||
};
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Mob2 });
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
C.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
|
||||
C.ScanNearbyTargets();
|
||||
}
|
||||
|
||||
/// <summary>A combat tick (Combat has the arbiter's tick). The attack cadence runs on the
|
||||
/// real clock, so it is reset.</summary>
|
||||
public void Tick()
|
||||
{
|
||||
S.BotAction = "Combat";
|
||||
LastAttackCmd.SetValue(C, DateTime.MinValue);
|
||||
C.OnHeartbeat();
|
||||
}
|
||||
|
||||
/// <summary>A tick while buffing has it (the wand swap): combat only watches.</summary>
|
||||
public void BuffTick(int mode)
|
||||
{
|
||||
FakeHost.CombatModeValue = mode;
|
||||
S.BotAction = "Buffing";
|
||||
C.OnHeartbeat();
|
||||
}
|
||||
|
||||
/// <summary>The wand swap BuffManager makes: Peace, Magic (casts), Peace, back to Melee.</summary>
|
||||
public void WandSwapAndBack()
|
||||
{
|
||||
BuffTick(CombatMode.NonCombat);
|
||||
BuffTick(CombatMode.Magic);
|
||||
BuffTick(CombatMode.Magic);
|
||||
BuffTick(CombatMode.NonCombat);
|
||||
FakeHost.CombatModeValue = CombatMode.Melee;
|
||||
}
|
||||
|
||||
/// <summary>Ticks until an attack reaches the server; its kind ("native" / "melee"), or null.</summary>
|
||||
public string? NextAttack()
|
||||
{
|
||||
int before = FakeHost.AttackCalls.Count;
|
||||
for (int i = 0; i < 40 && FakeHost.AttackCalls.Count == before; i++) Tick();
|
||||
return FakeHost.AttackCalls.Count > before ? FakeHost.AttackCalls[^1].Kind : null;
|
||||
}
|
||||
|
||||
/// <summary>Moves one of the combat manager's private clocks back by <paramref name="ms"/>.</summary>
|
||||
public void Age(string field, double ms)
|
||||
{
|
||||
FieldInfo f = typeof(CombatManager).GetField(field, Any)!;
|
||||
var t = (DateTime)f.GetValue(C)!;
|
||||
f.SetValue(C, t.AddMilliseconds(-ms));
|
||||
}
|
||||
|
||||
private static readonly FieldInfo LastAttackCmd = typeof(CombatManager).GetField("lastAttackCmd", Any)!;
|
||||
}
|
||||
|
||||
private static void Place(uint id, string name, float x, float y, bool creature = true)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x36, x, y, 0f);
|
||||
if (creature) FakeHost.ItemTypes[id] = 0x10;
|
||||
}
|
||||
|
||||
private static int Logged(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
|
||||
|
||||
// ── 1. The swap mid-fight ─────────────────────────────────────────────────
|
||||
|
||||
private static void SwapMidFightResets()
|
||||
{
|
||||
var rig = new Rig();
|
||||
Check.Eq(rig.NextAttack(), "native", "the fight starts native");
|
||||
Check.Eq(FakeHost.AttackCalls[^1].Target, Mob, "at the locked mob (selected for the client's pipeline)");
|
||||
Check.Eq(rig.NextAttack(), "native", "and stays native");
|
||||
|
||||
rig.WandSwapAndBack(); // 0.5 s after a native attack, as at 01:28:51
|
||||
Check.True(rig.C.NativeResetPending, "the stance left Melee right after a native attack: a reset is due");
|
||||
|
||||
Check.Eq(rig.NextAttack(), "melee", "the first swing back is the regular attack");
|
||||
Check.Eq(FakeHost.AttackCalls[^1].Target, Mob, "at the same mob");
|
||||
Check.Eq(Logged("goes out as the regular attack"), 1, "logged once");
|
||||
Check.False(rig.C.NativeResetPending, "one swing only");
|
||||
Check.Eq(rig.NextAttack(), "native", "then native again");
|
||||
Check.Eq(rig.NextAttack(), "native", "and stays native");
|
||||
Check.True(rig.S.UseNativeAttack, "the setting is untouched");
|
||||
Check.False(rig.C.NativeFallbackActive, "no fallback");
|
||||
}
|
||||
|
||||
// ── 2. A stance change between fights ─────────────────────────────────────
|
||||
|
||||
private static void SwapBetweenFightsStaysNative()
|
||||
{
|
||||
var rig = new Rig();
|
||||
Check.Eq(rig.NextAttack(), "native", "native");
|
||||
rig.Age("_lastNativeAttackAt", CombatManager.NativeResetWindowMs + 1000); // the last swing 6 s ago
|
||||
rig.WandSwapAndBack();
|
||||
Check.False(rig.C.NativeResetPending, "no attack was in flight when the stance left: no reset");
|
||||
Check.Eq(rig.NextAttack(), "native", "native straight away");
|
||||
Check.Eq(Logged("[Combat] native attack"), 0, "nothing logged");
|
||||
}
|
||||
|
||||
// ── 3. The safety net ─────────────────────────────────────────────────────
|
||||
|
||||
private static void StallFallsBackThenNativeNextFight()
|
||||
{
|
||||
var rig = new Rig();
|
||||
for (int i = 0; i < CombatManager.NativeFallbackAttacks; i++)
|
||||
Check.Eq(rig.NextAttack(), "native", $"native attack {i + 1}, no hit, miss or kill");
|
||||
Check.Eq((uint)rig.C.activeTargetId, Mob, "rig: the first mob is the target");
|
||||
|
||||
rig.Age("_nativeQuietSince", CombatManager.NativeFallbackMs + 500); // 10.5 s of them
|
||||
rig.Age("_lastNativeAttackAt", 900); // the last one a cycle ago (no gap)
|
||||
Check.Eq(rig.NextAttack(), "melee", "10 s with nothing: the regular attack");
|
||||
Check.True(rig.C.NativeFallbackActive, "for this fight");
|
||||
Check.Eq(Logged("native attack isn't landing"), 1, "logged");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("using the regular attack until the next fight")), "with what happens");
|
||||
Check.Eq(rig.NextAttack(), "melee", "the next swing at the same mob: regular");
|
||||
Check.Eq(rig.NextAttack(), "melee", "and the next");
|
||||
Check.Eq(Logged("native attack isn't landing"), 1, "logged once, not per swing");
|
||||
Check.True(rig.S.UseNativeAttack, "the setting is untouched");
|
||||
|
||||
// The fight ends (the mob gone), the next one starts: native again.
|
||||
rig.C.MarkGhost(unchecked((int)Mob), "Drumtaken Kithless Siraluun", 900_000, "test: the fight is over");
|
||||
Thread.Sleep(80); // the scan runs at most every 50 ms
|
||||
rig.C.ScanNearbyTargets();
|
||||
Check.Eq(rig.NextAttack(), "native", "the next fight: native again");
|
||||
Check.Eq((uint)rig.C.activeTargetId, Mob2, "at the next mob");
|
||||
Check.False(rig.C.NativeFallbackActive, "the fallback is over");
|
||||
Check.Eq(Logged("native attack again: a new fight"), 1, "logged");
|
||||
Check.Eq(rig.NextAttack(), "native", "and stays native (the quiet clock started over)");
|
||||
}
|
||||
|
||||
private static void EvidenceKeepsNative()
|
||||
{
|
||||
var rig = new Rig();
|
||||
for (int i = 0; i < CombatManager.NativeFallbackAttacks + 2; i++)
|
||||
Check.Eq(rig.NextAttack(), "native", $"native attack {i + 1}");
|
||||
rig.Age("_nativeQuietSince", CombatManager.NativeFallbackMs + 500);
|
||||
rig.C.OnCombatDamage(120, 1, false, isAttacker: true); // a hit lands
|
||||
Check.Eq(rig.NextAttack(), "native", "a hit since: still native");
|
||||
Check.False(rig.C.NativeFallbackActive, "no fallback");
|
||||
|
||||
// A long pause between native attacks (a loot run) starts the clock over too.
|
||||
for (int i = 0; i < CombatManager.NativeFallbackAttacks; i++) rig.NextAttack();
|
||||
rig.Age("_nativeQuietSince", CombatManager.NativeFallbackMs + 500);
|
||||
rig.Age("_lastNativeAttackAt", CombatManager.NativeQuietGapMs + 500);
|
||||
Check.Eq(rig.NextAttack(), "native", "the last native attack 5.5 s ago: a new quiet clock, native");
|
||||
Check.Eq(Logged("native attack isn't landing"), 0, "never fell back");
|
||||
}
|
||||
|
||||
// ── 4. Native attack off ──────────────────────────────────────────────────
|
||||
|
||||
private static void NonNativeUnchanged()
|
||||
{
|
||||
var rig = new Rig(native: false);
|
||||
Check.Eq(rig.NextAttack(), "melee", "regular");
|
||||
rig.WandSwapAndBack();
|
||||
Check.False(rig.C.NativeResetPending, "no reset pending");
|
||||
for (int i = 0; i < 6; i++)
|
||||
Check.Eq(rig.NextAttack(), "melee", $"regular attack {i + 1}");
|
||||
Check.False(rig.C.NativeFallbackActive, "no fallback");
|
||||
Check.Eq(Logged("[Combat] native attack"), 0, "nothing logged");
|
||||
Check.False(FakeHost.AttackCalls.Any(a => a.Kind == "native"), "never a native attack");
|
||||
}
|
||||
}
|
||||
34
Tools/RynthCore.RynthAiHostTests/Tests/NavHeadingTests.cs
Normal file
34
Tools/RynthCore.RynthAiHostTests/Tests/NavHeadingTests.cs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// /ra navheading walks round what's in the way (owner, 2026-11-06: "nav route is not navving around
|
||||
// obstacles"): RynthNav's corners become a Once route, in nav coordinates, doorways kept.
|
||||
internal static class NavHeadingTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("navheading: RynthNav's corners become a Once route in nav coordinates, doorways kept", CornersToRoute);
|
||||
}
|
||||
|
||||
private static double World(double navUnits) => (navUnits * 10.0 + 1019.5) * 24.0;
|
||||
|
||||
private static void CornersToRoute()
|
||||
{
|
||||
var corners = new[]
|
||||
{
|
||||
new OutdoorHunt.Vec(World(56.0), World(42.4), 240.0),
|
||||
new OutdoorHunt.Vec(World(56.1), World(42.5), 480.0, Door: true),
|
||||
};
|
||||
var route = RynthAiPlugin.HeadingRoute(corners);
|
||||
Check.True(route.RouteType == NavRouteType.Once, "a Once route");
|
||||
Check.True(route.Points.Count == 2, "one point per corner");
|
||||
Check.True(Math.Abs(route.Points[0].EW - 56.0) < 1e-9 && Math.Abs(route.Points[0].NS - 42.4) < 1e-9, "x is EW, y is NS");
|
||||
Check.True(Math.Abs(route.Points[1].Z - 2.0) < 1e-9, "z in 240-yard units");
|
||||
Check.True(!route.Points[0].Doorway && route.Points[1].Doorway, "doorway corners stay doorways");
|
||||
Check.True(route.Points[0].Type == NavPointType.Point, "plain points");
|
||||
}
|
||||
}
|
||||
|
|
@ -28,6 +28,219 @@ internal static class OutdoorHuntTests
|
|||
r.Add("hunt: a monster right beside it that combat doesn't take: stands, then leaves it out", RightHere);
|
||||
r.Add("hunt (test 10-23): in a building it walks back out the way it went in (the loops it made cut out)", WayBackOut);
|
||||
r.Add("hunt: in a building with no way in known, or the walks out ending still inside: it waits", IndoorsWaits);
|
||||
r.Add("hunt pick (11-08): Nearest is the hunt as it was (the lone one 10 yd off, not the pack)", PickNearestUnchanged);
|
||||
r.Add("hunt pick (11-08): Biggest pack goes to a 5-pack 80 yd off over a lone monster 10 yd off; logged", PickPackFar);
|
||||
r.Add("hunt pick (11-08): a lone monster wins when the pack is very far", PickPackTooFar);
|
||||
r.Add("hunt pick (11-08): Most XP prefers 2 high-XP monsters over 4 low-XP ones (Biggest pack the other way)", PickMostXp);
|
||||
r.Add("hunt pick (11-08): Most XP with no XP learned falls back to the pack's size; an unknown name counts as the known average", PickXpUnknown);
|
||||
r.Add("hunt pick (11-08): a higher Priority still comes first; paths only for the top few; the target is kept while walking", PickPriorityAndCost);
|
||||
r.Add("hunt pick (11-08): /ra hunt pick answers with the choice, sets it, and says why not with the usage", PickCommand);
|
||||
r.Add("hunt pick (11-08): OutdoorHuntPick round-trips (saved, copied, engine payload, clamped, an older engine leaves it)", PickSetting);
|
||||
}
|
||||
|
||||
// ── Pick (2026-11-08, Tom: "a setting to go for nearest spawn or most dense or highest experience") ──
|
||||
|
||||
/// <summary>A pack of <paramref name="n"/> round (x, y), ids from <paramref name="firstId"/>, each within a few yd of the others.</summary>
|
||||
private static List<OutdoorHunt.Candidate> Pack(int firstId, int n, double x, double y, OutdoorHunt.Vec me, string? name = null, int priority = 1)
|
||||
{
|
||||
var list = new List<OutdoorHunt.Candidate>();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
double a = i * 2 * Math.PI / Math.Max(1, n);
|
||||
double px = x + (i == 0 ? 0 : 4 * Math.Cos(a)), py = y + (i == 0 ? 0 : 4 * Math.Sin(a));
|
||||
list.Add(C(firstId + i, px, py, me, priority, name));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<OutdoorHunt.Candidate> Sorted(IEnumerable<OutdoorHunt.Candidate> c) => c.OrderBy(x => x.Distance).ToList();
|
||||
|
||||
private static void PickNearestUnchanged()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var all = Sorted(Pack(10, 5, 1080, 1000, me).Append(C(1, 1010, 1000, me)));
|
||||
var h = new OutdoorHunt();
|
||||
Check.Eq(h.Pick, OutdoorHunt.PickMode.Nearest, "Nearest by default");
|
||||
h.Start(T0, me);
|
||||
var d = h.Tick(T0, me, true, all, new Nav().Path);
|
||||
Check.Eq(d.TargetId, 1, "the lone one 10 yd away");
|
||||
Check.True(h.Note.StartsWith("next: 'Monster 1', a 10 yd walk"), "the same log line as before: " + h.Note);
|
||||
}
|
||||
|
||||
private static void PickPackFar()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var all = Sorted(Pack(10, 5, 1080, 1000, me).Append(C(1, 1010, 1000, me)));
|
||||
var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack };
|
||||
h.Start(T0, me);
|
||||
var d = h.Tick(T0, me, true, all, new Nav().Path);
|
||||
Check.True(d.Act == OutdoorHunt.Act.Walk && d.TargetId >= 10 && d.TargetId < 15, $"to the pack, not the lone one ({d.Act} {d.TargetId})");
|
||||
var nearestOfPack = all.Where(c => c.Id >= 10).OrderBy(c => c.Distance).First();
|
||||
Check.Eq(d.TargetId, nearestOfPack.Id, "the pack's member with the shortest walk");
|
||||
Check.True(h.Note.Contains("pack of 5") && h.Note.Contains("yd walk"), "logged with the pack: " + h.Note);
|
||||
}
|
||||
|
||||
private static void PickPackTooFar()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
// 3 at 180 yd: 3 / (1 + 180/60) = 0.75; one at 10 yd: 1 / (1 + 10/60) = 0.86.
|
||||
var all = Sorted(Pack(10, 3, 1180, 1000, me).Append(C(1, 1010, 1000, me)));
|
||||
var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack };
|
||||
h.Start(T0, me);
|
||||
var d = h.Tick(T0, me, true, all, new Nav().Path);
|
||||
Check.Eq(d.TargetId, 1, "the lone one near beats a small pack far away");
|
||||
Check.True(h.Note.Contains("on its own"), "logged: " + h.Note);
|
||||
// The same pack 80 yd off: 3 / 2.33 = 1.29 wins.
|
||||
var near = Sorted(Pack(10, 3, 1080, 1000, me).Append(C(1, 1010, 1000, me)));
|
||||
var h2 = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack };
|
||||
h2.Start(T0, me);
|
||||
Check.True(h2.Tick(T0, me, true, near, new Nav().Path).TargetId >= 10, "and at 80 yd the pack wins");
|
||||
}
|
||||
|
||||
private static Func<string, double?> Xp(params (string Name, double Xp)[] known)
|
||||
{
|
||||
var map = known.ToDictionary(k => k.Name, k => k.Xp);
|
||||
return n => map.TryGetValue(n, out double v) ? v : null;
|
||||
}
|
||||
|
||||
private static void PickMostXp()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var all = Sorted(Pack(10, 2, 1050, 1000, me, "Olthoi Slayer").Concat(Pack(20, 4, 1000, 1030, me, "Drudge Skulker")));
|
||||
var lookup = Xp(("Olthoi Slayer", 1000), ("Drudge Skulker", 100));
|
||||
var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Xp, XpLookup = lookup };
|
||||
h.Start(T0, me);
|
||||
var d = h.Tick(T0, me, true, all, new Nav().Path);
|
||||
Check.True(d.TargetId is 10 or 11, $"the 2 high-XP ones 50 yd off ({d.TargetId})");
|
||||
Check.True(h.Note.Contains("pack of 2") && h.Note.Contains("(2,000 XP)"), "logged with the pack's XP: " + h.Note);
|
||||
var p = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack, XpLookup = lookup };
|
||||
p.Start(T0, me);
|
||||
Check.True(p.Tick(T0, me, true, all, new Nav().Path).TargetId >= 20, "Biggest pack takes the 4 nearer ones");
|
||||
}
|
||||
|
||||
private static void PickXpUnknown()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var all = Sorted(Pack(10, 2, 1050, 1000, me, "Olthoi Slayer").Concat(Pack(20, 4, 1000, 1030, me, "Drudge Skulker")));
|
||||
var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Xp, XpLookup = _ => null };
|
||||
h.Start(T0, me);
|
||||
Check.True(h.Tick(T0, me, true, all, new Nav().Path).TargetId >= 20, "nothing learned: by size, the 4");
|
||||
Check.True(h.Note.Contains("no XP learned yet"), "and says so: " + h.Note);
|
||||
var none = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Xp }; // no lookup at all
|
||||
none.Start(T0, me);
|
||||
Check.True(none.Tick(T0, me, true, all, new Nav().Path).TargetId >= 20, "no lookup: by size too");
|
||||
// Only the Slayers known (1000): the Drudges count as that average, so 4 of them win.
|
||||
var half = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Xp, XpLookup = Xp(("Olthoi Slayer", 1000)) };
|
||||
half.Start(T0, me);
|
||||
Check.True(half.Tick(T0, me, true, all, new Nav().Path).TargetId >= 20, "an unknown name counts as the known average");
|
||||
}
|
||||
|
||||
private static void PickPriorityAndCost()
|
||||
{
|
||||
var me = V(1000, 1000);
|
||||
var all = Sorted(Pack(10, 5, 1020, 1000, me).Append(C(1, 1000, 1050, me, priority: 5)));
|
||||
var h = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack };
|
||||
h.Start(T0, me);
|
||||
var nav = new Nav();
|
||||
var d = h.Tick(T0, me, true, all, nav.Path);
|
||||
Check.Eq(d.TargetId, 1, "Priority 5 on its own before a Priority 1 pack of 5");
|
||||
|
||||
// Twenty monsters about: paths for PickCandidates only.
|
||||
var many = new List<OutdoorHunt.Candidate>();
|
||||
for (int i = 0; i < 20; i++) many.Add(C(100 + i, 1000 + 5 * i, 1100, me));
|
||||
var cost = new OutdoorHunt { Pick = OutdoorHunt.PickMode.Pack };
|
||||
cost.Start(T0, me);
|
||||
var counted = new Nav();
|
||||
d = cost.Tick(T0, me, true, Sorted(many), counted.Path);
|
||||
Check.Eq(counted.Calls, cost.PickCandidates, "a path for each of the top few only");
|
||||
int target = d.TargetId;
|
||||
Check.True(target != 0, "one chosen");
|
||||
// Walking to it: kept, even with a bigger pack turning up.
|
||||
var more = Sorted(many.Concat(Pack(200, 8, 1000, 1010, me)));
|
||||
d = cost.Tick(T0.AddSeconds(2), me, false, more, counted.Path);
|
||||
Check.True(d.Act == OutdoorHunt.Act.None && cost.TargetId == target, $"the target is kept while walking ({d.Act} {cost.TargetId})");
|
||||
}
|
||||
|
||||
private static (RynthAiPlugin P, LegacyDashboardRenderer Dash, Action<string> Ra, Func<string> All) HuntRig()
|
||||
{
|
||||
const System.Reflection.BindingFlags Any = System.Reflection.BindingFlags.Instance
|
||||
| System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public;
|
||||
RynthCore.RynthAiHostTests.Fakes.FakeHost.Reset();
|
||||
var host = RynthCore.RynthAiHostTests.Fakes.FakeHost.Create();
|
||||
var p = new RynthAiPlugin();
|
||||
typeof(RynthCore.PluginCore.RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { RynthCore.RynthAiHostTests.Fakes.FakeHost.LastApi });
|
||||
var dash = new LegacyDashboardRenderer(host);
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(p, dash);
|
||||
var chat = RynthCore.RynthAiHostTests.Fakes.FakeHost.Chat;
|
||||
void Ra(string line)
|
||||
{
|
||||
chat.Clear();
|
||||
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(p, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
|
||||
}
|
||||
return (p, dash, Ra, () => string.Join(" | ", chat));
|
||||
}
|
||||
|
||||
private static void PickCommand()
|
||||
{
|
||||
var (_, dash, Ra, All) = HuntRig();
|
||||
Ra("/ra hunt pick");
|
||||
Check.True(All().Contains("Outdoor hunt pick: Nearest") && All().Contains(RynthAiPlugin.HuntPickUsage), "no word: the choice now and the usage: " + All());
|
||||
Ra("/ra hunt pick pack");
|
||||
Check.Eq(dash.Settings.OutdoorHuntPick, 1, "pack = 1");
|
||||
Check.True(All().Contains("set: Biggest pack"), "and says so: " + All());
|
||||
Ra("/ra hunt pick xp");
|
||||
Check.Eq(dash.Settings.OutdoorHuntPick, 2, "xp = 2");
|
||||
Check.True(All().Contains("set: Most XP"), "and says so: " + All());
|
||||
Ra("/ra hunt pick most dense");
|
||||
Check.Eq(dash.Settings.OutdoorHuntPick, 1, "Tom's words work too");
|
||||
Ra("/ra hunt pick fastest");
|
||||
Check.Eq(dash.Settings.OutdoorHuntPick, 1, "an unknown word changes nothing");
|
||||
Check.True(All().Contains("isn't one of nearest, pack or xp") && All().Contains("Biggest pack now") && All().Contains("Usage: /ra hunt pick"),
|
||||
"why, what it is, the usage: " + All());
|
||||
Ra("/ra hunt pick nearest");
|
||||
Check.Eq(dash.Settings.OutdoorHuntPick, 0, "back to nearest");
|
||||
Ra("/ra hunt status");
|
||||
Check.True(All().Contains("Pick: Nearest"), "status says the pick: " + All());
|
||||
Ra("/ra hunt nonsense");
|
||||
Check.True(All().Contains(RynthAiPlugin.HuntPickUsage), "the usage lists it: " + All());
|
||||
}
|
||||
|
||||
private static void PickSetting()
|
||||
{
|
||||
Check.Eq(new LegacyUiSettings().OutdoorHuntPick, 0, "Nearest by default");
|
||||
var ctx = RynthAiJsonContext.Default.LegacyUiSettings;
|
||||
var saved = System.Text.Json.JsonSerializer.Deserialize(
|
||||
System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { OutdoorHuntPick = 2 }, ctx), ctx)!;
|
||||
Check.Eq(saved.OutdoorHuntPick, 2, "saved");
|
||||
var live = new LegacyUiSettings();
|
||||
typeof(LegacyDashboardRenderer).GetMethod("CopySettings",
|
||||
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)!
|
||||
.Invoke(null, new object[] { saved, live });
|
||||
Check.Eq(live.OutdoorHuntPick, 2, "copied");
|
||||
var old = System.Text.Json.JsonSerializer.Deserialize("{\"OutdoorHuntRange\":70}", ctx)!;
|
||||
Check.Eq(old.OutdoorHuntPick, 0, "a profile from before the setting: Nearest");
|
||||
|
||||
// The engine's face (SettingsBridgePayload): sent as "OutdoorHuntPick", applied, clamped.
|
||||
var s = new LegacyUiSettings { OutdoorHuntPick = 1 };
|
||||
var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
const System.Reflection.BindingFlags F = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", F)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", F)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", F)!.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
string json = dash.BuildSettingsJson();
|
||||
using (var doc = System.Text.Json.JsonDocument.Parse(json))
|
||||
Check.True(doc.RootElement.TryGetProperty("OutdoorHuntPick", out var pe) && pe.GetInt32() == 1, "sent to the engine as \"OutdoorHuntPick\"");
|
||||
var sent = System.Text.Json.JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.SettingsBridgePayload)!;
|
||||
Check.Eq(sent.OutdoorHuntPick, 1, "in the payload");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.Eq(s.OutdoorHuntPick, 1, "an engine without it leaves it alone");
|
||||
dash.ApplySettingsJson("{\"OutdoorHuntPick\":2}");
|
||||
Check.Eq(s.OutdoorHuntPick, 2, "applied: Most XP");
|
||||
dash.ApplySettingsJson("{\"OutdoorHuntPick\":9}");
|
||||
Check.Eq(s.OutdoorHuntPick, 2, "9 clamped to 2");
|
||||
dash.ApplySettingsJson("{\"OutdoorHuntPick\":-3}");
|
||||
Check.Eq(s.OutdoorHuntPick, 0, "-3 clamped to 0");
|
||||
}
|
||||
|
||||
private static void WallBetween()
|
||||
|
|
|
|||
333
Tools/RynthCore.RynthAiHostTests/Tests/PetSummonStopsTests.cs
Normal file
333
Tools/RynthCore.RynthAiHostTests/Tests/PetSummonStopsTests.cs
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Summons stopped for the rest of the session (report 2026-11-06, release 2026.11.3.2: "after a
|
||||
// time my character will stop summoning, he keeps fighting and looting", fixed only by restarting
|
||||
// the game). Two ways PetManager waited forever, with no log line:
|
||||
// * the client's gesture gate (CanCastNow) stuck closed: buffs and combat go on through
|
||||
// CastGateWatchdog's override, the summon read the raw gate and never went;
|
||||
// * a pet the client still shows (a ghost the server no longer has, or one whose delete the
|
||||
// cache missed) read as "a pet is out" forever.
|
||||
// Follow-up from the same player: "it thinks it's already summoned if you die", and it stopped
|
||||
// while "rescanning inventory". A pet out at a death or a portal is left behind (the server drops
|
||||
// it without telling a player who left), a read of 0 during a rescan refilled or parked a full
|
||||
// essence, and an essence that vanished from the client was used instead of its successor.
|
||||
internal static unsafe class PetSummonStopsTests
|
||||
{
|
||||
private const uint Player = 0x50000D11;
|
||||
private const uint Mob = 0x80310010;
|
||||
private const uint Essence = 0x80310001;
|
||||
private const uint Pet = 0x80310020;
|
||||
private const uint Spirit = 0x80310002;
|
||||
private const uint Essence2 = 0x80310004; // a same-named essence that replaces a vanished one
|
||||
private const uint StructureKey = 92; // AcIntProperty.Structure
|
||||
private const uint Lb = 0xA9B40000;
|
||||
|
||||
private const string PetName = "Pet Tester's Fire Moar";
|
||||
|
||||
/// <summary>GetObjectServerAge answers (ms since the server's last message), -1 = no record.</summary>
|
||||
private static readonly Dictionary<uint, int> ServerAges = new();
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("pets: a gesture gate stuck closed holds the summon only 4 s, logged; a short gesture just waits", StuckGestureGate);
|
||||
r.Add("pets: a pet the server has been silent about for 60 s is a ghost: a new pet is summoned", GhostPetIgnored);
|
||||
r.Add("pets: a pet the client no longer has (missed delete) does not hold summons", MissedDeleteIgnored);
|
||||
r.Add("pets: 'is already active' after a ghost summon trusts the quiet pet for 5 min", AlreadyActiveTrustsPet);
|
||||
r.Add("pets: a death leaves the pet out behind: the next fight summons at once (before: never again)", DeathLeavesPetBehind);
|
||||
r.Add("pets: a death mid-summon clears the summon state; the server's essence cooldown still holds", DeathMidSummon);
|
||||
r.Add("pets: a portal leaves the pet out behind; 'is already active' brings it back", PortalLeavesPetBehind);
|
||||
r.Add("pets: no server record for a pet for 60 s of watching (engine reload) is silence too", NoRecordIsSilence);
|
||||
r.Add("pets: a read of 0 right after 50 (a rescan) summons; it does not refill or park the essence", RescanZeroRead);
|
||||
r.Add("pets: empty read, no spirit, never confirmed by the server: tried once, parked only after 'not enough charges'", UnconfirmedEmptyTried);
|
||||
r.Add("pets: an essence the client no longer has is not used; its same-named successor is", VanishedEssenceReplaced);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig : IDisposable
|
||||
{
|
||||
public long Now = 1_000_000;
|
||||
public readonly LegacyUiSettings S = new() { SummonPets = true, MonsterRange = 20, CustomPetRange = 5, PetAutoRefill = true };
|
||||
public readonly PetManager Pets;
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Rig(bool gates = false, bool serverAge = false, bool pet = false, bool spirit = false, bool replacement = false, int charges = 50)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
ServerAges.Clear();
|
||||
FakeHost.WeaponCalls = true; // UseObject (summon)
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.ServerGates = gates; // GetCastBusyState (FakeHost.CastBusy)
|
||||
if (serverAge) FakeHost.ConfigureApi = ServerAgeApi;
|
||||
Place(Player, "Pet Tester", 96, 96, creature: false);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
Place(Mob, "Drudge Skulker", 96, 99, creature: true); // 3 m north
|
||||
FakeHost.Names[Essence] = "Fire Moar Essence (50)";
|
||||
FakeHost.Containers[Essence] = Player;
|
||||
FakeHost.Ints[(Essence, StructureKey)] = charges;
|
||||
var known = new List<uint> { Mob, Essence };
|
||||
if (spirit)
|
||||
{
|
||||
FakeHost.Names[Spirit] = "Encapsulated Spirit";
|
||||
FakeHost.Containers[Spirit] = Player;
|
||||
known.Add(Spirit);
|
||||
}
|
||||
if (replacement)
|
||||
{
|
||||
FakeHost.Names[Essence2] = "Fire Moar Essence (50)";
|
||||
FakeHost.Containers[Essence2] = Player;
|
||||
FakeHost.Ints[(Essence2, StructureKey)] = 50;
|
||||
known.Add(Essence2);
|
||||
}
|
||||
|
||||
var host = FakeHost.Create(Player);
|
||||
Cache = FakeHost.MakeCache(host, Player, known);
|
||||
S.IsMacroRunning = true;
|
||||
S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence), Name = "Fire Moar Essence (50)", Type = "Pet" });
|
||||
var combat = new CombatManager(host, S, Cache);
|
||||
combat.SetPlayerId(Player);
|
||||
combat.ScanNearbyTargets();
|
||||
Check.True(combat.ScannedTargets.Count == 1, "rig: the monster is scanned");
|
||||
if (pet)
|
||||
{
|
||||
Place(Pet, PetName, 96, 97, creature: true);
|
||||
_ = Cache[unchecked((int)Pet)]; // filed on the landscape as a creature
|
||||
Check.True(Cache.GetLandscape().Any(w => w.Id == unchecked((int)Pet)), "rig: the pet is in the landscape cache");
|
||||
}
|
||||
PetManager.Clock = () => Now;
|
||||
Pets = new PetManager(host, S, Cache, combat, null);
|
||||
}
|
||||
|
||||
private static void Place(uint id, string name, float x, float y, bool creature)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
|
||||
if (creature) FakeHost.ItemTypes[id] = 0x10;
|
||||
}
|
||||
|
||||
/// <summary>Runs the heartbeat for <paramref name="ms"/> of fake time in 100 ms steps.</summary>
|
||||
public void Run(long ms)
|
||||
{
|
||||
for (long t = 0; t < ms; t += 100)
|
||||
{
|
||||
Now += 100;
|
||||
Pets.OnHeartbeat(0);
|
||||
}
|
||||
}
|
||||
|
||||
public int Summons => FakeHost.Uses.Count(u => u == Essence);
|
||||
public int Refills => FakeHost.UsesOn.Count(u => u.Source == Spirit);
|
||||
|
||||
public static void SetCharges(int charges) => FakeHost.Ints[(Essence, StructureKey)] = charges;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
PetManager.Clock = static () => Environment.TickCount64;
|
||||
FakeHost.ConfigureApi = null;
|
||||
ServerAges.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
private static void ServerAgeApi(ref RynthCoreApiNative api)
|
||||
{
|
||||
api.Version = Math.Max(api.Version, 83u);
|
||||
api.GetObjectServerAgeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&GetObjectServerAge;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetObjectServerAge(uint id) => ServerAges.TryGetValue(id, out int age) ? age : -1;
|
||||
|
||||
private static bool Logged(string text) => FakeHost.Logs.Any(l => l.Contains(text, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void StuckGestureGate()
|
||||
{
|
||||
using (var rig = new Rig(gates: true))
|
||||
{
|
||||
FakeHost.CastBusy = 1; // the gate never opens again
|
||||
rig.Run(3_000);
|
||||
Check.Eq(rig.Summons, 0, "inside 4 s the closed gate holds the summon (a gesture may be animating)");
|
||||
rig.Run(3_000);
|
||||
Check.Eq(rig.Summons, 1, "closed past 4 s: taken as stuck, the summon goes (before: never again)");
|
||||
Check.True(Logged("taken as stuck"), "the stuck gate is logged");
|
||||
FakeHost.CastBusy = 0;
|
||||
rig.Run(200);
|
||||
Check.True(Logged("reads clear again"), "the gate opening again is logged");
|
||||
}
|
||||
|
||||
using (var rig = new Rig(gates: true))
|
||||
{
|
||||
FakeHost.CastBusy = 1; // a buff gesture
|
||||
rig.Run(2_000);
|
||||
Check.Eq(rig.Summons, 0, "a gesture animating: no summon");
|
||||
FakeHost.CastBusy = 0;
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "the gesture ended: the summon goes");
|
||||
Check.False(Logged("taken as stuck"), "a short gesture is not called stuck");
|
||||
}
|
||||
|
||||
using (var rig = new Rig(gates: true))
|
||||
{
|
||||
// Gestures back to back with the gate open in between, never 4 s closed in one go.
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
FakeHost.CastBusy = 1;
|
||||
rig.Run(900);
|
||||
FakeHost.CastBusy = 0;
|
||||
rig.Run(100);
|
||||
FakeHost.CastBusy = 1;
|
||||
}
|
||||
Check.False(Logged("taken as stuck"), "a gate that opens between gestures is never called stuck");
|
||||
}
|
||||
}
|
||||
|
||||
private static void GhostPetIgnored()
|
||||
{
|
||||
using (var rig = new Rig(pet: true))
|
||||
{
|
||||
rig.Run(5_000);
|
||||
Check.Eq(rig.Summons, 0, "no server-age record (older engine): the pet counts as out, as before");
|
||||
}
|
||||
|
||||
using (var rig = new Rig(serverAge: true, pet: true))
|
||||
{
|
||||
ServerAges[Pet] = 2_000;
|
||||
rig.Run(5_000);
|
||||
Check.Eq(rig.Summons, 0, "the server talked about the pet 2 s ago: it is out, no second summon");
|
||||
ServerAges[Pet] = -1;
|
||||
rig.Run(5_000);
|
||||
Check.Eq(rig.Summons, 0, "no record for the pet says nothing: it is out");
|
||||
ServerAges[Pet] = 90_000;
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "silent for 90 s: a ghost, a new pet is summoned (before: never again)");
|
||||
Check.True(Logged("does not count as out") && Logged("0x80310020"), "the ghost is logged with its id");
|
||||
int lines = FakeHost.Logs.Count(l => l.Contains("does not count as out"));
|
||||
rig.Run(10_000);
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("does not count as out")), lines, "the ghost is logged once");
|
||||
}
|
||||
}
|
||||
|
||||
private static void MissedDeleteIgnored()
|
||||
{
|
||||
using var rig = new Rig(pet: true);
|
||||
rig.Run(3_000);
|
||||
Check.Eq(rig.Summons, 0, "the pet is out: no summon");
|
||||
FakeHost.Names.Remove(Pet); // the client deleted it; the cache never heard
|
||||
FakeHost.Positions.Remove(Pet);
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "a pet the client no longer has does not hold summons");
|
||||
Check.True(Logged("client no longer has it"), "the missed delete is logged");
|
||||
}
|
||||
|
||||
private static void AlreadyActiveTrustsPet()
|
||||
{
|
||||
using var rig = new Rig(serverAge: true, pet: true);
|
||||
ServerAges[Pet] = 90_000; // quiet, so taken as a ghost
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "the quiet pet is taken as a ghost: one summon");
|
||||
rig.Pets.OnChatWindowText("Pet Tester's Fire Moar is already active.");
|
||||
Check.True(Logged("already active"), "the server's answer is logged");
|
||||
rig.Run(4 * 60_000);
|
||||
Check.Eq(rig.Summons, 1, "the server has the pet: no Use every 45 s on top of it for 5 min");
|
||||
rig.Run(90_000);
|
||||
Check.Eq(rig.Summons, 2, "after 5 min the quiet pet is checked again");
|
||||
}
|
||||
|
||||
private static void DeathLeavesPetBehind()
|
||||
{
|
||||
using var rig = new Rig(pet: true); // no server-age API: only the death says the pet is gone
|
||||
rig.Run(3_000);
|
||||
Check.Eq(rig.Summons, 0, "the pet is out: no summon");
|
||||
rig.Pets.OnPlayerDeath();
|
||||
Check.True(Logged("died: 1 pet(s) out are left behind"), "the death is logged with the pet left behind");
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "after the death the first fight summons at once");
|
||||
Check.True(Logged("left behind)") && Logged("0x80310020"), "the left-behind pet is logged with its id");
|
||||
}
|
||||
|
||||
private static void DeathMidSummon()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "first summon");
|
||||
rig.Pets.OnPlayerDeath(); // in flight: no pet, no charge drop yet
|
||||
Check.True(Logged("the summon state was cleared"), "the in-flight summon is dropped and logged");
|
||||
rig.Run(30_000);
|
||||
Check.Eq(rig.Summons, 1, "the server's 45 s essence cooldown still holds after the death");
|
||||
rig.Run(16_000);
|
||||
Check.Eq(rig.Summons, 2, "after the cooldown it summons again");
|
||||
}
|
||||
|
||||
private static void PortalLeavesPetBehind()
|
||||
{
|
||||
using var rig = new Rig(pet: true);
|
||||
rig.Run(2_000);
|
||||
Check.Eq(rig.Summons, 0, "the pet is out: no summon");
|
||||
rig.Pets.OnPortal();
|
||||
Check.True(Logged("portal space: 1 pet(s) out are left behind"), "the portal is logged");
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "after the portal the first fight summons");
|
||||
rig.Pets.OnChatWindowText("Pet Tester's Fire Moar is already active.");
|
||||
rig.Run(4 * 60_000);
|
||||
Check.Eq(rig.Summons, 1, "the server still has that pet: it counts as out again, no more Uses");
|
||||
}
|
||||
|
||||
private static void NoRecordIsSilence()
|
||||
{
|
||||
using var rig = new Rig(serverAge: true, pet: true);
|
||||
ServerAges[Pet] = -1; // an engine reload: no record for anything
|
||||
rig.Run(50_000);
|
||||
Check.Eq(rig.Summons, 0, "no record for 50 s: still taken as out");
|
||||
rig.Run(12_000);
|
||||
Check.Eq(rig.Summons, 1, "no record for 60 s of watching: silence, a new pet is summoned");
|
||||
Check.True(Logged("s of watching"), "logged as silence");
|
||||
}
|
||||
|
||||
private static void RescanZeroRead()
|
||||
{
|
||||
using var rig = new Rig(spirit: true);
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "50 charges: summon");
|
||||
Rig.SetCharges(0); // an inventory rescan: the property reads 0 for now
|
||||
rig.Run(46_000);
|
||||
Check.Eq(rig.Refills, 0, "no spirit spent on a read of 0 right after 50 (before: a refill)");
|
||||
Check.Eq(rig.Summons, 2, "it summons from the essence after the cooldown");
|
||||
Check.True(Logged("taken as a read in progress"), "the implausible read is logged");
|
||||
}
|
||||
|
||||
private static void UnconfirmedEmptyTried()
|
||||
{
|
||||
using var rig = new Rig(charges: 0); // no spirit, the read says empty from the start
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 1, "the server never called it empty: one summon is tried (before: parked every 15 s, never tried)");
|
||||
Check.True(Logged("the server hasn't called it empty"), "the try is logged");
|
||||
rig.Pets.OnChatWindowText("Your summoning device does not have enough charges to function!");
|
||||
rig.Run(120_000);
|
||||
Check.Eq(rig.Summons, 1, "confirmed empty: parked, no Use every 15 s");
|
||||
Rig.SetCharges(50); // refilled by hand
|
||||
rig.Run(2_000);
|
||||
Check.Eq(rig.Summons, 2, "charges again: it summons");
|
||||
}
|
||||
|
||||
private static void VanishedEssenceReplaced()
|
||||
{
|
||||
using var rig = new Rig(replacement: true);
|
||||
FakeHost.Names.Remove(Essence); // dropped on a corpse the client let go; the cache still has it
|
||||
FakeHost.Containers.Remove(Essence); // (container reads 0, which read as "in the pack")
|
||||
rig.Run(1_500);
|
||||
Check.Eq(rig.Summons, 0, "the vanished essence is not used");
|
||||
Check.Eq(FakeHost.Uses.Count(u => u == Essence2), 1, "its same-named successor in the pack is");
|
||||
}
|
||||
}
|
||||
235
Tools/RynthCore.RynthAiHostTests/Tests/RingTests.cs
Normal file
235
Tools/RynthCore.RynthAiHostTests/Tests/RingTests.cs
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// "It doesn't like to use rings even when set" (2026-11-06). A rule with Ring on casts a ring only
|
||||
// when Min Ring Targets monsters are within Ring Range of the character and a ring of the cast's
|
||||
// element is known; otherwise the rule's other shape. Nothing said which of those held a ring
|
||||
// back, so a player saw bolts and no reason. Now the log says it (the count against the setting,
|
||||
// Ring Range 0, or the ring that isn't known and why), for the cast itself only and never every
|
||||
// attack. And a War caster whose rule says Nether (its bolts are Fire's) casts Fire's rings: they
|
||||
// used to be looked up under Nether, which War has none of.
|
||||
internal static class RingTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const uint Lb = 0x5B480000;
|
||||
private const int Target = unchecked((int)0x80000301);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("rings: the count is the live monsters within Ring Range of the character (dead and unattackable left out)", LiveCount);
|
||||
r.Add("rings: too few near is logged with the count and the setting, at most every 30 s per rule", NotDueLogged);
|
||||
r.Add("rings: Ring Range 0 turns rings off and says so once", RingRangeZero);
|
||||
r.Add("rings: a ring that isn't known says why (tier, rings tried), for the cast only, not element probes", NoRingKnownReason);
|
||||
r.Add("rings: a War caster whose rule says Nether casts Fire's ring, as its bolts are Fire", WarCasterNetherRule);
|
||||
}
|
||||
|
||||
private static MonsterRule BoltRing(string name = "Default") => new() { Name = name, UseBolt = true, UseRing = true };
|
||||
|
||||
private static string NameOf(int id) => id == 0 ? "(none)" : SpellTable.ById(id)?.Name ?? $"#{id}";
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new();
|
||||
public readonly CombatManager C;
|
||||
public DateTime Now = new(2026, 11, 6, 12, 0, 0);
|
||||
private uint _next = 0x80000301;
|
||||
|
||||
/// <summary>A caster at combat tier <paramref name="tier"/> knowing exactly <paramref name="known"/>,
|
||||
/// with monsters at (north, east, up, health) metres from it; health null = never sent.</summary>
|
||||
public Rig(int tier, string[] known, (double N, double E, double Up, float? Health, bool Attackable)[]? mobs = null,
|
||||
(int Buffed, int Training)? war = null, (int Buffed, int Training)? voidMagic = null)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
foreach (string n in known)
|
||||
{
|
||||
var rows = SpellTable.Named(n).ToList();
|
||||
Check.True(rows.Count > 0, $"test setup: '{n}' is in the spell data");
|
||||
foreach (var row in rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
}
|
||||
int T(int k) => k <= tier ? 0 : 10000; // the tier reads the no-skills stub (250 buffed)
|
||||
S.MinSkillLevelTier1 = 0; S.MinSkillLevelTier2 = T(2); S.MinSkillLevelTier3 = T(3); S.MinSkillLevelTier4 = T(4);
|
||||
S.MinSkillLevelTier5 = T(5); S.MinSkillLevelTier6 = T(6); S.MinSkillLevelTier7 = T(7); S.MinSkillLevelTier8 = T(8);
|
||||
S.RingRange = 5; S.MinRingTargets = 3; S.WallRange = 0; S.BlastRange = 0;
|
||||
|
||||
FakeHost.Names[Player] = "Me";
|
||||
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
if (war is { } w) FakeHost.Skills[(Player, 34)] = w;
|
||||
if (voidMagic is { } v) FakeHost.Skills[(Player, 43)] = v;
|
||||
var ids = new List<uint>();
|
||||
var health = new Dictionary<uint, float>();
|
||||
foreach (var m in mobs ?? Array.Empty<(double, double, double, float?, bool)>())
|
||||
{
|
||||
uint id = _next++;
|
||||
FakeHost.Names[id] = "Drudge Skulker";
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, (float)(96 + m.E), (float)(96 + m.N), (float)m.Up);
|
||||
FakeHost.ItemTypes[id] = 0x10; // a creature
|
||||
if (!m.Attackable) FakeHost.NotAttackable.Add(id);
|
||||
if (m.Health is float h) health[id] = h;
|
||||
ids.Add(id);
|
||||
}
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, ids, health);
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
if (war != null || voidMagic != null)
|
||||
{
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
C.SetCharacterSkills(skills);
|
||||
}
|
||||
var sm = new SpellManager(host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.RefreshKnownSpells();
|
||||
C.SetSpellManager(sm);
|
||||
C.TargetClock = () => Now;
|
||||
}
|
||||
|
||||
/// <summary>The cast itself (a target id, as AttackWithMagic passes it).</summary>
|
||||
public (string Spell, string Shape) Cast(string element, MonsterRule rule)
|
||||
{
|
||||
int id = C.FindBestShapedSpell(element, rule, out _, out int shape, arcTargetId: Target);
|
||||
return (NameOf(id), CombatManager.ShapeName(shape));
|
||||
}
|
||||
|
||||
/// <summary>An element probe (no target), as Auto's weakness pick and the wand check ask.</summary>
|
||||
public int Probe(string element, MonsterRule rule) => C.FindBestShapedSpell(element, rule, out _, out _);
|
||||
}
|
||||
|
||||
private static int Lines(string text) => FakeHost.Logs.Count(l => l.Contains(text));
|
||||
|
||||
// Three living, attackable monsters inside 5 m (one whose health was never sent, as ACE sends it
|
||||
// only for the selected target; one partly above), and around them one at 6 m, a dead one and an
|
||||
// unattackable one (an NPC) right next to the character: 3 count.
|
||||
private static void LiveCount()
|
||||
{
|
||||
var mobs = new (double, double, double, float?, bool)[]
|
||||
{
|
||||
(2, 0, 0, 0.8f, true),
|
||||
(0, 3, 0, null, true),
|
||||
(3, 0, 4, 1f, true), // 3 north, 4 up: 5.0 m, on the edge (in)
|
||||
(6, 0, 0, 1f, true), // out
|
||||
(1, 0, 0, 0f, true), // dead
|
||||
(0, 1, 0, 1f, false), // not attackable
|
||||
};
|
||||
var known = new[] { "Frost Bolt VI", "Halo of Frost" };
|
||||
|
||||
var rig = new Rig(6, known, mobs);
|
||||
rig.S.MinRingTargets = 3;
|
||||
Check.Eq(rig.Cast("Cold", BoltRing()), ("Halo of Frost", "Ring"), "3 near, 3 needed: the ring");
|
||||
|
||||
rig = new Rig(6, known, mobs);
|
||||
rig.S.MinRingTargets = 4;
|
||||
Check.Eq(rig.Cast("Cold", BoltRing()), ("Frost Bolt VI", "Bolt"), "3 near, 4 needed: the bolt");
|
||||
Check.Eq(Lines("3 monsters within Ring Range 5 and Min Ring Targets is 4"), 1, "the log gives the count and the setting");
|
||||
|
||||
rig = new Rig(6, known, mobs);
|
||||
rig.S.MinRingTargets = 3; rig.S.RingRange = 4;
|
||||
Check.Eq(rig.Cast("Cold", BoltRing()).Shape, "Bolt", "Ring Range 4: the one at 5 m is out, 2 near");
|
||||
Check.Eq(Lines("2 monsters within Ring Range 4"), 1, "the count at Ring Range 4");
|
||||
}
|
||||
|
||||
private static void NotDueLogged()
|
||||
{
|
||||
var rig = new Rig(6, new[] { "Frost Bolt VI", "Halo of Frost" });
|
||||
int near = 1;
|
||||
rig.C.RingCountOverride = () => near;
|
||||
rig.S.MinRingTargets = 3;
|
||||
var rule = BoltRing("Drudge");
|
||||
|
||||
Check.Eq(rig.Cast("Cold", rule), ("Frost Bolt VI", "Bolt"), "1 near, 3 needed: the bolt");
|
||||
Check.Eq(Lines("rule 'Drudge' has Ring on: no ring yet, 1 monster within Ring Range 5 and Min Ring Targets is 3"), 1, "said, singular");
|
||||
for (int i = 0; i < 20; i++) { rig.Now = rig.Now.AddSeconds(1); rig.Cast("Cold", rule); }
|
||||
Check.Eq(Lines("has Ring on: no ring yet"), 1, "not every attack: once in 20 s");
|
||||
rig.Now = rig.Now.AddSeconds(11);
|
||||
near = 2;
|
||||
rig.Cast("Cold", rule);
|
||||
Check.Eq(Lines("has Ring on: no ring yet"), 2, "again after 30 s, with the new count");
|
||||
Check.Eq(Lines("2 monsters within Ring Range 5"), 1, "the new count");
|
||||
|
||||
near = 3;
|
||||
Check.Eq(rig.Cast("Cold", rule), ("Halo of Frost", "Ring"), "3 near: the ring");
|
||||
Check.Eq(Lines("has Ring on: no ring yet"), 2, "a ring cast says nothing more (the cast line has shape=Ring)");
|
||||
|
||||
var other = BoltRing("Mosswart");
|
||||
near = 1;
|
||||
rig.Cast("Cold", other);
|
||||
Check.Eq(Lines("rule 'Mosswart' has Ring on: no ring yet"), 1, "per rule");
|
||||
|
||||
var noRing = new MonsterRule { Name = "Golem", UseBolt = true };
|
||||
rig.Cast("Cold", noRing);
|
||||
Check.Eq(Lines("rule 'Golem'"), 0, "a rule without Ring says nothing about rings");
|
||||
|
||||
rig.Probe("Cold", BoltRing("Lugian"));
|
||||
Check.Eq(Lines("rule 'Lugian'"), 0, "an element probe says nothing");
|
||||
}
|
||||
|
||||
private static void RingRangeZero()
|
||||
{
|
||||
var rig = new Rig(6, new[] { "Frost Bolt VI", "Halo of Frost" });
|
||||
rig.C.RingCountOverride = () => 8;
|
||||
rig.S.RingRange = 0;
|
||||
Check.Eq(rig.Cast("Cold", BoltRing()), ("Frost Bolt VI", "Bolt"), "Ring Range 0: no ring, however many are near");
|
||||
rig.Now = rig.Now.AddMinutes(5);
|
||||
rig.Cast("Cold", BoltRing());
|
||||
Check.Eq(Lines("has Ring on, but Ring Range is 0: rings are off"), 1, "said once");
|
||||
Check.Eq(rig.S.RingRange, 0, "the setting is left as it is");
|
||||
}
|
||||
|
||||
private static void NoRingKnownReason()
|
||||
{
|
||||
// Tier 4: rings are level 5 and 7, so none is castable yet, known or not.
|
||||
var low = new Rig(4, new[] { "Frost Bolt IV", "Halo of Frost" });
|
||||
low.C.RingCountOverride = () => 5;
|
||||
Check.Eq(low.Cast("Cold", BoltRing()), ("Frost Bolt IV", "Bolt"), "tier 4: the bolt");
|
||||
Check.Eq(Lines("no Cold ring spell known (War Magic tier 4: rings are level 5 and 7)"), 1, "the log names the tier");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Ring spell not found for Cold (War Magic tier 4")), "and the chat");
|
||||
Check.Eq(Lines("has Ring on: no ring yet"), 0, "not a count problem: the count was met");
|
||||
|
||||
// Tier 6 knowing only the II (level 7): the rings tried, and that the II waits for tier 7.
|
||||
var six = new Rig(6, new[] { "Frost Bolt VI", "Halo of Frost II" });
|
||||
six.C.RingCountOverride = () => 5;
|
||||
Check.Eq(six.Cast("Cold", BoltRing()).Shape, "Bolt", "tier 6 with only the II: the bolt");
|
||||
Check.Eq(Lines("tried: Halo of Frost; Halo of Frost II is level 7"), 1, "the rings tried");
|
||||
|
||||
// Element probes (Auto's weakness pick asks every element) say nothing: the chat used to
|
||||
// report "Ring spell not found for Slash" while the bot cast Cold.
|
||||
var probe = new Rig(7, new[] { "Frost Bolt VI", "Halo of Frost II", "Whirling Blade VI" });
|
||||
probe.C.RingCountOverride = () => 5;
|
||||
foreach (string e in new[] { "Slash", "Fire", "Acid", "Pierce", "Bludgeon", "Lightning" })
|
||||
probe.Probe(e, BoltRing());
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Ring spell not found")), 0, "no chat from the probes");
|
||||
Check.Eq(Lines("ring spell known"), 0, "no log from the probes");
|
||||
Check.Eq(probe.Cast("Cold", BoltRing()), ("Halo of Frost II", "Ring"), "the cast's own element has its ring");
|
||||
Check.Eq(probe.Cast("Slash", BoltRing()).Shape, "Bolt", "a cast of Slash, no Slash ring: the bolt");
|
||||
Check.Eq(Lines("no Slash ring spell known (tried: Horizon's Blades II, Horizon's Blades)"), 1, "said for the cast");
|
||||
}
|
||||
|
||||
private static void WarCasterNetherRule()
|
||||
{
|
||||
var known = new[] { "Flame Bolt VI", "Cassius' Ring of Fire II", "Nether Bolt VI", "Clouded Soul II" };
|
||||
var rig = new Rig(7, known, war: (400, 3), voidMagic: (10, 1));
|
||||
rig.C.RingCountOverride = () => 5;
|
||||
Check.Eq(rig.Cast("Nether", BoltRing()), ("Cassius' Ring of Fire II", "Ring"), "War only, rule says Nether: Fire's ring");
|
||||
rig.C.RingCountOverride = () => 1;
|
||||
Check.Eq(rig.Cast("Nether", BoltRing()), ("Flame Bolt VI", "Bolt"), "too few near: Fire's bolt, as before");
|
||||
|
||||
// Void trained: the Nether rule casts Void's ring, as before.
|
||||
var both = new Rig(7, known, war: (400, 3), voidMagic: (400, 3));
|
||||
both.C.RingCountOverride = () => 5;
|
||||
Check.Eq(both.Cast("Nether", BoltRing()), ("Clouded Soul II", "Ring"), "Void trained: Void's ring");
|
||||
|
||||
// War only, Nether rule, no fire ring known: the reason names Fire's rings.
|
||||
var none = new Rig(7, new[] { "Flame Bolt VI" }, war: (400, 3), voidMagic: (10, 1));
|
||||
none.C.RingCountOverride = () => 5;
|
||||
Check.Eq(none.Cast("Nether", BoltRing()), ("Flame Bolt VI", "Bolt"), "no fire ring known: the bolt");
|
||||
Check.Eq(Lines("no Nether ring spell known (tried: Cassius' Ring of Fire II, Cassius' Ring of Fire, Flame Ring)"), 1, "the rings tried are Fire's");
|
||||
}
|
||||
}
|
||||
|
|
@ -40,6 +40,9 @@ internal static class SelfTestMetaTests
|
|||
Check.Eq(bare.M.Expressions.Evaluate("ratargetcount[]"), "-1", "not wired: -1");
|
||||
bare.M.SetCombatTargetCount(() => 3);
|
||||
Check.Eq(bare.M.Expressions.Evaluate("ratargetcount[]"), "3", "wired: combat's count");
|
||||
Check.Eq(bare.M.Expressions.Evaluate("ralastchestlooted[]"), "0", "ralastchestlooted[] not wired: 0");
|
||||
bare.M.SetLastChestLooted(() => 0x80061193u);
|
||||
Check.Eq(bare.M.Expressions.Evaluate("ralastchestlooted[]"), "2147881363", "wired: the chest's id, as wobjectgetid[] gives it");
|
||||
|
||||
Run Beside(int targets)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -0,0 +1,146 @@
|
|||
using System.IO;
|
||||
using System.Threading;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The session's luminance from the active server profile's bank value (SessionStatsTracker: RynthAi's
|
||||
// Mini Remote stats, which RynthTracker shows; 2026-11-02). A server that keeps earned luminance in its
|
||||
// bank where the client can't read it has its server plugin publish "bankLuminance" (a /b every minute);
|
||||
// its rises are Lum/hr, a drop (spending) isn't negative, and ACECustom's own bank property (9005) wins
|
||||
// when it is readable. Without the value nothing changes.
|
||||
internal static class SessionBankProfileTests
|
||||
{
|
||||
private const uint Player = 0x50000D02;
|
||||
private const uint TotalXp = 1;
|
||||
private const uint BankedLuminance = 9005;
|
||||
private const string Tag = "[RynthAi] Mini Remote stats:";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("session stats: the server profile's bank luminance rises are Lum/hr, a drop isn't negative", BankRises);
|
||||
r.Add("session stats: without a bank value in the profile, luminance stays as before", NoValue);
|
||||
r.Add("session stats: ACECustom's bank property wins over the profile's bank value", PropertyWins);
|
||||
r.Add("session stats: the profile's bank baseline carries over a reload", AcrossReload);
|
||||
}
|
||||
|
||||
private static string Folder(string name)
|
||||
{
|
||||
string dir = Path.Combine(Program.TempRoot, "session-bank", name);
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static RynthCoreHost Create(double? bank)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeServerState.Reset();
|
||||
FakeServerState.Install();
|
||||
var host = FakeHost.Create(Player);
|
||||
FakeHost.Quads[(Player, TotalXp)] = 1_000_000;
|
||||
FakeServerState.StateJson = FakeServerState.State("testsrv", "Test Server", "RynthTestSrv", "Test World");
|
||||
SetBank(bank);
|
||||
return host;
|
||||
}
|
||||
|
||||
private static void SetBank(double? bank)
|
||||
=> FakeServerState.ProfileJson = bank is double b
|
||||
? FakeServerState.Profile("testsrv", ("bankLuminance", b))
|
||||
: FakeServerState.Profile("testsrv", ("difficultyTier", 0));
|
||||
|
||||
private static SessionStatsTracker LogIn(RynthCoreHost host, string dir)
|
||||
{
|
||||
var t = new SessionStatsTracker(host, Tag, dir) { ProfileIntervalMs = 0 };
|
||||
t.OnLoginComplete();
|
||||
t.Tick();
|
||||
return t;
|
||||
}
|
||||
|
||||
/// <summary>The next poll (the tracker reads every 0.5 s on the real clock).</summary>
|
||||
private static void NextPoll(SessionStatsTracker t)
|
||||
{
|
||||
Thread.Sleep(550);
|
||||
t.Tick();
|
||||
}
|
||||
|
||||
private static void BankRises()
|
||||
{
|
||||
try
|
||||
{
|
||||
var host = Create(1_000_000);
|
||||
var t = LogIn(host, Folder("rises"));
|
||||
Check.Eq(t.View.Lum, 0L, "the first reading is the baseline");
|
||||
SetBank(1_250_000);
|
||||
NextPoll(t);
|
||||
Check.Eq(t.View.Lum, 250_000L, "a rise is earned luminance");
|
||||
Check.True(t.View.LumPerHour > 0, "Lum/hr above 0");
|
||||
NextPoll(t);
|
||||
Check.Eq(t.View.Lum, 250_000L, "the same reading again adds nothing");
|
||||
SetBank(200_000); // spent from the bank
|
||||
NextPoll(t);
|
||||
Check.Eq(t.View.Lum, 250_000L, "a drop isn't counted (nor negative)");
|
||||
SetBank(260_000);
|
||||
NextPoll(t);
|
||||
Check.Eq(t.View.Lum, 310_000L, "the next rise counts from the drop");
|
||||
Check.Eq(t.View.LumLast5Min, 310_000L, "and in the last five minutes");
|
||||
t.OnLogout();
|
||||
}
|
||||
finally { FakeHost.Reset(); FakeServerState.Reset(); }
|
||||
}
|
||||
|
||||
private static void NoValue()
|
||||
{
|
||||
try
|
||||
{
|
||||
var host = Create(null);
|
||||
FakeHost.Quads[(Player, 6)] = 5_000; // AvailableLuminance, as on retail ACE
|
||||
var t = LogIn(host, Folder("none"));
|
||||
FakeHost.Quads[(Player, 6)] = 7_000;
|
||||
NextPoll(t);
|
||||
Check.Eq(t.View.Lum, 2_000L, "the character's luminance counts as before");
|
||||
Check.False(t.View.PassUpTracked, "no bank is tracked");
|
||||
t.OnLogout();
|
||||
}
|
||||
finally { FakeHost.Reset(); FakeServerState.Reset(); }
|
||||
}
|
||||
|
||||
private static void PropertyWins()
|
||||
{
|
||||
try
|
||||
{
|
||||
var host = Create(50);
|
||||
FakeHost.Quads[(Player, BankedLuminance)] = 1_000_000;
|
||||
var t = LogIn(host, Folder("property"));
|
||||
SetBank(900_000);
|
||||
FakeHost.Quads[(Player, BankedLuminance)] = 1_000_400;
|
||||
NextPoll(t);
|
||||
Check.Eq(t.View.Lum, 400L, "9005's rise counts, the profile's value is not used");
|
||||
t.OnLogout();
|
||||
}
|
||||
finally { FakeHost.Reset(); FakeServerState.Reset(); }
|
||||
}
|
||||
|
||||
// A hot reload is a Shutdown (the save) and a new copy's OnLoginComplete (the restore).
|
||||
private static void AcrossReload()
|
||||
{
|
||||
try
|
||||
{
|
||||
var host = Create(1_000_000);
|
||||
string dir = Folder("reload");
|
||||
var a = LogIn(host, dir);
|
||||
SetBank(1_100_000);
|
||||
NextPoll(a);
|
||||
Check.Eq(a.View.Lum, 100_000L, "before the reload");
|
||||
a.Shutdown();
|
||||
SetBank(1_150_000); // earned while the plugin was unloaded
|
||||
var b = LogIn(host, dir);
|
||||
NextPoll(b);
|
||||
Check.Eq(b.View.Lum, 150_000L, "the gap's luminance counts once after the reload");
|
||||
b.OnLogout();
|
||||
}
|
||||
finally { FakeHost.Reset(); FakeServerState.Reset(); }
|
||||
}
|
||||
}
|
||||
|
|
@ -41,9 +41,18 @@ internal static class ShieldBuffTests
|
|||
r.Add("shield buffs: a shield being moved is not cast at until the move settles", MidSwapWaits);
|
||||
r.Add("shield buffs: renewed on the armor's timers (Rebuff With, Also Refresh Under, Force Rebuff)", RenewedLikeArmor);
|
||||
r.Add("shield buffs: a fizzle, a refusal or a late armor line at the shield leaves the armor alone", RefusalsLeaveArmor);
|
||||
r.Add("shield buffs: casts at the shield with no answer, or 'cannot be cast on', rest shield buffing; the armor carries on", NoAnswerParks);
|
||||
r.Add("shield buffs: casts at the shield with no answer rest shield buffing; 'cannot be cast on' skips that shield for good (kept, /ra buffs unbuffable clear); the armor carries on", NoAnswerParks);
|
||||
r.Add("shield buffs: the shield's timers are saved and loaded with the others", TimersSaved);
|
||||
r.Add("shield buffs: Buff the shield defaults on, loads, saves, copies, is in the settings map", Setting);
|
||||
r.Add("shield buffs: a shield marked No buff gets nothing (rebuff batch, Force Rebuff, expiring), never makes buffing due; the armor as always", ExcludedShield);
|
||||
r.Add("shield buffs: two shields listed, one marked No buff: the other is still buffed", ExcludedShieldOtherStillBuffed);
|
||||
r.Add("shield buffs: cast lines naming a No buff shield (self-cast reaching it, late line, an in-flight cast) never make a rebuff due", ExcludedShieldCastLinesNeverDue);
|
||||
r.Add("shield buffs: the kept shield choice is read again at once when an entry's No buff flips in place", ExcludedFlipInvalidatesShieldChoice);
|
||||
r.Add("shield buffs: No buff on a weapon (non-shield) does nothing: the weapon auras as always", ExcludedWeaponDoesNothing);
|
||||
r.Add("shield buffs: the Items bridge carries noBuff for every entry, applies it back for shields only, absent = unchanged, never saved", NoBuffPayloadContract);
|
||||
r.Add("shield buffs: a No buff shield in the off hand: no shield is buffed, not one put away for the wand before", ExcludedWornBeatsStaleStow);
|
||||
r.Add("shield buffs: a shield listed twice, one rule No buff: left alone, in either order", ExcludedAnyRuleEitherOrder);
|
||||
r.Add("shield buffs: a VTank re-import keeps a shield's No buff", ReimportKeepsShieldExclusion);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
|
@ -499,17 +508,37 @@ internal static class ShieldBuffTests
|
|||
Check.Eq(rig.Sm.UnresolvableSpellIds.Count, 0, "no spell blacklisted (it just went on the armor)");
|
||||
Check.True(Armor.All(rig.HasArmor), "the armor got everything");
|
||||
|
||||
// "cannot be cast on" (ACE IsInvalidTarget) parks it at once.
|
||||
// "cannot be cast on" (ACE IsInvalidTarget): the shield takes no spells, never buffed again
|
||||
// (2026-11-08, Tom: "if an item is deemed unbuffable it should just skip it altogether").
|
||||
string folder = Path.Combine(Program.TempRoot, "shieldbuff-unbuffable");
|
||||
Directory.CreateDirectory(folder);
|
||||
foreach (string f in Directory.GetFiles(folder)) File.Delete(f);
|
||||
var invalid = new Rig(worn: true);
|
||||
invalid.B.SetTimerPath(folder);
|
||||
invalid.PutAwayForWand();
|
||||
Check.Eq(ToFirstShieldCast(invalid), "Impenetrability VI", "a cast at the shield");
|
||||
invalid.B.OnChatWindowText("Impenetrability VI cannot be cast on Kite Shield.", 7);
|
||||
Check.Eq(invalid.B.PendingSpellId, 0, "it ends the cast");
|
||||
Check.Eq(invalid.B.UnbuffableShields.Count, 1, "the shield is marked as taking no spells");
|
||||
invalid.EndRun();
|
||||
Check.False(invalid.B.NeedsAnyBuff(), "the shield rests");
|
||||
Check.False(invalid.B.NeedsAnyBuff(), "the shield never holds Buffing");
|
||||
Check.Eq(invalid.CastAll().Count, 0, "nothing more at it");
|
||||
invalid.B.ForceFullRebuff();
|
||||
Check.Eq(string.Join(", ", At(invalid.CastAll(), "Kite Shield")), ArmorAtPlayer, "Force Rebuff gives it a fresh try");
|
||||
Check.Eq(At(invalid.CastAll(), "Kite Shield").Count(), 0, "Force Rebuff doesn't try it again either");
|
||||
Check.True(File.ReadAllLines(Path.Combine(folder, "bufftimers.txt")).Any(l => l.StartsWith("unbuffable|", StringComparison.Ordinal)), "kept in bufftimers.txt");
|
||||
|
||||
// Kept across a reload; /ra buffs unbuffable clear forgets it and it is tried again.
|
||||
var reloaded = new Rig(worn: true);
|
||||
reloaded.PutAwayForWand();
|
||||
reloaded.B.SetTimerPath(folder);
|
||||
Check.Eq(reloaded.B.UnbuffableShields.Count, 1, "loaded back");
|
||||
Check.Eq(At(reloaded.CastAll(), "Kite Shield").Count(), 0, "still skipped after the reload");
|
||||
var listed = reloaded.B.UnbuffableCommand(clear: false);
|
||||
Check.True(listed.Any(l => l.Contains("Kite Shield", StringComparison.Ordinal)), "/ra buffs unbuffable lists it: " + string.Join(" | ", listed));
|
||||
reloaded.B.UnbuffableCommand(clear: true);
|
||||
Check.Eq(reloaded.B.UnbuffableShields.Count, 0, "cleared");
|
||||
reloaded.B.ForceFullRebuff();
|
||||
Check.Eq(string.Join(", ", At(reloaded.CastAll(), "Kite Shield")), ArmorAtPlayer, "cleared: tried again");
|
||||
|
||||
// The same line with nothing aimed at a shield changes nothing.
|
||||
var other = new Rig(worn: true, listShield: false);
|
||||
|
|
@ -537,6 +566,271 @@ internal static class ShieldBuffTests
|
|||
Check.Eq(again.CastAll().Count, 0, "nothing due after the reload");
|
||||
}
|
||||
|
||||
// ── No buff (ItemRule.KeepBuffed off on a listed shield) ─────────────────
|
||||
|
||||
private const string MarkedWhy = "the listed shield is marked No buff";
|
||||
|
||||
private static void ExcludeId(Rig rig, uint id) => rig.S.ItemRules.First(x => x.Id == unchecked((int)id)).KeepBuffed = false;
|
||||
|
||||
private static void ExcludedShield()
|
||||
{
|
||||
// Control: the same rig, not marked, casts at the shield (StowedShieldBuffed has the detail).
|
||||
var control = new Rig(worn: true);
|
||||
control.PutAwayForWand();
|
||||
Check.Eq(At(control.CastAll(), "Kite Shield").Count(), Armor.Length, "control: the listed shield gets its armor spells");
|
||||
|
||||
// Put away for the wand and worn: left alone either way.
|
||||
foreach (bool stowed in new[] { true, false })
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
ExcludeId(rig, Kite);
|
||||
if (stowed) rig.PutAwayForWand();
|
||||
string how = stowed ? "put away for the wand" : "in the off hand";
|
||||
Check.Eq(rig.B.ShieldToBuff(out string where), 0, $"{how}: no shield to buff ({where})");
|
||||
Check.Eq(where, MarkedWhy, $"{how}: and the reason says why");
|
||||
var sent = rig.CastAll();
|
||||
Check.Eq(At(sent, "Kite Shield").Count(), 0, $"{how}: nothing aimed at the marked shield");
|
||||
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", $"{how}: the character's buffs as always");
|
||||
Check.False(rig.B.NeedsAnyBuff(), $"{how}: nothing due after the run");
|
||||
|
||||
// Force Rebuff (and /ra buff, which runs it): still nothing at the shield.
|
||||
rig.B.ForceFullRebuff();
|
||||
sent = rig.CastAll();
|
||||
Check.Eq(At(sent, "Kite Shield").Count(), 0, $"{how}: Force Rebuff casts nothing at it");
|
||||
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", $"{how}: Force Rebuff still renews the character's");
|
||||
Check.False(rig.B.NeedsAnyBuff(), $"{how}: the run ends done");
|
||||
Check.False(FakeHost.Casts.Any(c => c.Target == Kite), $"{how}: no cast ever went at the shield");
|
||||
}
|
||||
|
||||
// A shield timer from before it was marked running low makes nothing due.
|
||||
var was = new Rig(worn: true);
|
||||
was.PutAwayForWand();
|
||||
was.CastAll();
|
||||
Check.Eq(was.B.ShieldSpellCount, Armor.Length, "buffed before it was marked");
|
||||
was.SetShieldLeft("Flame Bane VI", 10);
|
||||
Check.True(was.B.NeedsAnyBuff(), "control: its bane running out is due while it is buffed");
|
||||
ExcludeId(was, Kite);
|
||||
was.S.ItemRules = new List<ItemRule>(was.S.ItemRules); // the Items face saves a new list
|
||||
Check.False(was.B.NeedsAnyBuff(), "marked: its expiring bane is not due");
|
||||
Check.Eq(was.CastAll().Count, 0, "and nothing is cast for it");
|
||||
|
||||
// Two shields listed, the worn one marked: the other (in a pack, not in use) is no target either.
|
||||
var two = new Rig(worn: true);
|
||||
two.List(Sword, Kite, Round);
|
||||
ExcludeId(two, Kite);
|
||||
Check.Eq(two.B.ShieldToBuff(out _), 0, "the worn shield marked, the other in a pack: none");
|
||||
Check.Eq(At(two.CastAll(), "Round Shield").Count(), 0, "nothing goes to the other shield instead");
|
||||
}
|
||||
|
||||
private static void ExcludedShieldOtherStillBuffed()
|
||||
{
|
||||
// The Kite marked and in a pack, the Round worn: the Round is buffed.
|
||||
var pin = new Rig();
|
||||
Wear(Round);
|
||||
pin.List(Sword, Kite, Round);
|
||||
ExcludeId(pin, Kite);
|
||||
Check.Eq(pin.B.ShieldToBuff(out string where), unchecked((int)Round), "the other listed shield, worn: " + where);
|
||||
var sent = pin.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "Round Shield")), ArmorAtPlayer, "the other shield gets the armor spells");
|
||||
Check.Eq(At(sent, "Kite Shield").Count(), 0, "nothing at the marked one");
|
||||
|
||||
// Both read as in hand, the marked Kite listed FIRST. Ignoring the flag the first listed
|
||||
// (Kite) would be picked; with it, the Round is.
|
||||
var both = new Rig(worn: true);
|
||||
Wear(Round);
|
||||
both.List(Sword, Kite, Round);
|
||||
Check.Eq(both.B.ShieldToBuff(out _), unchecked((int)Kite), "control: nothing marked, the first listed in hand is picked");
|
||||
ExcludeId(both, Kite);
|
||||
Check.Eq(both.B.ShieldToBuff(out where, fresh: true), unchecked((int)Round), "the Kite marked: the Round is picked (" + where + ")");
|
||||
sent = both.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "Round Shield")), ArmorAtPlayer, "and buffed");
|
||||
Check.Eq(At(sent, "Kite Shield").Count(), 0, "never the marked one");
|
||||
Check.False(both.B.NeedsAnyBuff(), "nothing due after the run");
|
||||
}
|
||||
|
||||
private static void ExcludedShieldCastLinesNeverDue()
|
||||
{
|
||||
// 1. The self-cast reached the worn, marked shield ("You cast X on Kite Shield"): no timer
|
||||
// is kept for it, so nothing on it can ever run low and make buffing due.
|
||||
var self = new Rig(worn: true);
|
||||
ExcludeId(self, Kite);
|
||||
var sent = self.CastAll(alsoOnShield: _ => true);
|
||||
Check.Eq(At(sent, "Kite Shield").Count(), 0, "nothing aimed at it");
|
||||
Check.Eq(self.B.ShieldSpellCount, 0, "its self-cast lines record no shield timer");
|
||||
Check.True(Armor.All(self.HasArmor), "the armor's are recorded as always");
|
||||
Check.False(self.B.NeedsAnyBuff(), "nothing due");
|
||||
|
||||
// 2. A late line naming it, nothing pending.
|
||||
self.B.OnChatWindowText("You cast Flame Bane VI on Kite Shield", 7);
|
||||
Check.Eq(self.B.ShieldSpellCount, 0, "a late line names it: still no shield timer");
|
||||
Check.False(self.B.NeedsAnyBuff(), "and nothing due");
|
||||
|
||||
// 3. A cast at it already in flight when it is marked: its line may record the timer, but
|
||||
// neither that nor the timer running low makes anything due.
|
||||
var flight = new Rig(worn: true);
|
||||
flight.PutAwayForWand();
|
||||
flight.B.ForceFullRebuff();
|
||||
string first = ToFirstShieldCast(flight);
|
||||
Check.Eq(first, "Impenetrability VI", "a cast at the shield is pending");
|
||||
ExcludeId(flight, Kite);
|
||||
flight.S.ItemRules = new List<ItemRule>(flight.S.ItemRules); // the Items face saves a new list
|
||||
flight.Answer(Kite, first);
|
||||
Check.Eq(flight.B.PendingSpellId, 0, "its line resolves the cast");
|
||||
Check.Eq(flight.CastAll().Count(s => s.EndsWith("@Kite Shield", StringComparison.Ordinal)), 0, "nothing more at it");
|
||||
Check.False(flight.B.NeedsAnyBuff(), "nothing due after the run");
|
||||
if (flight.HasShield("Impenetrability VI"))
|
||||
{
|
||||
flight.SetShieldLeft("Impenetrability VI", 10);
|
||||
Check.False(flight.B.NeedsAnyBuff(), "its recorded timer running low is not due");
|
||||
}
|
||||
Check.Eq(flight.CastAll().Count, 0, "and nothing is cast for it");
|
||||
|
||||
// Control for 1: the same lines with it not marked do record the shield's timers.
|
||||
var control = new Rig(worn: true);
|
||||
control.CastAll(alsoOnShield: _ => true);
|
||||
Check.Eq(control.B.ShieldSpellCount, Armor.Length, "control: not marked, the lines record its timers");
|
||||
}
|
||||
|
||||
private static void ExcludedWornBeatsStaleStow()
|
||||
{
|
||||
// The Kite was put away for the wand some time ago; the Round is now in the off hand.
|
||||
Rig Make(bool excludeRound)
|
||||
{
|
||||
var made = new Rig(worn: true);
|
||||
made.List(Sword, Kite, Round);
|
||||
made.PutAwayForWand(); // the Kite into a pack, remembered as stowed
|
||||
Wear(Round);
|
||||
if (excludeRound) ExcludeId(made, Round);
|
||||
return made;
|
||||
}
|
||||
|
||||
var control = Make(excludeRound: false);
|
||||
Check.Eq(control.B.ShieldToBuff(out string where), unchecked((int)Round), "control: the Round in the off hand is picked (" + where + ")");
|
||||
|
||||
var rig = Make(excludeRound: true);
|
||||
Check.Eq(rig.B.ShieldToBuff(out where), 0, "the marked Round in the off hand: no shield");
|
||||
Check.Eq(where, "the shield in the off hand is marked No buff", "and the reason says so");
|
||||
var sent = rig.CastAll();
|
||||
Check.Eq(At(sent, "Kite Shield").Count() + At(sent, "Round Shield").Count(), 0, "no cast names either shield: " + string.Join(", ", sent));
|
||||
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the character's buffs as always");
|
||||
Check.False(rig.B.NeedsAnyBuff(), "nothing due");
|
||||
}
|
||||
|
||||
private static void ExcludedAnyRuleEitherOrder()
|
||||
{
|
||||
foreach (bool excludedFirst in new[] { false, true })
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
var keep = new ItemRule { Id = unchecked((int)Kite), Name = "Kite Shield", Action = WeaponList.ShieldAction, Element = "", ElementSource = "" };
|
||||
var off = new ItemRule { Id = unchecked((int)Kite), Name = "Kite Shield", Action = WeaponList.ShieldAction, Element = "", ElementSource = "", KeepBuffed = false };
|
||||
var sword = rig.S.ItemRules.First(x => x.Id == unchecked((int)Sword));
|
||||
rig.S.ItemRules = excludedFirst ? new List<ItemRule> { sword, off, keep } : new List<ItemRule> { sword, keep, off };
|
||||
string order = excludedFirst ? "the marked rule first" : "the marked rule second";
|
||||
Check.Eq(rig.B.ShieldToBuff(out string where), 0, $"{order}: no shield ({where})");
|
||||
Check.Eq(At(rig.CastAll(), "Kite Shield").Count(), 0, $"{order}: nothing at it");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReimportKeepsShieldExclusion()
|
||||
{
|
||||
ItemRule Rule(int id, string action, bool keep) => new() { Id = id, Name = "x" + id, Action = action, Element = "Slash", KeepBuffed = keep };
|
||||
var rules = new List<ItemRule>
|
||||
{
|
||||
Rule(1, WeaponList.ShieldAction, false), // a marked shield
|
||||
Rule(2, WeaponList.ShieldAction, true),
|
||||
Rule(3, "Weapon", false), // a "marked" weapon (the flag does nothing there)
|
||||
};
|
||||
foreach (int id in new[] { 1, 2, 3, 4 })
|
||||
RynthCore.Plugin.RynthAi.MiniRemote.VTankUsdImporter.ReplaceItemRule(rules, Rule(id, id <= 2 ? WeaponList.ShieldAction : "Weapon", true));
|
||||
Check.Eq(rules.Count, 4, "each id replaced once, the new one added");
|
||||
Check.True(rules.Single(x => x.Id == 1).ExcludedFromBuffing(), "the marked shield stays marked after a re-import");
|
||||
Check.False(rules.Single(x => x.Id == 2).ExcludedFromBuffing(), "a buffed shield stays buffed");
|
||||
Check.False(rules.Single(x => x.Id == 3).ExcludedFromBuffing(), "a weapon takes the import as it is");
|
||||
Check.False(rules.Single(x => x.Id == 4).ExcludedFromBuffing(), "a new entry is buffed");
|
||||
}
|
||||
|
||||
private static void ExcludedFlipInvalidatesShieldChoice()
|
||||
{
|
||||
var rig = new Rig(worn: true);
|
||||
long ms = 50_000;
|
||||
rig.B.KitClockMs = () => ms;
|
||||
rig.B.ShieldReadMs = 1000; // the shipped value
|
||||
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "the worn shield, kept for a second");
|
||||
ms += 10;
|
||||
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "control: 10 ms later the kept answer");
|
||||
ExcludeId(rig, Kite); // flipped in place: same list, same count
|
||||
ms += 10;
|
||||
Check.Eq(rig.B.ShieldToBuff(out string where), 0, "marked in place: read again at once, none (" + where + ")");
|
||||
rig.S.ItemRules.First(x => x.Id == unchecked((int)Kite)).KeepBuffed = true;
|
||||
ms += 10;
|
||||
Check.Eq(rig.B.ShieldToBuff(out _), unchecked((int)Kite), "and back on: at once");
|
||||
}
|
||||
|
||||
private static void ExcludedWeaponDoesNothing()
|
||||
{
|
||||
// Marking a weapon does nothing: the marked sword's own aura (Blood Drinker) is still due.
|
||||
var rig = new Rig(worn: true, listShield: false);
|
||||
ExcludeId(rig, Sword);
|
||||
var sent = rig.CastAll();
|
||||
Check.Eq(string.Join(", ", At(sent, "player")), $"{Aura}, {ArmorAtPlayer}", "the marked sword still makes its aura due");
|
||||
Check.Eq(rig.B.ShieldToBuff(out _), 0, "and no shield is involved");
|
||||
}
|
||||
|
||||
private static void NoBuffPayloadContract()
|
||||
{
|
||||
const int SwordId = 1, ShieldId = 3;
|
||||
List<ItemRule> Saved(bool swordKeep, bool shieldKeep) => new()
|
||||
{
|
||||
new() { Id = SwordId, Name = "Sword", Action = "Weapon", Element = "Slash", KeepBuffed = swordKeep },
|
||||
new() { Id = ShieldId, Name = "Shield", Action = WeaponList.ShieldAction, Element = "", KeepBuffed = shieldKeep },
|
||||
};
|
||||
|
||||
// Out: every entry carries noBuff, shields and weapons alike.
|
||||
var shown = WeaponList.ForDisplay(Saved(false, false), x => x.Name);
|
||||
Check.True(shown.All(x => x.NoBuff == true), "a marked entry is sent noBuff true (weapon and shield)");
|
||||
shown = WeaponList.ForDisplay(Saved(true, true), x => x.Name);
|
||||
Check.True(shown.All(x => x.NoBuff == false), "a buffed entry is sent noBuff false");
|
||||
string json = JsonSerializer.Serialize(new ItemsBridgePayload { Weapons = WeaponList.ForDisplay(Saved(true, false), x => x.Name) },
|
||||
RynthAiJsonContext.Default.ItemsBridgePayload);
|
||||
Check.Eq(System.Text.RegularExpressions.Regex.Matches(json, "\"noBuff\":").Count, 2, "the wire field is \"noBuff\", once per entry: " + json);
|
||||
Check.True(System.Text.RegularExpressions.Regex.IsMatch(json, "\"noBuff\":\\s*false") && System.Text.RegularExpressions.Regex.IsMatch(json, "\"noBuff\":\\s*true"),
|
||||
"with its value per entry: " + json);
|
||||
|
||||
// Back, in the engine's shape (lower-case names, only the fields WeaponEntry knows).
|
||||
List<ItemRule> Back(string weapons) =>
|
||||
WeaponList.MergeEdited(Saved(true, true),
|
||||
JsonSerializer.Deserialize("{\"weapons\":[" + weapons + "]}", RynthAiJsonContext.Default.ItemsBridgePayload)!.Weapons);
|
||||
const string Sw = "{\"id\":1,\"name\":\"Sword\",\"element\":\"Slash\",\"action\":\"Weapon\"";
|
||||
const string Sh = "{\"id\":3,\"name\":\"Shield\",\"element\":\"Shield\",\"action\":\"Shield\"";
|
||||
var m = Back(Sw + "}," + Sh + ",\"noBuff\":true}");
|
||||
Check.True(m.Single(x => x.Id == ShieldId).ExcludedFromBuffing(), "a shield ticked noBuff is left alone");
|
||||
m = Back(Sw + ",\"noBuff\":true}," + Sh + "}");
|
||||
Check.False(m.Single(x => x.Id == SwordId).ExcludedFromBuffing(), "noBuff on a weapon is ignored");
|
||||
m = WeaponList.MergeEdited(Saved(true, false),
|
||||
JsonSerializer.Deserialize("{\"weapons\":[" + Sw + "}," + Sh + ",\"noBuff\":false}]}", RynthAiJsonContext.Default.ItemsBridgePayload)!.Weapons);
|
||||
Check.False(m.Single(x => x.Id == ShieldId).ExcludedFromBuffing(), "a shield unticked is buffed again");
|
||||
m = WeaponList.MergeEdited(Saved(false, false),
|
||||
JsonSerializer.Deserialize("{\"weapons\":[" + Sw + "}," + Sh + "}]}", RynthAiJsonContext.Default.ItemsBridgePayload)!.Weapons);
|
||||
Check.True(m.All(x => x.ExcludedFromBuffing()), "noBuff absent (an older engine): both keep their saved value");
|
||||
m = WeaponList.MergeEdited(Saved(true, true),
|
||||
JsonSerializer.Deserialize("{\"weapons\":[" + Sw + "}," + Sh + ",\"noBuff\":null}]}", RynthAiJsonContext.Default.ItemsBridgePayload)!.Weapons);
|
||||
Check.False(m.Single(x => x.Id == ShieldId).ExcludedFromBuffing(), "noBuff null: unchanged");
|
||||
Check.True(m.All(x => x.NoBuff == null), "merged entries carry no wire field");
|
||||
var added = WeaponList.MergeEdited(new List<ItemRule>(), new[] { new ItemRule { Id = 9, Name = "New", Action = WeaponList.ShieldAction, NoBuff = true } });
|
||||
Check.True(added.Single().ExcludedFromBuffing() && added.Single().NoBuff == null, "a new shield entry takes noBuff, and drops the wire field");
|
||||
|
||||
// Saved profiles: the field is never written; old profiles load with nothing marked.
|
||||
var settings = new LegacyUiSettings { ItemRules = m };
|
||||
string profile = JsonSerializer.Serialize(settings, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.False(profile.Contains("noBuff", StringComparison.OrdinalIgnoreCase), "a saved profile has no noBuff");
|
||||
var old = JsonSerializer.Deserialize("{\"ItemRules\":[{\"Id\":1,\"Name\":\"Sword\",\"Action\":\"Weapon\"},{\"Id\":3,\"Name\":\"Shield\",\"Action\":\"Shield\",\"KeepBuffed\":true}]}",
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.ItemRules.Count == 2 && old.ItemRules.All(x => !x.ExcludedFromBuffing()), "old profiles load with nothing marked");
|
||||
var round = JsonSerializer.Deserialize(JsonSerializer.Serialize(new LegacyUiSettings { ItemRules = { new ItemRule { Id = 3, Name = "Shield", Action = WeaponList.ShieldAction, KeepBuffed = false } } },
|
||||
RynthAiJsonContext.Default.LegacyUiSettings), RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(round != null && round.ItemRules.Single().ExcludedFromBuffing(), "No buff is saved and loaded");
|
||||
}
|
||||
|
||||
private static void Setting()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().BuffShield, "a new profile: on");
|
||||
|
|
|
|||
408
Tools/RynthCore.RynthAiHostTests/Tests/ShieldFacingTests.cs
Normal file
408
Tools/RynthCore.RynthAiHostTests/Tests/ShieldFacingTests.cs
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.CreatureData;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Damage taken by shield and facing (2026-11-08): does a shield actually cut a boss's hits? ACE
|
||||
// counts a shield only in a combat stance and only when the attacker is within 90 degrees of the
|
||||
// defender's facing (Creature_Combat.GetShieldMod, effectiveAngle 180). Each monster hit line is
|
||||
// learned split by both, saved as TS rows in monster_damage.txt, and sent with the Damage panel row.
|
||||
internal static class ShieldFacingTests
|
||||
{
|
||||
private const uint Player = 0x50000C01;
|
||||
private const uint Boss = 0x80001001, BossTwin = 0x80001002;
|
||||
private const uint BossWcid = 70001;
|
||||
private const uint Sword = 0x80000401, Shield = 0x80000404, Dagger = 0x80000402;
|
||||
private const int MeleeSlot = 0x00100000, ShieldSlot = 0x00200000;
|
||||
private const string BossName = "Hive Boss";
|
||||
private static readonly BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("shield facing: in front within 90 degrees either side, behind past it, at every heading", FacingMath);
|
||||
r.Add("shield facing: unknown when nothing can be measured (on top, no frame, too far, NaN)", FacingUnknown);
|
||||
r.Add("shield facing: the compass heading comes from the pose quaternion (not GetPlayerHeading)", HeadingFromQuaternion);
|
||||
r.Add("shield facing: a monster's hit line is split by shield and where it stood", HitLinesSplit);
|
||||
r.Add("shield facing: peace, a dual-wield off hand, an unknown off-hand item, two of the name that disagree", HitLinesEdgeCases);
|
||||
r.Add("shield facing: TS rows save and load (tier rows too), old files load, unknown kinds are skipped", SaveLoadRoundTrip);
|
||||
r.Add("shield facing: the [Taken] summary is one line per monster, not one per hit", SummaryLine);
|
||||
r.Add("shield facing: the Damage panel row's mstats carries the split, even with no session numbers", DamageRowJson);
|
||||
}
|
||||
|
||||
// ── The math ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The point <paramref name="dist"/> m away at compass bearing <paramref name="bearing"/> (0 = North, clockwise).</summary>
|
||||
private static (double X, double Y) At(double bearing, double dist)
|
||||
{
|
||||
double r = bearing * Math.PI / 180.0;
|
||||
return (Math.Sin(r) * dist, Math.Cos(r) * dist);
|
||||
}
|
||||
|
||||
private static HitFacing F(double heading, double relBearing, double dist = 5)
|
||||
{
|
||||
var (x, y) = At(heading + relBearing, dist);
|
||||
return ShieldFacing.Classify(heading, 0, 0, x, y);
|
||||
}
|
||||
|
||||
private static void FacingMath()
|
||||
{
|
||||
foreach (double h in new[] { 0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 359.0, 1.0 })
|
||||
{
|
||||
Check.Eq(F(h, 0), HitFacing.Front, $"heading {h}: straight ahead is in front");
|
||||
Check.Eq(F(h, 180), HitFacing.Behind, $"heading {h}: straight behind");
|
||||
Check.Eq(F(h, 45), HitFacing.Front, $"heading {h}: 45 right is in front");
|
||||
Check.Eq(F(h, -45), HitFacing.Front, $"heading {h}: 45 left is in front");
|
||||
Check.Eq(F(h, 89), HitFacing.Front, $"heading {h}: 89 right is in front");
|
||||
Check.Eq(F(h, -89), HitFacing.Front, $"heading {h}: 89 left is in front");
|
||||
Check.Eq(F(h, 91), HitFacing.Behind, $"heading {h}: 91 right is behind");
|
||||
Check.Eq(F(h, -91), HitFacing.Behind, $"heading {h}: 91 left is behind");
|
||||
Check.Eq(F(h, 135), HitFacing.Behind, $"heading {h}: back right");
|
||||
Check.Eq(F(h, -135), HitFacing.Behind, $"heading {h}: back left");
|
||||
}
|
||||
// Exactly at the side: ACE's test is |angle| > 90 for no shield, so 90 still counts.
|
||||
Check.Eq(ShieldFacing.Classify(0, 0, 0, 5, 0), HitFacing.Front, "facing north, the attacker due east (90): in front");
|
||||
Check.Eq(ShieldFacing.Classify(0, 0, 0, -5, 0), HitFacing.Front, "due west (-90): in front");
|
||||
Check.Eq(ShieldFacing.Classify(90, 0, 0, 0, -5), HitFacing.Front, "facing east, due south: in front (side)");
|
||||
Check.Eq(ShieldFacing.Classify(90, 0, 0, -5, 0.01), HitFacing.Behind, "facing east, due west: behind");
|
||||
// The compass basis: facing north, a monster to the north-east is in front, to the south-west behind.
|
||||
Check.Eq(ShieldFacing.Classify(0, 10, 10, 13, 13), HitFacing.Front, "north-east of us, facing north");
|
||||
Check.Eq(ShieldFacing.Classify(0, 10, 10, 7, 7), HitFacing.Behind, "south-west of us, facing north");
|
||||
Check.Eq(ShieldFacing.Classify(270, 10, 10, 5, 10), HitFacing.Front, "facing west, a monster west");
|
||||
Check.Eq(ShieldFacing.Classify(270, 10, 10, 15, 10), HitFacing.Behind, "facing west, a monster east");
|
||||
Check.Eq(Math.Round(ShieldFacing.AngleTo(350, 1, 10), 0), 16.0, "angle wraps past north (350 -> 5.7)");
|
||||
|
||||
// Landblock-local positions: across an outdoor landblock edge they are one frame.
|
||||
Check.Eq(ShieldFacing.Classify(90, 0xA9B40001, 191f, 50f, 0xAAB40001, 1f, 50f), HitFacing.Front,
|
||||
"outdoors, the attacker 2 m east in the next landblock, facing east");
|
||||
Check.Eq(ShieldFacing.Classify(270, 0xA9B40001, 191f, 50f, 0xAAB40001, 1f, 50f), HitFacing.Behind,
|
||||
"the same, facing west");
|
||||
Check.Eq(ShieldFacing.Classify(0, 0x01D90105, 10f, 10f, 0x01D9010A, 10f, 20f), HitFacing.Front,
|
||||
"in a dungeon, two cells of one landblock share its frame");
|
||||
|
||||
// Several of the name: they must all agree.
|
||||
Check.Eq(ShieldFacing.Agree(new[] { HitFacing.Front, HitFacing.Front }), HitFacing.Front, "all in front: front");
|
||||
Check.Eq(ShieldFacing.Agree(new[] { HitFacing.Front, HitFacing.Behind }), HitFacing.Unknown, "one each side: unknown");
|
||||
Check.Eq(ShieldFacing.Agree(new[] { HitFacing.Behind, HitFacing.Unknown }), HitFacing.Unknown, "one not measurable: unknown");
|
||||
Check.Eq(ShieldFacing.Agree(Array.Empty<HitFacing>()), HitFacing.Unknown, "none: unknown");
|
||||
}
|
||||
|
||||
private static void FacingUnknown()
|
||||
{
|
||||
Check.Eq(ShieldFacing.Classify(0, 10, 10, 10, 10), HitFacing.Unknown, "on top of us: no direction");
|
||||
Check.Eq(ShieldFacing.Classify(double.NaN, 0, 0, 5, 5), HitFacing.Unknown, "no heading");
|
||||
Check.Eq(ShieldFacing.Classify(0, 0, 0, double.NaN, 5), HitFacing.Unknown, "a garbage position");
|
||||
Check.Eq(ShieldFacing.Classify(0, 0x01D90105, 10f, 10f, 0x01DA0105, 10f, 20f), HitFacing.Unknown,
|
||||
"two dungeon landblocks: no shared frame");
|
||||
Check.Eq(ShieldFacing.Classify(0, 0xA9B40001, 10f, 10f, 0xA9B40001, 10f, 100f), HitFacing.Unknown,
|
||||
"90 m away: too far to be the one that hit");
|
||||
Check.Eq(ShieldFacing.Classify(0, 0xA9B40001, 10f, 10f, 0xA9B40001, 10f, 80f), HitFacing.Front, "70 m: measured");
|
||||
Check.True(ShieldFacing.TryParse("behind", out var b) && b == HitFacing.Behind, "parse behind");
|
||||
Check.False(ShieldFacing.TryParse("sideways", out _), "an unknown word does not parse");
|
||||
}
|
||||
|
||||
private static void HeadingFromQuaternion()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.PlayerPose = (0xA9B40001, 10f, 10f, 0f);
|
||||
var host = FakeHost.Create(Player);
|
||||
foreach (double h in new[] { 0.0, 13.9, 90.0, 180.0, 270.0, 300.0 })
|
||||
{
|
||||
FakeHost.HeadingDeg = h;
|
||||
Check.True(PlayerCompass.TryGet(host, out float c), "pose read");
|
||||
Check.Eq(Math.Round(c, 1), Math.Round(h, 1), $"compass {h} from the quaternion");
|
||||
double half = -h * Math.PI / 360.0;
|
||||
Check.Eq(Math.Round(ShieldFacing.CompassFromQuaternion(Math.Cos(half), Math.Sin(half)), 1), Math.Round(h % 360.0, 1),
|
||||
$"ShieldFacing reads {h} the same way");
|
||||
}
|
||||
}
|
||||
|
||||
// ── The rig: a boss hits us ──────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new();
|
||||
public readonly CombatManager C;
|
||||
public readonly MonsterDamageStore Store = new();
|
||||
|
||||
public Rig(bool shieldOn, double heading, (float X, float Y) boss, (float X, float Y)? twin = null, bool offhandUnknown = false,
|
||||
bool dagger = false, int mode = CombatMode.Melee)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.EquippedCalls = true; // the engine's EquipmentTracker (v87)
|
||||
FakeHost.WeaponCalls = true; // GetCurrentCombatMode
|
||||
FakeHost.CombatModeValue = mode;
|
||||
FakeHost.PlayerPose = (0xA9B40001, 50f, 50f, 0f);
|
||||
FakeHost.HeadingDeg = heading;
|
||||
Item(Sword, "Long Sword", 0x1, MeleeSlot, 1);
|
||||
Item(Shield, "Kite Shield", 0x2, ShieldSlot, 4);
|
||||
Item(Dagger, "Dagger", 0x1, MeleeSlot, 1);
|
||||
FakeHost.Equipped[Sword] = (uint)MeleeSlot;
|
||||
if (shieldOn) FakeHost.Equipped[offhandUnknown ? 0x80000999u : Shield] = (uint)ShieldSlot;
|
||||
if (dagger) FakeHost.Equipped[Dagger] = (uint)ShieldSlot;
|
||||
Monster(Boss, boss);
|
||||
var ids = new List<uint> { Sword, Shield, Dagger, Boss };
|
||||
var health = new Dictionary<uint, float> { [Boss] = 1f };
|
||||
if (twin is { } t) { Monster(BossTwin, t); ids.Add(BossTwin); health[BossTwin] = 1f; }
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, ids, health);
|
||||
C = new CombatManager(host, S, cache);
|
||||
C.SetPlayerId(Player);
|
||||
string folder = Path.Combine(Program.TempRoot, "shield-facing", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(folder);
|
||||
Store.SetCharacter(folder);
|
||||
C.SetDamageStores(null, Store);
|
||||
C.OffhandReadMs = 0;
|
||||
EquippedState.Invalidate();
|
||||
var seen = (Dictionary<string, uint>)typeof(CombatManager).GetField("_seenMonsterNameToWcid", Any)!.GetValue(C)!;
|
||||
seen[BossName] = BossWcid; // what the scan learns when it sees the boss
|
||||
}
|
||||
|
||||
private static void Item(uint id, string name, uint itemType, int validSlots, int combatUse)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = itemType;
|
||||
FakeHost.Ints[(id, 9)] = validSlots;
|
||||
FakeHost.Ints[(id, 51)] = combatUse;
|
||||
}
|
||||
|
||||
private static void Monster(uint id, (float X, float Y) at)
|
||||
{
|
||||
FakeHost.Names[id] = BossName;
|
||||
FakeHost.ItemTypes[id] = 0x10;
|
||||
FakeHost.Wcids[id] = BossWcid;
|
||||
FakeHost.Positions[id] = (0xA9B40001, at.X, at.Y, 0f);
|
||||
}
|
||||
|
||||
public void Hit(int amount) => C.HandleChatForDamage($"{BossName} slashes your upper leg for {amount} points of slashing damage!");
|
||||
|
||||
public Dictionary<(bool, HitFacing), MonsterDamageStore.ShieldTakenRow> Split()
|
||||
=> Store.GetShieldTaken(BossWcid, 0).ToDictionary(r => (r.Shield, r.Facing));
|
||||
}
|
||||
|
||||
private static void HitLinesSplit()
|
||||
{
|
||||
// Facing north, shield up, the boss 2 m north: in front, the shield counts.
|
||||
var rig = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f));
|
||||
rig.Hit(10);
|
||||
rig.Hit(14);
|
||||
var s = rig.Split();
|
||||
Check.True(s.TryGetValue((true, HitFacing.Front), out var sf), "shield + front recorded");
|
||||
Check.Eq(sf.Hits, 2, "two hits");
|
||||
Check.Eq(sf.Avg, 12.0, "their mean");
|
||||
Check.Eq(sf.Max, 14.0, "the biggest");
|
||||
Check.Eq(s.Count, 1, "nothing else");
|
||||
var t = rig.Store.GetDetail(BossWcid, 0).Taken;
|
||||
Check.True(t.Any(x => x.Element == "Slash" && x.Hits == 2), "the T row (per element) still learns the hits");
|
||||
|
||||
// It walks behind us.
|
||||
FakeHost.Positions[Boss] = (0xA9B40001, 50f, 48f, 0f);
|
||||
rig.Hit(60);
|
||||
Check.Eq(rig.Split()[(true, HitFacing.Behind)].Hits, 1, "shield + behind");
|
||||
|
||||
// We turn round to face it: in front again.
|
||||
FakeHost.HeadingDeg = 180;
|
||||
rig.Hit(20);
|
||||
Check.Eq(rig.Split()[(true, HitFacing.Front)].Hits, 3, "turned to face it: in front");
|
||||
|
||||
// No shield in the off hand.
|
||||
var bare = new Rig(shieldOn: false, heading: 90, boss: (53f, 50f));
|
||||
bare.Hit(54);
|
||||
bare.Hit(54);
|
||||
var b = bare.Split();
|
||||
Check.Eq(b[(false, HitFacing.Front)].Hits, 2, "no shield, in front");
|
||||
Check.False(b.ContainsKey((true, HitFacing.Front)), "and no shield cell");
|
||||
FakeHost.Positions[Boss] = (0xA9B40001, 47f, 50f, 0f);
|
||||
bare.Hit(70);
|
||||
Check.Eq(bare.Split()[(false, HitFacing.Behind)].Max, 70.0, "no shield, behind");
|
||||
|
||||
// A line for a monster the bot never saw (no wcid) learns nothing.
|
||||
bare.C.HandleChatForDamage("Some Stranger slashes your upper leg for 9 points of slashing damage!");
|
||||
Check.Eq(bare.Split().Values.Sum(x => x.Hits), 3, "an unknown monster's line is not counted");
|
||||
}
|
||||
|
||||
private static void HitLinesEdgeCases()
|
||||
{
|
||||
var peace = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), mode: CombatMode.NonCombat);
|
||||
peace.Hit(30);
|
||||
Check.True(peace.Split().ContainsKey((false, HitFacing.Front)), "in peace ACE ignores the shield: shield 0");
|
||||
|
||||
var dw = new Rig(shieldOn: false, heading: 0, boss: (50f, 52f), dagger: true);
|
||||
dw.Hit(30);
|
||||
Check.True(dw.Split().ContainsKey((false, HitFacing.Front)), "a dagger in the off hand is no shield");
|
||||
|
||||
var unknown = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), offhandUnknown: true);
|
||||
unknown.Hit(30);
|
||||
Check.Eq(unknown.Split().Count, 0, "an off-hand item the cache doesn't know: not split (no guess)");
|
||||
Check.True(unknown.Store.GetDetail(BossWcid, 0).Taken.Any(x => x.Hits == 1), "the T row still learns it");
|
||||
|
||||
var twins = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), twin: (50f, 47f));
|
||||
twins.Hit(30);
|
||||
Check.True(twins.Split().ContainsKey((true, HitFacing.Unknown)), "two of the name, one each side: unknown");
|
||||
|
||||
var agree = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), twin: (52f, 53f));
|
||||
agree.Hit(30);
|
||||
Check.True(agree.Split().ContainsKey((true, HitFacing.Front)), "two of the name, both in front: front");
|
||||
|
||||
var far = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), twin: (50f, 0f));
|
||||
FakeHost.Positions[BossTwin] = (0xA9B40001, 50f, -60f, 0f); // 110 m behind: not the one that hit
|
||||
far.Hit(30);
|
||||
Check.True(far.Split().ContainsKey((true, HitFacing.Front)), "one of the name 110 m away is left out");
|
||||
|
||||
var dead = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f), twin: (50f, 47f));
|
||||
var cache = (WorldObjectCache)typeof(CombatManager).GetField("_worldFilter", Any)!.GetValue(dead.C)!;
|
||||
cache.OnUpdateHealth(BossTwin, 0f);
|
||||
dead.Hit(30);
|
||||
Check.True(dead.Split().ContainsKey((true, HitFacing.Front)), "a dead one of the name is left out");
|
||||
|
||||
var noPose = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f));
|
||||
FakeHost.HasPose = false;
|
||||
noPose.Hit(30);
|
||||
Check.True(noPose.Split().ContainsKey((true, HitFacing.Unknown)), "no pose: unknown");
|
||||
}
|
||||
|
||||
// ── Save and load ────────────────────────────────────────────────────────
|
||||
|
||||
private static string Folder(string name)
|
||||
{
|
||||
string folder = Path.Combine(Program.TempRoot, "shield-facing-file", name);
|
||||
if (Directory.Exists(folder)) Directory.Delete(folder, true);
|
||||
Directory.CreateDirectory(folder);
|
||||
return folder;
|
||||
}
|
||||
|
||||
private static void SaveLoadRoundTrip()
|
||||
{
|
||||
string folder = Folder("roundtrip");
|
||||
var s = new MonsterDamageStore();
|
||||
s.SetCharacter(folder);
|
||||
s.RecordTaken(BossWcid, BossName, "Slash", 40);
|
||||
s.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Front, 10);
|
||||
s.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Front, 13);
|
||||
s.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Behind, 274);
|
||||
s.RecordTakenSplit(BossWcid, BossName, false, HitFacing.Unknown, 54);
|
||||
s.Difficulty = 3;
|
||||
s.RecordTakenSplit(BossWcid, BossName, false, HitFacing.Front, 90);
|
||||
s.Difficulty = 0;
|
||||
s.SaveIfDirty();
|
||||
|
||||
string file = Path.Combine(folder, "monster_damage.txt");
|
||||
string[] lines = File.ReadAllLines(file);
|
||||
Check.True(lines.Any(l => l.StartsWith("# TS|wcid|name|shield|facing|hitsTaken|avgDamageTaken|maxDamageTaken")), "the header names the TS row");
|
||||
Check.True(lines.Any(l => l.StartsWith("# ATS|tier|wcid|name|shield|facing")), "and the tier row");
|
||||
Check.True(lines.Contains($"TS|{BossWcid}|{BossName}|1|front|2|11.5|13"), "shield front: 2 hits, mean 11.5, max 13");
|
||||
Check.True(lines.Contains($"TS|{BossWcid}|{BossName}|1|behind|1|274|274"), "shield behind");
|
||||
Check.True(lines.Contains($"TS|{BossWcid}|{BossName}|0|unknown|1|54|54"), "no shield, facing unknown");
|
||||
Check.True(lines.Contains($"ATS|3|{BossWcid}|{BossName}|0|front|1|90|90"), "a difficulty tier's row");
|
||||
int ts = Array.FindIndex(lines, l => l.StartsWith("TS|"));
|
||||
Check.True(ts > Array.FindIndex(lines, l => l.StartsWith("T|")), "TS rows follow the T rows");
|
||||
|
||||
var again = new MonsterDamageStore();
|
||||
again.SetCharacter(folder);
|
||||
var rows = again.GetShieldTaken(BossWcid, 0);
|
||||
Check.Eq(string.Join(";", rows.Select(r => $"{(r.Shield ? 1 : 0)}{ShieldFacing.Word(r.Facing)}{r.Hits}/{r.Avg}/{r.Max}")),
|
||||
"1front2/11.5/13;1behind1/274/274;0unknown1/54/54", "loaded back the same, shield first, front before behind");
|
||||
Check.Eq(again.GetShieldTaken(BossWcid, 3).Single().Avg, 90.0, "the tier's row loaded");
|
||||
Check.Eq(again.GetDetail(BossWcid, 0).Taken.Single().Hits, 1, "the T row loaded beside them");
|
||||
again.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Front, 12.5);
|
||||
Check.Eq(Math.Round(again.GetShieldTaken(BossWcid, 0)[0].Avg, 2), 11.83, "a loaded mean goes on being a mean ((10+13+12.5)/3)");
|
||||
|
||||
// An older file (no TS rows), with unknown row kinds a newer RynthAi might write: they load, the
|
||||
// unknown kinds are skipped, and nothing breaks.
|
||||
string old = Folder("old");
|
||||
File.WriteAllLines(Path.Combine(old, "monster_damage.txt"), new[]
|
||||
{
|
||||
"# RynthAi per-character monster damage learning (auto-generated).",
|
||||
$"H|{BossWcid}|{BossName}|5000|2",
|
||||
$"T|{BossWcid}|{BossName}|Slash|7|55|274",
|
||||
$"TX|{BossWcid}|{BossName}|future|1|2|3|4",
|
||||
$"TS|{BossWcid}|{BossName}|2|front|1|2|3",
|
||||
$"TS|{BossWcid}|{BossName}|1|sideways|1|2|3",
|
||||
$"TS|{BossWcid}|{BossName}|1|front|zero|2|3",
|
||||
$"TS|{BossWcid}|{BossName}|1",
|
||||
$"AZZ|2|{BossWcid}|{BossName}|1|2",
|
||||
$"D|{BossWcid}|{BossName}|0|Fire|7|120|20|3.5|4|200|4|100|16",
|
||||
});
|
||||
var o = new MonsterDamageStore();
|
||||
o.SetCharacter(old);
|
||||
Check.Eq(o.GetLearnedHp(BossWcid), 5000.0, "the H row loads");
|
||||
Check.Eq(o.GetDetail(BossWcid, 0).Taken.Single().Max, 274.0, "the T row loads");
|
||||
Check.Eq(o.Snapshot().Count, 1, "the D row loads");
|
||||
Check.Eq(o.GetShieldTaken(BossWcid, 0).Count, 0, "unknown kinds and bad TS rows are skipped");
|
||||
|
||||
// What an older RynthAi does with a TS row: its loader compares the kind exactly (H, M, W, O,
|
||||
// P, U, PK, T, D, DEF, and A* tier rows), so "TS" matches none and is skipped; this loader
|
||||
// does the same with a kind it doesn't know (TX above).
|
||||
Check.True(lines.All(l => !l.StartsWith("TS") || l.StartsWith("TS|")), "TS is its own kind, never a T row");
|
||||
}
|
||||
|
||||
private static void SummaryLine()
|
||||
{
|
||||
var rig = new Rig(shieldOn: true, heading: 0, boss: (50f, 52f));
|
||||
for (int i = 0; i < 5; i++) rig.Hit(10 + i);
|
||||
FakeHost.Positions[Boss] = (0xA9B40001, 50f, 48f, 0f);
|
||||
rig.Hit(274);
|
||||
Check.False(FakeHost.Logs.Any(l => l.StartsWith("[Taken]")), "no line per hit");
|
||||
List<string> lines = rig.C.TakenSummaryLines(RynthClock.Now);
|
||||
Check.Eq(lines.Count, 1, "one line for the one monster");
|
||||
string line = lines[0];
|
||||
Check.True(line.StartsWith($"[Taken] {BossName}: 6 hits in "), "who and how many: " + line);
|
||||
Check.True(line.Contains("shield front 5 avg 12 max 14"), "the front cell: " + line);
|
||||
Check.True(line.Contains("shield behind 1 avg 274 max 274"), "the behind cell: " + line);
|
||||
Check.Eq(rig.C.TakenSummaryLines(RynthClock.Now).Count, 0, "the tally starts over");
|
||||
}
|
||||
|
||||
// ── The Damage panel row ─────────────────────────────────────────────────
|
||||
|
||||
private static void DamageRowJson()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.PlayerPose = (0xA9B40001, 10f, 10f, 0f);
|
||||
var host = FakeHost.Create(Player);
|
||||
var p = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(p, new object[] { FakeHost.LastApi });
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(p, v);
|
||||
Set("_objectCache", cache);
|
||||
Set("_playerId", Player);
|
||||
var store = new MonsterDamageStore();
|
||||
store.SetCharacter(Folder("row"));
|
||||
Set("_damageStore", store);
|
||||
Set("_creatureStore", new CreatureProfileStore());
|
||||
|
||||
store.RecordKill(0, BossWcid, BossName, "Fire", 7, 3, 5000);
|
||||
for (int i = 0; i < 19; i++) store.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Front, 11);
|
||||
store.RecordTakenSplit(BossWcid, BossName, true, HitFacing.Behind, 274);
|
||||
store.RecordTakenSplit(BossWcid, BossName, false, HitFacing.Front, 54);
|
||||
store.RecordTakenSplit(BossWcid, BossName, false, HitFacing.Front, 55);
|
||||
|
||||
using var doc = JsonDocument.Parse(p.BuildMonsterDamageJson());
|
||||
JsonElement row = doc.RootElement.EnumerateArray().Single(e => e.GetProperty("name").GetString() == BossName);
|
||||
Check.True(row.TryGetProperty("mstats", out JsonElement m), "mstats is sent with only learned numbers (none since login)");
|
||||
Check.Eq(m.GetProperty("hsf").GetInt32(), 19, "shield front hits");
|
||||
Check.Eq(m.GetProperty("dsf").GetInt64(), 209L, "shield front total damage (19 x 11)");
|
||||
Check.Eq(m.GetProperty("msf").GetInt64(), 11L, "shield front biggest");
|
||||
Check.Eq(m.GetProperty("hsb").GetInt32(), 1, "shield behind hits");
|
||||
Check.Eq(m.GetProperty("msb").GetInt64(), 274L, "shield behind biggest");
|
||||
Check.Eq(m.GetProperty("hnf").GetInt32(), 2, "no shield front hits");
|
||||
Check.Eq(m.GetProperty("dnf").GetInt64(), 109L, "no shield front total");
|
||||
Check.False(m.TryGetProperty("hsu", out _), "an empty cell isn't sent");
|
||||
Check.False(m.TryGetProperty("sw", out _), "no session numbers: none sent");
|
||||
|
||||
// With session numbers too: both, one object.
|
||||
string both = RynthAiPlugin.MonsterStatsJson(null, p.ShieldTakenFor(new[] { BossWcid }, 0));
|
||||
Check.True(both.StartsWith("\"mstats\":{\"hsf\":19,\"dsf\":209,\"msf\":11"), "the split alone: " + both);
|
||||
Check.Eq(p.MonsterStatsJsonFor("Nobody", new uint[] { 12345 }, 0), "", "a monster with nothing: no mstats");
|
||||
}
|
||||
}
|
||||
|
|
@ -375,31 +375,55 @@ internal static class StuckCastTests
|
|||
|
||||
private static void ProbeWhenNothingOpen()
|
||||
{
|
||||
// A start that is no heal: a waiting heal's probe is capped at ActionPacer.HealGraceMs (below).
|
||||
bool Start(RynthCoreHost h) => MayAs(h, "Buff", HealNeed.None);
|
||||
var host = Setup();
|
||||
try
|
||||
{
|
||||
Check.True(May(host), "free");
|
||||
Check.True(Start(host), "free");
|
||||
Cast(host, "Heart Rend");
|
||||
_t += 100;
|
||||
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused: the server is busy with something of no UseDone (a pickup)
|
||||
Check.False(May(host), "held right after the 0x1D");
|
||||
Check.False(Start(host), "held right after the 0x1D");
|
||||
_t += ActionPacer.BusyProbeMs - 1;
|
||||
Check.False(May(host), "held until BusyProbeMs");
|
||||
Check.False(Start(host), "held until BusyProbeMs");
|
||||
_t += 1;
|
||||
Check.True(May(host), "one probe at BusyProbeMs");
|
||||
Check.False(May(host), "only one");
|
||||
Check.True(Start(host), "one probe at BusyProbeMs");
|
||||
Check.False(Start(host), "only one");
|
||||
Cast(host, "Heart Rend");
|
||||
_t += 100;
|
||||
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again
|
||||
_t += ActionPacer.BusyProbeMs * 2 - 101;
|
||||
Check.False(May(host), "the next probe waits twice as long");
|
||||
Check.False(Start(host), "the next probe waits twice as long");
|
||||
_t += 1;
|
||||
Check.True(May(host), "second probe at 2 x BusyProbeMs");
|
||||
Check.True(Start(host), "second probe at 2 x BusyProbeMs");
|
||||
Check.Eq(FakeHost.TapJumps + FakeHost.CombatModeRequests.Count, 0, "no breaker: no cast of ours was left open");
|
||||
Cast(host, "Heart Rend");
|
||||
_t += 900;
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(May(host), "a UseDone(0) clears it");
|
||||
Check.True(Start(host), "a UseDone(0) clears it");
|
||||
}
|
||||
finally { Done(); }
|
||||
|
||||
// The heal grace: a plain heal's probe comes at least every HealGraceMs, where the doubling would make it 3 s.
|
||||
var heal = Setup();
|
||||
try
|
||||
{
|
||||
Check.True(May(heal), "free");
|
||||
Cast(heal, "Heart Rend");
|
||||
_t += 100;
|
||||
FakeHost.UseDone(ActionPacer.TooBusyErr);
|
||||
Check.False(May(heal), "held right after the 0x1D");
|
||||
_t += ActionPacer.BusyProbeMs;
|
||||
Check.True(May(heal), "the heal's first probe at BusyProbeMs");
|
||||
Cast(heal, "Heart Rend");
|
||||
_t += 100;
|
||||
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused again
|
||||
Check.False(May(heal), "held right after the second 0x1D");
|
||||
_t += ActionPacer.HealGraceMs - 101;
|
||||
Check.False(May(heal), "1 ms under the heal grace: held");
|
||||
_t += 1;
|
||||
Check.True(May(heal), "the heal's second probe at HealGraceMs, not 2 x BusyProbeMs");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,8 +12,9 @@ namespace RynthCore.RynthAiHostTests.Tests;
|
|||
|
||||
// Combat target selection (2026-10-10): the Targeting setting (lowest health, closest, farthest,
|
||||
// least turning) and Target Lock. Combat used to switch targets mid-fight on a blended score; now
|
||||
// a locked target is kept until it dies or goes, leaves Monster Range, or a higher-priority
|
||||
// monster is in range, and with the lock off a switch needs a clear margin under the rule.
|
||||
// a locked target is kept until it dies or goes or leaves Monster Range (a higher priority too,
|
||||
// since 2026-11-07), and with the lock off a higher priority in range takes over at once and any
|
||||
// other switch needs a clear margin under the rule.
|
||||
internal static class TargetingTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
|
|
@ -22,14 +23,48 @@ internal static class TargetingTests
|
|||
|
||||
private const int LowestHealth = 0, Closest = 1, Farthest = 2, LeastTurning = 3;
|
||||
|
||||
// Melee reaches through walls (2026-11-06): within 4 yd the raycast doesn't hide a monster from melee.
|
||||
private static void MeleeThroughWalls()
|
||||
{
|
||||
var near = new ScanPick(20);
|
||||
near.Place(A, "Mob A", north: 3);
|
||||
near.Blocked.Add(A);
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Melee;
|
||||
Check.Eq(near.Tick(), A, "melee, 3 yd, a wall between: still the target");
|
||||
|
||||
var far = new ScanPick(20);
|
||||
far.Place(A, "Mob A", north: 6);
|
||||
far.Blocked.Add(A);
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Melee;
|
||||
Check.Eq(far.Tick(), 0u, "melee, 6 yd, a wall between: the raycast still counts");
|
||||
|
||||
var magic = new ScanPick(20);
|
||||
magic.Place(A, "Mob A", north: 3);
|
||||
magic.Blocked.Add(A);
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
Check.Eq(magic.Tick(), 0u, "magic, 3 yd, a wall between: spells don't go through");
|
||||
|
||||
var missile = new ScanPick(20);
|
||||
missile.Place(A, "Mob A", north: 3);
|
||||
missile.Blocked.Add(A);
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Missile;
|
||||
Check.Eq(missile.Tick(), 0u, "missile, 3 yd, a wall between: nor do arrows");
|
||||
}
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("targeting: melee within 4 yd ignores the raycast; beyond it, or with magic or missile, it counts", MeleeThroughWalls);
|
||||
r.Add("targeting: each scheme picks its monster", SchemesPick);
|
||||
r.Add("targeting: unknown health counts as full; ties go to the closest, then the lower id", UnknownHealthAndTies);
|
||||
r.Add("targeting: Target Lock keeps the target when a better one of its tier appears", LockKeeps);
|
||||
r.Add("targeting: Target Lock lets go when the target goes (after the scan grace)", LockReleasesWhenGone);
|
||||
r.Add("targeting: Target Lock lets go when the target leaves Monster Range", LockReleasesOutOfRange);
|
||||
r.Add("targeting: a higher-priority monster in range takes over, lock or not", HigherPriorityWins);
|
||||
r.Add("targeting: lock off, a higher-priority monster in range takes over", HigherPriorityWins);
|
||||
r.Add("targeting: Target Lock holds over a higher priority until the target dies or leaves Monster Range", LockHoldsOverPriority);
|
||||
r.Add("targeting: lock off switches only past each scheme's margin", LockOffMargins);
|
||||
r.Add("targeting: lock off never switches with an attack at the target in flight", NoSwitchInFlight);
|
||||
r.Add("targeting: settings default to lowest health with the lock on", Defaults);
|
||||
|
|
@ -39,6 +74,132 @@ internal static class TargetingTests
|
|||
r.Add("targeting: lock off keeps a target that blinks out of the scan (no switch on stale values)", LockOffNoSwitchOnStale);
|
||||
r.Add("targeting: lock off holds right after a cast goes out, before it is judged", LockOffHoldsJustSentCast);
|
||||
r.Add("targeting: a higher priority just past Monster Range is logged once while fighting, and /ra why names it", BeyondRangeWhileEngaged);
|
||||
r.Add("targeting: lowest health ranks unread monsters by the engine plates' readings", PlatesRankUnread);
|
||||
r.Add("targeting: plate readings older than 10 s, or 0, are ignored", PlatesStaleIgnored);
|
||||
r.Add("targeting: a plate reading beats an estimate when lower, and an older own server value when clearly fresher", PlatesVersusOwn);
|
||||
r.Add("targeting: plate readings rank only; health, fight and kill tracking are untouched", PlatesRankOnly);
|
||||
r.Add("targeting: without the engine call (or on an older engine) lowest health is as before", PlatesNoCapability);
|
||||
}
|
||||
|
||||
// ── The engine plates' health (API v93 GetMonsterHealth, 2026-11-07) ─────
|
||||
|
||||
private static void PlatesRankUnread()
|
||||
{
|
||||
// The server streams health only for the queried target: RynthAi knows none of these three.
|
||||
var plates = new Dictionary<uint, (float, uint)> { [A] = (0.9f, 1000), [B] = (0.25f, 3000), [C] = (0.6f, 500) };
|
||||
var t = new Rig(LowestHealth, true, plates: plates);
|
||||
Check.True(t.Host.HasMonsterHealth, "the fake engine has the call");
|
||||
Check.Eq(t.Pick((A, 2, 0), (B, 5, 0), (C, 3, 0)), B, "B, 25% on the plates, is the most hurt (the closest is A)");
|
||||
Check.True(FakeHost.PlateHealthQueries > 0, "the plates were asked");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] lock 0x80000402") && l.Contains("lowest health: health 25% (the plates' reading)")),
|
||||
"the lock line gives the plates' number and says where it came from");
|
||||
|
||||
// A known own value still competes: A at 20% (the streamed target) beats B's 25% on the plates.
|
||||
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [A] = 0.2f }, plates: new() { [B] = (0.25f, 3000) });
|
||||
Check.Eq(t.Pick((A, 4, 0), (B, 2, 0)), A, "own 20% beats the plates' 25%");
|
||||
|
||||
// Lock off: a plate reading clearly lower takes over, by the scheme's margin.
|
||||
t = new Rig(LowestHealth, false, new Dictionary<uint, float> { [A] = 0.5f }, plates: new() { [B] = (0.9f, 1000) });
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "lock off: A at 50%, B at 90% on the plates");
|
||||
t.Plate(B, 0.47f, 1000);
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B at 47% on the plates (3 points lower): A kept");
|
||||
t.Plate(B, 0.30f, 1000);
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "B at 30% on the plates (20 points lower): switch");
|
||||
}
|
||||
|
||||
private static void PlatesStaleIgnored()
|
||||
{
|
||||
var t = new Rig(LowestHealth, true, plates: new() { [A] = (0.9f, 1000), [B] = (0.1f, 10_500) });
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B's 10% is 10.5 s old: ignored (full), A's 90% wins");
|
||||
|
||||
t = new Rig(LowestHealth, true, plates: new() { [A] = (0.9f, 1000), [B] = (0.1f, 10_000) });
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "exactly 10 s old: still used");
|
||||
|
||||
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [B] = 0.95f }, plates: new() { [A] = (0f, 500) });
|
||||
Check.Eq(t.Pick((A, 1, 0), (B, 3, 0)), B, "a plate 0 (dead to the plates, not to RynthAi) isn't the most hurt: B at 95%");
|
||||
|
||||
t = new Rig(LowestHealth, true, plates: new() { [A] = (0.9f, uint.MaxValue) });
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "a reading of unknown age is stale: all full, the closest");
|
||||
}
|
||||
|
||||
private static void PlatesVersusOwn()
|
||||
{
|
||||
// Own estimate (our splash hit) vs the plates: the lower of the two.
|
||||
var t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [B] = 0.5f }, plates: new() { [A] = (0.4f, 2000) });
|
||||
t.Cache.ApplyDamageEstimate(unchecked((int)A), 0.3); // A estimated 70%
|
||||
Check.True(t.Cache.IsHealthEstimated(unchecked((int)A)), "A's own value is an estimate");
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "A: estimate 70%, plates 40% -> 40%, below B's 50%");
|
||||
|
||||
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [B] = 0.5f }, plates: new() { [A] = (0.8f, 2000) });
|
||||
t.Cache.ApplyDamageEstimate(unchecked((int)A), 0.7); // A estimated 30%
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "A: estimate 30%, plates 80% -> 30% (the estimate saw hits the plates didn't)");
|
||||
|
||||
// Own server value 80%, 5 s old; the plates read 30% a second ago: the plates are fresher.
|
||||
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [A] = 0.5f }, plates: new() { [B] = (0.3f, 1000) });
|
||||
t.Health(B, 0.8f);
|
||||
t.Advance(5000);
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), B, "B: own 80% (5 s old) vs plates 30% (1 s old) -> 30%");
|
||||
|
||||
// Own server value just in; the plates' is older: own stands.
|
||||
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [A] = 0.5f }, plates: new() { [B] = (0.3f, 1000) });
|
||||
t.Health(B, 0.8f);
|
||||
t.Advance(200);
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "B: own 80% (0.2 s old) stands over the plates' 30% (1 s old): A at 50%");
|
||||
|
||||
// A few ms apart is the same 0x01C0: not "fresher".
|
||||
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [A] = 0.5f }, plates: new() { [B] = (0.3f, 1000) });
|
||||
t.Health(B, 0.8f);
|
||||
t.Advance(1300);
|
||||
Check.Eq(t.Pick((A, 3, 0), (B, 2, 0)), A, "plates only 0.3 s fresher: own 80% stands");
|
||||
|
||||
// The server said dead: that stands whatever the plates say.
|
||||
// (A dead monster never reaches the pick: the scan drops it. The rank itself is checked here.)
|
||||
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [B] = 0f }, plates: new() { [B] = (0.4f, 100) });
|
||||
Check.True(t.Combat.RankingHealth(unchecked((int)B), out bool fromPlates) == 0f && !fromPlates, "own 0 (dead) isn't revived by the plates");
|
||||
}
|
||||
|
||||
private static void PlatesRankOnly()
|
||||
{
|
||||
var t = new Rig(LowestHealth, true, plates: new() { [A] = (0.9f, 1000), [B] = (0.2f, 1000) });
|
||||
Check.Eq(t.Pick((A, 2, 0), (B, 4, 0)), B, "B is picked on the plates' 20%");
|
||||
int a = unchecked((int)A), b = unchecked((int)B);
|
||||
Check.Eq(t.Cache.GetHealthRatio(b), -1f, "the cache still doesn't know B's health");
|
||||
Check.Eq(t.Cache.GetHealthRatio(a), -1f, "nor A's");
|
||||
Check.False(t.Cache.IsHealthEstimated(b), "nothing was written as an estimate");
|
||||
Check.False(t.Cache.TryGetServerHealthTime(b, out _), "nor as a server reading");
|
||||
Check.Eq(t.Combat.FightTargetHealthRatio, -1f, "the fight target's health (metas, kill checks) is RynthAi's own: unknown");
|
||||
|
||||
// The kill path is the same as without the plates: the notice drops B, the next pick is fresh.
|
||||
t.Combat.OnKillNotification("Mob B's perforated corpse falls before you!");
|
||||
Check.Eq(t.Combat.activeTargetId, 0, "the kill notice drops B");
|
||||
Check.Eq(t.Cache.GetHealthRatio(b), -1f, "and still nothing in the cache from the plates");
|
||||
t.Plate(B, 0.2f, 1000); // the plates still remember B's last reading
|
||||
Check.Eq(t.Pick((A, 2, 0)), A, "A is next");
|
||||
|
||||
// The server's own stream still drives the cache exactly as before.
|
||||
t.Health(A, 0.6f);
|
||||
Check.Eq(t.Cache.GetHealthRatio(a), 0.6f, "a real UpdateHealth lands in the cache");
|
||||
Check.Eq(t.Combat.FightTargetHealthRatio, 0.6f, "and is the fight target's health");
|
||||
}
|
||||
|
||||
private static void PlatesNoCapability()
|
||||
{
|
||||
// No call on the engine: the plates' numbers can't be read, all unknown counts as full.
|
||||
var t = new Rig(LowestHealth, true);
|
||||
FakeHost.PlateHealth[B] = (0.1f, 500); // what an engine would have said (not wired)
|
||||
Check.False(t.Host.HasMonsterHealth, "no GetMonsterHealth on this engine");
|
||||
Check.Eq(t.Pick((A, 2, 0), (B, 4, 0)), A, "all unknown: the closest, as before");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("lowest health: health unknown (as full)")), "logged as unknown, as before");
|
||||
|
||||
// The slot filled but the engine says API 92: not used, never called.
|
||||
t = new Rig(LowestHealth, true, plates: new() { [B] = (0.1f, 500) }, plateVersion: 92);
|
||||
Check.False(t.Host.HasMonsterHealth, "API 92: no HasMonsterHealth");
|
||||
Check.Eq(t.Pick((A, 2, 0), (B, 4, 0)), A, "the closest, as before");
|
||||
Check.Eq(FakeHost.PlateHealthQueries, 0, "the call was never made");
|
||||
|
||||
// With the call, but the plates know nothing: as before too.
|
||||
t = new Rig(LowestHealth, true, new Dictionary<uint, float> { [B] = 0.95f }, plates: new());
|
||||
Check.Eq(t.Pick((A, 2, 0), (B, 5, 0)), B, "a known 95% beats an unknown (full) health, as before");
|
||||
}
|
||||
|
||||
// ── Schemes ───────────────────────────────────────────────────────────────
|
||||
|
|
@ -130,9 +291,31 @@ internal static class TargetingTests
|
|||
Check.Eq(t.Pick((A, 3, 0), (B, 4.8, 0)), B, "A coming back closer doesn't take it back (B is locked now)");
|
||||
}
|
||||
|
||||
// Target Lock holds until the target dies or leaves Monster Range, a higher priority or not
|
||||
// (the owner, 2026-11-07); with the lock off a higher priority in range takes over at once.
|
||||
private static void LockHoldsOverPriority()
|
||||
{
|
||||
var t = new Rig(Closest, true, monsterRange: 10);
|
||||
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 2 });
|
||||
Check.Eq(t.Pick((A, 2, 0), (B, 3, 0)), A, "A is locked");
|
||||
Check.Eq(t.Pick((A, 2, 0), (B, 3, 0), (Boss, 9, 0)), A, "a Boss inside Monster Range: the lock keeps A");
|
||||
Check.True(FakeHost.Logs.Count(l => l.Contains("[CombatTarget] Target Lock keeps 0x80000401") && l.Contains("over 0x80000404")) == 1,
|
||||
"the hold is logged once");
|
||||
t.Pick((A, 2, 0), (Boss, 9, 0));
|
||||
Check.True(FakeHost.Logs.Count(l => l.Contains("[CombatTarget] Target Lock keeps")) == 1, "and not again");
|
||||
Check.Eq(t.Pick((A, 11, 0), (Boss, 9, 0)), Boss, "A leaves Monster Range: the Boss");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[CombatTarget] switch 0x80000401") && l.Contains("out of Monster Range")),
|
||||
"the switch says why: out of Monster Range");
|
||||
|
||||
t = new Rig(Closest, true, monsterRange: 10);
|
||||
t.S.MonsterRules.Add(new MonsterRule { Name = "Boss", Priority = 2 });
|
||||
t.Pick((A, 2, 0), (Boss, 9, 0));
|
||||
Check.Eq(t.Combat.activeTargetId, unchecked((int)Boss), "nothing locked yet: the higher priority is picked first");
|
||||
}
|
||||
|
||||
private static void HigherPriorityWins()
|
||||
{
|
||||
foreach (bool lockOn in new[] { true, false })
|
||||
foreach (bool lockOn in new[] { false })
|
||||
{
|
||||
string mode = lockOn ? "lock on" : "lock off";
|
||||
var t = new Rig(Closest, lockOn, monsterRange: 10);
|
||||
|
|
@ -275,6 +458,7 @@ internal static class TargetingTests
|
|||
|
||||
FakeHost.NotAttackable.Remove(Boss);
|
||||
t.Blocked.Remove(Boss);
|
||||
t.S.TargetLock = false; // with the lock on, Mob A would be kept (LockHoldsOverPriority)
|
||||
Check.Eq(t.Tick(), Boss, "in sight and attackable: the Boss takes over at once");
|
||||
string sw = FakeHost.Logs.Last(l => l.Contains("[CombatTarget] switch"));
|
||||
Check.True(sw.Contains("priority 1 < 5") && !sw.Contains("passed over"), "the switch says priority, with nothing passed over");
|
||||
|
|
@ -371,7 +555,8 @@ internal static class TargetingTests
|
|||
Check.True(why != null && why.Contains("'Boss' priority 5") && why.Contains("beyond Monster Range (10 m)"), $"/ra why names it ({why})");
|
||||
|
||||
t.Place(Boss, "Boss", north: -9);
|
||||
Check.Eq(t.Tick(), Boss, "inside Monster Range: the Boss takes over at once");
|
||||
t.S.TargetLock = false; // with the lock on, Mob A would be kept (LockHoldsOverPriority)
|
||||
Check.Eq(t.Tick(), Boss, "inside Monster Range, lock off: the Boss takes over at once");
|
||||
}
|
||||
|
||||
private static int PassedLines() => FakeHost.Logs.Count(l => l.Contains("[CombatTarget] passed over"));
|
||||
|
|
@ -431,9 +616,18 @@ internal static class TargetingTests
|
|||
private readonly WorldObjectCache _cache;
|
||||
private DateTime _now = RynthClock.Now; // the clock RynthAi times with
|
||||
|
||||
public Rig(int scheme, bool targetLock, Dictionary<uint, float>? health = null, int monsterRange = 20)
|
||||
/// <param name="plates">The engine plates' readings (API v93 GetMonsterHealth: id -> ratio, age ms);
|
||||
/// null = an engine without the call. <paramref name="plateVersion"/> non-zero: the table's Version.</param>
|
||||
public Rig(int scheme, bool targetLock, Dictionary<uint, float>? health = null, int monsterRange = 20,
|
||||
Dictionary<uint, (float Ratio, uint AgeMs)>? plates = null, uint plateVersion = 0)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
if (plates != null)
|
||||
{
|
||||
FakeHost.PlateHealthCalls = true;
|
||||
FakeHost.PlateHealthVersion = plateVersion;
|
||||
foreach (var kv in plates) FakeHost.PlateHealth[kv.Key] = kv.Value;
|
||||
}
|
||||
Place(Player, "Me", 96, 96, creature: false);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
Place(A, "Mob A", 96, 98);
|
||||
|
|
@ -442,14 +636,20 @@ internal static class TargetingTests
|
|||
Place(Boss, "Boss", 96, 101);
|
||||
S = new LegacyUiSettings { MonsterRange = monsterRange, TargetSelection = scheme, TargetLock = targetLock };
|
||||
var host = FakeHost.Create();
|
||||
Host = host;
|
||||
_cache = FakeHost.MakeCache(host, Player, new[] { A, B, C, Boss }, health);
|
||||
_cache.Clock = () => _now; // health from here on is stamped on the rig's clock
|
||||
Combat = new CombatManager(host, S, _cache);
|
||||
Combat.SetPlayerId(Player);
|
||||
Combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
|
||||
Combat.TargetClock = () => _now;
|
||||
}
|
||||
|
||||
public readonly RynthCore.PluginSdk.RynthCoreHost Host;
|
||||
public WorldObjectCache Cache => _cache;
|
||||
public void Health(uint id, float ratio) => _cache.OnUpdateHealth(id, ratio);
|
||||
/// <summary>The engine plates now read <paramref name="id"/> at <paramref name="ratio"/>, <paramref name="ageMs"/> old.</summary>
|
||||
public void Plate(uint id, float ratio, uint ageMs) => FakeHost.PlateHealth[id] = (ratio, ageMs);
|
||||
public void Advance(double ms) => _now = _now.AddMilliseconds(ms);
|
||||
|
||||
/// <summary>One tick: the scan holds these (id, distance m, facing angle deg); returns the target.</summary>
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ internal static class UseRefusalTests
|
|||
r.Add("use check: the next open settles an answered one that opened nothing; an open resets", WatchSettlesOnNextOpen);
|
||||
r.Add("use check (looting): Drakkon's stall - stop once, retry, say it once in chat, stop opening corpses, probe, recover", LootingStall);
|
||||
r.Add("use check (looting): normal opens never trip it", LootingNormalOpens);
|
||||
r.Add("use check (looting): opens with monsters about never trip it (a fight cancels them)", OpensInAFightDontCount);
|
||||
r.Add("flight recorder: the use check asks the engine for a dump (clean stop, stuck); normal opens never do", FlightDumpRequests);
|
||||
r.Add("corpse open: a corpse claimed while Combat owns the tick is opened only on the Looting tick", OpenWaitsForLootingTick);
|
||||
r.Add("move hold: while a corpse use is in flight RynthAi's moves and turns wait, stops go through, UseDone or 1.5 s releases", MoveHoldWhileUseInFlight);
|
||||
|
|
@ -256,6 +257,34 @@ internal static class UseRefusalTests
|
|||
|
||||
private static int ChatCount(string text) => FakeHost.Chat.Count(c => c.Contains(text));
|
||||
|
||||
// 2026-11-06, a wave fight: combat's swings cancelled the walk to the corpse, each open came back
|
||||
// answered with nothing opened, and four of them paused looting 5 minutes with "a relog fixes it".
|
||||
private static void OpensInAFightDontCount()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
var combat = new CombatManager(host, bot.S, bot.Cache);
|
||||
combat.SetPlayerId(Player);
|
||||
combat.SetScannedTargetsForTests(new[] { new CombatManager.ScannedTarget { Id = 0x7000, Distance = 3, Angle = 0, Bearing = double.NaN, Name = "Mob" } });
|
||||
bot.Set("_combatManager", combat);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
long answerAt = 0;
|
||||
for (int i = 0; i < 600; i++)
|
||||
{
|
||||
int uses = FakeHost.Uses.Count;
|
||||
bot.Tick(BotActivity.Looting);
|
||||
if (FakeHost.Uses.Count > uses) answerAt = now() + 60;
|
||||
advance(100);
|
||||
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; }
|
||||
}
|
||||
Check.True(FakeHost.Uses.Count > 0, "opens went out");
|
||||
Check.Eq(ChatCount(StuckLine), 0, "no 'a relog fixes it'");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("Use check:")), "the use check never acts on them");
|
||||
});
|
||||
}
|
||||
|
||||
private static void LootingStall()
|
||||
{
|
||||
World();
|
||||
|
|
@ -289,7 +318,7 @@ internal static class UseRefusalTests
|
|||
int usesAtStuck = FakeHost.Uses.Count;
|
||||
Check.False((bool)bot.Call("HasLootWork", bot.S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!,
|
||||
"no loot work during the back-off: nav and combat run on");
|
||||
for (int i = 0; i < 2400; i++) Step(); // 4 minutes
|
||||
for (int i = 0; i < 200; i++) Step(); // 20 s of the 30 s back-off
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no corpse is opened during the back-off");
|
||||
Check.Eq(ChatCount(StuckLine), 1, "and nothing more is said");
|
||||
|
||||
|
|
@ -639,7 +668,7 @@ internal static class UseRefusalTests
|
|||
|
||||
var w = bot.Get<UseRefusalWatch>("_useRefusals");
|
||||
int usesAtStuck = FakeHost.Uses.Count;
|
||||
for (int i = 0; i < 2400; i++) { bot.Tick(BotActivity.Looting); advance(100); } // 4 minutes
|
||||
for (int i = 0; i < 200; i++) { bot.Tick(BotActivity.Looting); advance(100); } // 20 s of the 30 s back-off
|
||||
Check.Eq(FakeHost.TapJumps, 1, "no jump during the back-off");
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no opens during the back-off");
|
||||
|
||||
|
|
|
|||
118
Tools/RynthCore.RynthAiHostTests/Tests/VendorFlagTests.cs
Normal file
118
Tools/RynthCore.RynthAiHostTests/Tests/VendorFlagTests.cs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Vendor;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// /ub vendor open finds a vendor by the server's vendor flag (PublicWeenieDesc BF_VENDOR 0x200).
|
||||
/// The world cache never files anything as AcObjectClass.Vendor: a retail-style shopkeeper is a
|
||||
/// creature (an Npc there), and a summoned storage NPC can reach the cache as a typed item. By
|
||||
/// name, partial name or id the flagged object opens; without the flag it is not a vendor.
|
||||
/// </summary>
|
||||
internal static class VendorFlagTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint Here = 0xA9B4001C;
|
||||
private const uint Shopkeeper = 0x80310003; // a creature with the vendor flag (retail and stock ACE)
|
||||
private const uint Keeper = 0x80310001; // a typed item with the vendor flag (a server's own NPC)
|
||||
private const uint Plain = 0x80310002; // a typed item without it
|
||||
private const uint Bystander = 0x80310004; // a creature (an Npc) without it
|
||||
private const uint BfVendor = 0x200;
|
||||
private const uint TGem = 0x800, TCreature = 0x10;
|
||||
private const string Attempt = "AutoVendor: attempting to open vendor";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("vendor open: a shopkeeper NPC with the vendor bitfield is found by name (retail-style)", RetailShopkeeper);
|
||||
r.Add("vendor open: a cache non-Vendor with the vendor bitfield is found by name", FoundByName);
|
||||
r.Add("vendor open: a cache non-Vendor with the vendor bitfield is found by id", FoundById);
|
||||
r.Add("vendor open: objects without the vendor bitfield are not vendors (by name and by id)", NotFlagged);
|
||||
r.Add("vendor open: a partial name finds the flagged object", FoundByPartial);
|
||||
}
|
||||
|
||||
private static AutoVendorManager Rig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Names[Player] = "Vendor Tester";
|
||||
FakeHost.Positions[Player] = (Here, 96f, 96f, 0f);
|
||||
FakeHost.PlayerPose = (Here, 96f, 96f, 0f);
|
||||
FakeHost.Containers[Player] = 0;
|
||||
foreach (var (id, name, type) in new[]
|
||||
{
|
||||
(Keeper, "Vault Keeper", TGem), (Plain, "Plain Gem", TGem),
|
||||
(Shopkeeper, "Shopkeeper Alfrid", TCreature), (Bystander, "Town Crier", TCreature),
|
||||
})
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Here, 97f, 97f, 0f);
|
||||
FakeHost.ItemTypes[id] = type;
|
||||
FakeHost.Containers[id] = 0;
|
||||
FakeHost.NotAttackable.Add(id);
|
||||
}
|
||||
FakeHost.Bitfields[Keeper] = BfVendor;
|
||||
FakeHost.Bitfields[Shopkeeper] = BfVendor;
|
||||
FakeHost.Bitfields[Bystander] = 0;
|
||||
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
foreach (uint id in new[] { Keeper, Plain, Shopkeeper, Bystander }) cache.OnCreateObject(id);
|
||||
for (int i = 0; i < 12; i++) cache.Tick();
|
||||
// Precondition: the cache really does file all of them as something other than Vendor.
|
||||
foreach (uint id in new[] { Keeper, Plain, Shopkeeper, Bystander })
|
||||
Check.True(cache.AllKnownObjects().Any(w => w.Id == unchecked((int)id) && w.ObjectClass != AcObjectClass.Vendor),
|
||||
$"precondition: 0x{id:X8} cached as a non-Vendor");
|
||||
return new AutoVendorManager(host, new LegacyUiSettings(), cache, Player, () => string.Empty);
|
||||
}
|
||||
|
||||
private static bool Attempted() => FakeHost.Logs.Any(l => l.Contains(Attempt, StringComparison.Ordinal));
|
||||
|
||||
// The open attempt names the chosen object: "...attempting to open vendor <name>".
|
||||
private static bool Opened(string name) => FakeHost.Logs.Any(l => l.EndsWith(Attempt + " " + name, StringComparison.Ordinal));
|
||||
|
||||
private static void RetailShopkeeper()
|
||||
{
|
||||
var m = Rig();
|
||||
m.CommandOpen("Shopkeeper Alfrid", false);
|
||||
Check.True(Opened("Shopkeeper Alfrid"), "the flagged shopkeeper is the one opened by name");
|
||||
}
|
||||
|
||||
private static void FoundByName()
|
||||
{
|
||||
var m = Rig();
|
||||
m.CommandOpen("Vault Keeper", false);
|
||||
Check.True(Opened("Vault Keeper"), "the flagged object is the one opened by name");
|
||||
}
|
||||
|
||||
private static void FoundById()
|
||||
{
|
||||
var m = Rig();
|
||||
m.CommandOpen("0x" + Keeper.ToString("X8"), false);
|
||||
Check.True(Opened("Vault Keeper"), "the flagged object is the one opened by hex id");
|
||||
}
|
||||
|
||||
private static void NotFlagged()
|
||||
{
|
||||
var m = Rig();
|
||||
m.CommandOpen("Plain Gem", false);
|
||||
Check.False(Attempted(), "an unflagged item is not opened by name");
|
||||
m.CommandOpen("0x" + Plain.ToString("X8"), false);
|
||||
Check.False(Attempted(), "an unflagged item is not opened by id");
|
||||
m.CommandOpen("Town Crier", false);
|
||||
Check.False(Attempted(), "an unflagged NPC is not opened by name");
|
||||
}
|
||||
|
||||
private static void FoundByPartial()
|
||||
{
|
||||
var m = Rig();
|
||||
m.CommandOpen("keeper", true);
|
||||
Check.True(Opened("Vault Keeper") || Opened("Shopkeeper Alfrid"), "a partial name opens a flagged object");
|
||||
Check.False(Opened("Plain Gem") || Opened("Town Crier"), "never an unflagged one");
|
||||
}
|
||||
}
|
||||
543
Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs
Normal file
543
Tools/RynthCore.RynthAiHostTests/Tests/VitalWandGateTests.cs
Normal file
|
|
@ -0,0 +1,543 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Kits are the standard heal, and the shield stays on.
|
||||
// A vital spell out of Magic mode with no caster in hand starts no weapon swap while a kit or potion
|
||||
// for that vital is carried (BuffManager.VitalSpellWouldSwap); buffing still swaps.
|
||||
internal static class VitalWandGateTests
|
||||
{
|
||||
private const uint Player = 0x500000B7;
|
||||
private const uint Wand = 0x80071001;
|
||||
private const uint Kit = 0x80071002;
|
||||
private const uint StamKit = 0x80071003;
|
||||
private const uint ManaPot = 0x80071004;
|
||||
private const uint HealPot = 0x80071005;
|
||||
private const uint CurrentWieldedLocation = 10; // STypeInt CurrentWieldedLocation
|
||||
private const uint HeldSlot = 0x01000000;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("vital wand gate: out of Magic with a healing kit carried, Heal Self starts no wand swap (not handled)", HealRefusedWithKit);
|
||||
r.Add("vital wand gate: the refused Heal Self falls through to the kit despite Kit Min Success", KitDespiteMinSuccessAfterRefusal);
|
||||
r.Add("vital wand gate: a caster already wielded in melee stance: the Magic stance change only, no weapon move", StanceOnlyWithCasterWielded);
|
||||
r.Add("vital wand gate: no kit and no potion at all: the swap is allowed (the only heal there is)", SwapAllowedWithNothingElse);
|
||||
r.Add("vital wand gate: Revitalize with a stamina kit, Stamina to Mana in a fight, the script heal with a health potion: no swap", OtherVitalsRefused);
|
||||
r.Add("vital wand gate: a pure caster in Magic mode with a kit carried still casts Heal Self", PureCasterUnaffected);
|
||||
r.Add("vital wand gate: buffing still swaps to the wand with a kit carried", BuffsStillSwap);
|
||||
r.Add("vital wand gate: Revitalize refused, no stamina potion: the stamina kit is used despite Kit Min Success", StaminaKitDespiteMinSuccess);
|
||||
r.Add("vital wand gate: Stamina to Mana never swaps in a fight; out of one with no mana potion it may", ManaInFightNoSwap);
|
||||
r.Add("vital wand gate: in Magic stance with no wand in hand and a kit carried, Heal Self is not gated", MagicNoWandNotGated);
|
||||
r.Add("vital wand gate: a kit its line called used up, or gone from the client's pack, is no kit: Heal Self is handled and the swap is allowed", GoneKitAllowsSwap);
|
||||
r.Add("vital wand gate: a swap already under way finishes when a kit reappears (no abandoned swap, no kit mid-wield)", SwapInFlightFinishes);
|
||||
r.Add("vital wand gate: a kit the server refused 3 times within 10 s is no kit for the gate; a kit landing counts it again", RefusedKitAllowsSwap);
|
||||
r.Add("vital wand gate: the mana step's stamina refill also uses the stamina kit despite Kit Min Success", ManaRefillStaminaLastResort);
|
||||
r.Add("vital wand gate: out of a fight Stamina to Mana may swap with a mana potion carried; in a fight it may not", ManaPotionOutOfFightSwaps);
|
||||
r.Add("vital wand gate: a refusal streak ages out: 11 s after the last refusal the kit counts again", RefusedStreakAgesOut);
|
||||
r.Add("vital wand gate: no wand found: Heal Self takes the bare-handed Magic stance, not gated", NoWandNotGated);
|
||||
r.Add("vital wand gate: one line when it starts refusing, one when the swap may go again or nothing asks for 5 s, one for a refused kit", GateLogLines);
|
||||
r.Add("vital wand gate: under Emergency Heal At the kit despite Kit Min Success still goes; the HP failsafe's recall still swaps to the wand", EmergencyFloorKept);
|
||||
r.Add("vital wand gate: the between-fights top-off (no Revitalize) uses a stamina kit under Stamina Kit Min Success as the last resort", TopOffStaminaLastResort);
|
||||
r.Add("vital wand gate: at or under Emergency Heal At a health spell may swap to the wand with a kit carried (the surest heal goes)", EmergencySpellMaySwap);
|
||||
r.Add("buffs wait: under Heal At in a fight no buff is cast and the arbiter isn't asked for buffs; over it or out of a fight they go on", BuffsWaitWhileHurt);
|
||||
}
|
||||
|
||||
// 2026-11-07: at 9% the gate sent Drakkon's kit (5-8% at low health with vitae) instead of Stamina to Health, and he died.
|
||||
private static void EmergencySpellMaySwap()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit });
|
||||
S.EmergencyHealAt = 30;
|
||||
SetVitals(b, 9, 74, 100);
|
||||
Check.True(VitalCast(b, "Stamina to Health Self"), "9% health, kit carried: Stamina to Health is handled: " + Why(b));
|
||||
Check.True(SwapActive(b), "its wand swap is under way");
|
||||
|
||||
var a = Rig(CombatMode.Melee, new[] { Kit });
|
||||
S.EmergencyHealAt = 30;
|
||||
SetVitals(a, 45, 74, 100);
|
||||
Check.False(VitalCast(a, "Heal Self"), "45%, over Emergency Heal At: the gate still refuses Heal Self");
|
||||
Check.True(Why(a).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "with its reason: " + Why(a));
|
||||
}
|
||||
|
||||
// 2026-11-07: four weapon auras in a row with a golem hitting him under Heal At; the emergency heal waited for the last cast.
|
||||
private static void BuffsWaitWhileHurt()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, Array.Empty<uint>());
|
||||
S.HealAt = 60;
|
||||
b.InCombatOverride = () => true;
|
||||
SetVitals(b, 54, 100, 100);
|
||||
Check.True(b.BuffsWaitForHealth(), "54% under Heal At 60% in a fight: buffs wait");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[Buff] buffs wait: health 54% is under Heal At 60% in a fight", StringComparison.Ordinal)), "logged once at the start");
|
||||
Check.True(b.BuffsWaitForHealth(), "still waiting");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[Buff] buffs wait:", StringComparison.Ordinal)), 1, "not logged again");
|
||||
SetVitals(b, 70, 100, 100);
|
||||
Check.False(b.BuffsWaitForHealth(), "back over Heal At: buffs go on");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[Buff] buffs go on", StringComparison.Ordinal)), "the end is logged");
|
||||
SetVitals(b, 40, 100, 100);
|
||||
b.InCombatOverride = () => false;
|
||||
Check.False(b.BuffsWaitForHealth(), "out of a fight: buffs go on even under Heal At");
|
||||
}
|
||||
|
||||
private static void GateLogLines()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit });
|
||||
DateTime t0 = new DateTime(2026, 1, 1, 18, 0, 0);
|
||||
DateTime now = t0;
|
||||
b.Clock = () => now;
|
||||
VitalCast(b, "Heal Self");
|
||||
VitalCast(b, "Heal Self");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[RynthAi] Vitals: wand gate: no wand swap for Heal Self - a kit is carried", StringComparison.Ordinal)), 1,
|
||||
"the start is logged once: " + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains("wand gate", StringComparison.Ordinal))));
|
||||
now = t0.AddSeconds(6);
|
||||
b.OnHeartbeat();
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("wand gate ended for Heal Self: not asked for in 5 s", StringComparison.Ordinal)), "5 s with no refusal: the end is logged");
|
||||
|
||||
// The swap allowed again (the kit gone) ends it at once.
|
||||
var g = Rig(CombatMode.Melee, new[] { Kit });
|
||||
VitalCast(g, "Heal Self");
|
||||
Check.True((bool)typeof(BuffManager).GetMethod("AttemptHealthKitUse", Np, new[] { typeof(bool) })!.Invoke(g, new object[] { false })!, "the kit goes out");
|
||||
g.OnChatWindowText("You heal yourself for 12 Health points. Your Treated Healing Kit is used up.", 0);
|
||||
Check.True(VitalCast(g, "Heal Self"), "the kit used up: Heal Self handled");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("wand gate ended for Heal Self: no healing kit or potion is carried; its wand swap may go", StringComparison.Ordinal)),
|
||||
"the end is logged with why");
|
||||
|
||||
// A kit refused 3 times stops counting, logged.
|
||||
var k = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
RefuseKit(k, Kit); RefuseKit(k, Kit); RefuseKit(k, Kit);
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("refused 3 times in 10 s: it no longer counts as a heal", StringComparison.Ordinal)), 1, "the streak is logged once");
|
||||
}
|
||||
|
||||
// The safety floor: the gate only refuses spells in the vitals chain. The last-resort kit still goes
|
||||
// at Emergency Heal At, and the HP failsafe's Lifestone Recall (EnsureMagicMode, macro off) still swaps.
|
||||
private static void EmergencyFloorKept()
|
||||
{
|
||||
// 2026-11-07: under Emergency Heal At a kit under Kit Min Success no longer beats the heal spell's wand
|
||||
// swap (Drakkon's kit was 5-8% at low health and he died at 9% with it).
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 95);
|
||||
S.EmergencyHealAt = 30;
|
||||
SetVitals(b, 20, 100, 100);
|
||||
Check.True(b.CheckVitals(), "20% under Emergency Heal At 30%: the vitals act");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "no kit under Kit Min Success");
|
||||
Check.True(SwapActive(b), "the heal spell's wand swap goes instead");
|
||||
|
||||
// A kit at Kit Min Success is still the heal at Emergency Heal At.
|
||||
var k = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 0);
|
||||
S.EmergencyHealAt = 30;
|
||||
SetVitals(k, 20, 100, 100);
|
||||
Check.True(k.CheckVitals(), "20%, a kit that passes Kit Min Success: the vitals act");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "the kit goes out");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no spell");
|
||||
|
||||
var r = Rig(CombatMode.Melee, new[] { Kit, HealPot }, usePotions: true);
|
||||
int before = SwapActivity();
|
||||
string wait = (string)typeof(BuffManager).GetMethod("RecallCastHolds", Np)!.Invoke(r, null)!;
|
||||
Check.Eq(wait, "wand swap / Magic stance", "the recall waits for its wand swap");
|
||||
Check.True(SwapActivity() > before, "the recall's wand swap starts with a kit and a potion carried");
|
||||
}
|
||||
|
||||
// b2e1ade4: between fights out of Magic no Revitalize is cast for Top Off Stamina; kits still top off,
|
||||
// and with this port a stamina kit under Stamina Kit Min Success % is that last resort.
|
||||
private static void TopOffStaminaLastResort()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 95);
|
||||
b.InCombatOverride = () => false;
|
||||
S.TopOffStam = 60; S.RestamAt = 10;
|
||||
SetVitals(b, 100, 40, 100);
|
||||
Check.True(b.CheckVitals(), "stamina 40% under Top Off Stamina 60%, no fight: acts");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use");
|
||||
Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "the stamina kit");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, "no Magic stance");
|
||||
}
|
||||
|
||||
// Out of a fight buffing is about to swap to the wand anyway, so a
|
||||
// mana potion drunk to spare the swap is a potion wasted. In a fight the refusal stands.
|
||||
private static void ManaPotionOutOfFightSwaps()
|
||||
{
|
||||
var q = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true);
|
||||
q.InCombatOverride = () => false;
|
||||
Check.True(VitalCast(q, "Stamina to Mana Self"), "out of a fight, mana potion carried: handled: " + Why(q));
|
||||
Check.True(SwapActive(q), "the wand swap is under way");
|
||||
|
||||
var f = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true);
|
||||
f.InCombatOverride = () => true;
|
||||
Check.False(VitalCast(f, "Stamina to Mana Self"), "in a fight, mana potion carried: not handled");
|
||||
Check.True(Why(f).Contains("Stamina to Mana in a fight", StringComparison.Ordinal), "the in-fight reason: " + Why(f));
|
||||
Check.Eq(SwapActivity(), 0, "in a fight: no swap");
|
||||
}
|
||||
|
||||
// The stamina last resort covers every stamina path: the stamina step, the mana step's refill
|
||||
// (AttemptManaRefill) and the buffing mana floor.
|
||||
private static void ManaRefillStaminaLastResort()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 95);
|
||||
SetVitals(b, 100, 10, 10); // stamina 10% <= the Stamina to Mana floor (15): refill stamina first
|
||||
object[] args = { 10, false };
|
||||
bool acted = (bool)typeof(BuffManager).GetMethod("AttemptManaRefill", Np)!.Invoke(b, args)!;
|
||||
Check.True(acted, "the mana step acts");
|
||||
Check.True((bool)args[1], "by refilling stamina");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use");
|
||||
Check.Eq(FakeHost.UsesOn[0].Source, StamKit, "the stamina kit Kit Min Success skipped");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("using the stamina kit despite Stamina Kit Min Success", StringComparison.Ordinal)), "logged");
|
||||
Check.Eq(SwapActivity(), 0, "no swap");
|
||||
}
|
||||
|
||||
/// <summary>The kit sent and refused by the server (a UseDone with an error code).</summary>
|
||||
private static void RefuseKit(BuffManager b, uint kit, bool stamina = false)
|
||||
{
|
||||
typeof(BuffManager).GetField("_kitRefusedAt", Np)!.SetValue(b, DateTime.MinValue); // past KitRetryAfterRefusalMs (real clock)
|
||||
int uses = FakeHost.UsesOn.Count;
|
||||
Check.True((bool)typeof(BuffManager).GetMethod(stamina ? "AttemptStaminaKitUse" : "AttemptHealthKitUse", Np,
|
||||
stamina ? Type.EmptyTypes : new[] { typeof(bool) })!.Invoke(b, stamina ? null : new object[] { false })!, "the kit goes out");
|
||||
Check.Eq(FakeHost.UsesOn.Count, uses + 1, "sent");
|
||||
Check.Eq(FakeHost.UsesOn[^1].Source, kit, "that kit");
|
||||
FakeHost.UseDone(0x1D); // YoureTooBusy
|
||||
Check.False(b.KitPending(), "refused: the wait ends");
|
||||
}
|
||||
|
||||
// A kit the server keeps refusing (a UseDone error, "You're too busy!") is no answer the kit wait
|
||||
// drops: without a cap it would count for the gate forever and no spell heal could ever go.
|
||||
private static void RefusedKitAllowsSwap()
|
||||
{
|
||||
var setNow = new Action<BuffManager, DateTime>((bm, t) => bm.Clock = () => t);
|
||||
var t0 = new DateTime(2026, 1, 1, 18, 0, 0);
|
||||
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
RefuseKit(b, Kit);
|
||||
RefuseKit(b, Kit);
|
||||
Check.False(VitalCast(b, "Heal Self"), "2 refusals: the kit still counts, Heal Self refused");
|
||||
RefuseKit(b, Kit);
|
||||
Check.True(VitalCast(b, "Heal Self"), "3 refusals within 10 s: the kit is no kit, Heal Self handled: " + Why(b));
|
||||
Check.True(SwapActive(b), "the wand swap is under way");
|
||||
|
||||
// Spread over more than 10 s: no streak.
|
||||
var s = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
setNow(s, t0); RefuseKit(s, Kit);
|
||||
setNow(s, t0.AddSeconds(6)); RefuseKit(s, Kit);
|
||||
setNow(s, t0.AddSeconds(12)); RefuseKit(s, Kit);
|
||||
Check.False(VitalCast(s, "Heal Self"), "3 refusals over 12 s: the kit still counts");
|
||||
|
||||
// A kit landing ends the streak.
|
||||
var l = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
RefuseKit(l, Kit); RefuseKit(l, Kit); RefuseKit(l, Kit);
|
||||
typeof(BuffManager).GetField("_kitRefusedAt", Np)!.SetValue(l, DateTime.MinValue);
|
||||
typeof(BuffManager).GetMethod("AttemptHealthKitUse", Np, new[] { typeof(bool) })!.Invoke(l, new object[] { false });
|
||||
l.OnChatWindowText("You heal yourself for 40 Health points. Your Treated Healing Kit has 3 uses left.", 0);
|
||||
Check.False(VitalCast(l, "Heal Self"), "a kit landed: it counts again, Heal Self refused");
|
||||
|
||||
// Stamina kits too: Revitalize may swap once the stamina kit is refused 3 times.
|
||||
var st = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: 0, kitAnswers: true);
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
Check.False(VitalCast(st, "Revitalize Self"), "control: the stamina kit carried, Revitalize refused");
|
||||
RefuseKit(st, StamKit, stamina: true); RefuseKit(st, StamKit, stamina: true); RefuseKit(st, StamKit, stamina: true);
|
||||
Check.True(VitalCast(st, "Revitalize Self"), "stamina kit refused 3 times: Revitalize handled: " + Why(st));
|
||||
}
|
||||
|
||||
// The gate allowed a swap (no kit), then a kit came back. Refusing now would leave the
|
||||
// swap untouched until TickWandSwap abandons it, with the shield maybe already in the pack.
|
||||
private static void SwapInFlightFinishes()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, Array.Empty<uint>());
|
||||
Check.True(VitalCast(b, "Heal Self"), "no kit: Heal Self handled");
|
||||
Check.True(SwapActive(b), "the swap started");
|
||||
var cache = (WorldObjectCache)typeof(BuffManager).GetField("_worldObjectCache", Np)!.GetValue(b)!;
|
||||
_ = cache[unchecked((int)Kit)]; // the kit is back in the pack
|
||||
cache.GetDirectInventory(forceRefresh: true); // the fake host has no container walk: refresh the snapshot by hand
|
||||
Check.True((bool)typeof(BuffManager).GetMethod("HasUsableHealthKit", Np)!.Invoke(b, null)!, "the rig: the kit counts as usable");
|
||||
Check.True(VitalCast(b, "Heal Self"), "the kit back, the swap under way: still handled: " + Why(b));
|
||||
Check.True(SwapActive(b), "the swap is still under way");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "no kit sent mid-swap");
|
||||
}
|
||||
|
||||
private static bool SwapActive(BuffManager b)
|
||||
{
|
||||
object swap = typeof(BuffManager).GetField("_wandSwap", Np)!.GetValue(b)!;
|
||||
return (bool)swap.GetType().GetProperty("Active")!.GetValue(swap)!;
|
||||
}
|
||||
|
||||
// A wand not in hand is no reason to gate
|
||||
// a character already in Magic: no weapon moves for its cast.
|
||||
private static void MagicNoWandNotGated()
|
||||
{
|
||||
var b = Rig(CombatMode.Magic, new[] { Kit });
|
||||
VitalCast(b, "Heal Self");
|
||||
Check.False(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "in Magic: not gated: " + Why(b));
|
||||
}
|
||||
|
||||
// A kit the kit picks would not use must not count for the gate either: one its result line called
|
||||
// used up (BuffManager.KitUsedUp.cs), or one the client's live pack walk no longer lists.
|
||||
private static void GoneKitAllowsSwap()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit });
|
||||
Check.False(VitalCast(b, "Heal Self"), "control: the kit carried, Heal Self refused");
|
||||
|
||||
var u = Rig(CombatMode.Melee, new[] { Kit });
|
||||
Check.True((bool)typeof(BuffManager).GetMethod("AttemptHealthKitUse", Np, new[] { typeof(bool) })!.Invoke(u, new object[] { false })!, "the kit goes out");
|
||||
u.OnChatWindowText("You heal yourself for 12 Health points. Your Treated Healing Kit is used up.", 0);
|
||||
Check.True(VitalCast(u, "Heal Self"), "the kit's line said used up: Heal Self handled: " + Why(u));
|
||||
Check.True(SwapActive(u), "the wand swap is under way");
|
||||
|
||||
var w = Rig(CombatMode.Melee, new[] { Kit }, walk: true);
|
||||
var wc = (WorldObjectCache)typeof(BuffManager).GetField("_worldObjectCache", Np)!.GetValue(w)!;
|
||||
DateTime wt = new DateTime(2026, 1, 1, 18, 0, 0);
|
||||
wc.WalkClock = () => wt; // the walk's reuse on a test clock
|
||||
Check.False(VitalCast(w, "Heal Self"), "control, live walk: the kit carried, Heal Self refused");
|
||||
FakeHost.Containers.Remove(Kit); // used up: the client deletes it; the cache never hears
|
||||
FakeHost.Names.Remove(Kit);
|
||||
wt = wt.AddMilliseconds(1100); // past the walk's 1 s reuse
|
||||
Check.True(VitalCast(w, "Heal Self"), "the kit gone from the client's pack: Heal Self handled: " + Why(w));
|
||||
Check.True(SwapActive(w), "the wand swap is under way");
|
||||
}
|
||||
|
||||
// A refusal streak ages out: with no refusal for 10 s the kit counts for the gate again.
|
||||
private static void RefusedStreakAgesOut()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
|
||||
var t0 = new DateTime(2026, 1, 1, 18, 0, 0);
|
||||
DateTime now = t0;
|
||||
b.Clock = () => now;
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
RefuseKit(b, Kit); RefuseKit(b, Kit); RefuseKit(b, Kit);
|
||||
Check.True(VitalCast(b, "Heal Self"), "control: 3 refusals, the kit is no kit: Heal Self handled: " + Why(b));
|
||||
var c = Rig(CombatMode.Melee, new[] { Kit }, kitAnswers: true);
|
||||
DateTime cnow = t0;
|
||||
c.Clock = () => cnow;
|
||||
FakeHost.UseDoneSeq = 10;
|
||||
RefuseKit(c, Kit); RefuseKit(c, Kit); RefuseKit(c, Kit);
|
||||
cnow = t0.AddSeconds(11);
|
||||
Check.False(VitalCast(c, "Heal Self"), "11 s after the last refusal: the kit counts again, Heal Self refused");
|
||||
Check.True(Why(c).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "the gate's reason: " + Why(c));
|
||||
}
|
||||
|
||||
// No wand found (no wand rule, none carried): the Magic stance goes bare-handed and no weapon moves.
|
||||
private static void NoWandNotGated()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit }, noWand: true);
|
||||
VitalCast(b, "Heal Self");
|
||||
Check.False(Why(b).Contains("no wand swap", StringComparison.Ordinal), "no wand: not refused by the gate: " + Why(b));
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "the bare-handed Magic stance request goes out");
|
||||
Check.Eq(FakeHost.Wields.Count, 0, "no wield");
|
||||
}
|
||||
|
||||
private static void SetVitals(BuffManager b, uint health, uint stamina, uint mana)
|
||||
{
|
||||
var v = (PlayerVitalsCache)typeof(BuffManager).GetField("_vitals", Np)!.GetValue(b)!;
|
||||
v.CurrentHealth = health; v.CurrentStamina = stamina; v.CurrentMana = mana;
|
||||
}
|
||||
|
||||
private static void StaminaKitDespiteMinSuccess()
|
||||
{
|
||||
foreach (int minSuccess in new[] { 95, 0 })
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { StamKit }, kitMinSuccess: minSuccess);
|
||||
S.RestamAt = 50;
|
||||
SetVitals(b, 100, 20, 100);
|
||||
Check.True(b.CheckVitals(), $"min {minSuccess}: stamina 20% under Re-stam At 50%: the chain acts");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, $"min {minSuccess}: one kit use");
|
||||
Check.Eq(FakeHost.UsesOn[0].Source, StamKit, $"min {minSuccess}: the stamina kit");
|
||||
bool lastResort = FakeHost.Logs.Any(l => l.Contains("using the stamina kit despite Stamina Kit Min Success", StringComparison.Ordinal));
|
||||
if (minSuccess == 95) Check.True(lastResort, "under Kit Min Success: used as the last resort, logged");
|
||||
else Check.False(lastResort, "control, chance fine: the normal kit use, no last-resort line");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, $"min {minSuccess}: no Magic stance");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, $"min {minSuccess}: no Revitalize");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ManaInFightNoSwap()
|
||||
{
|
||||
// No mana potion, no kit: only the fight decides.
|
||||
var f = Rig(CombatMode.Melee, Array.Empty<uint>(), usePotions: true);
|
||||
f.InCombatOverride = () => true;
|
||||
Check.False(VitalCast(f, "Stamina to Mana Self"), "in a fight: Stamina to Mana not handled");
|
||||
Check.True(Why(f).Contains("Stamina to Mana in a fight", StringComparison.Ordinal), "the why says so: " + Why(f));
|
||||
Check.Eq(SwapActivity(), 0, "in a fight: no swap");
|
||||
|
||||
var q = Rig(CombatMode.Melee, Array.Empty<uint>(), usePotions: true);
|
||||
q.InCombatOverride = () => false;
|
||||
int before = SwapActivity();
|
||||
Check.True(VitalCast(q, "Stamina to Mana Self"), "out of a fight, no mana potion: handled (the swap step): " + Why(q));
|
||||
Check.True(SwapActivity() > before, "out of a fight: the wand swap started");
|
||||
|
||||
// A caster in hand needs no swap: Stamina to Mana still goes in a fight.
|
||||
var c = Rig(CombatMode.Melee, Array.Empty<uint>(), wandWielded: true);
|
||||
c.InCombatOverride = () => true;
|
||||
VitalCast(c, "Stamina to Mana Self");
|
||||
Check.False(Why(c).Contains("no wand swap", StringComparison.Ordinal), "caster in hand, in a fight: not gated: " + Why(c));
|
||||
}
|
||||
|
||||
private static LegacyUiSettings S = new();
|
||||
|
||||
private static BuffManager Rig(int mode, uint[] items, bool wandWielded = false, bool usePotions = false, int kitMinSuccess = 0, bool kitAnswers = false,
|
||||
bool walk = false, bool noWand = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
uint[] carried = (noWand ? Array.Empty<uint>() : new[] { Wand }).Concat(items).ToArray();
|
||||
if (walk)
|
||||
{
|
||||
FakeHost.ContentsCalls = true; // the client's pack walk (GetContainerContents)
|
||||
foreach (uint id in carried) FakeHost.Containers[id] = Player;
|
||||
}
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
if (kitAnswers) { FakeHost.ServerGates = true; FakeHost.LastUseDoneCalls = true; } // a kit's UseDone answers
|
||||
FakeHost.CombatModeValue = mode;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, 33)] = (400, 2); // Life Magic
|
||||
FakeHost.Skills[(Player, 21)] = (10, 2); // Healing, low: a kit chance under any real Kit Min Success
|
||||
if (!noWand)
|
||||
{
|
||||
FakeHost.Names[Wand] = "Wand";
|
||||
FakeHost.ItemTypes[Wand] = 0x8000; // a caster
|
||||
FakeHost.Appraised.Add(Wand); // identified: FindWandInItems takes it (a real swap, not bare-handed Magic)
|
||||
}
|
||||
FakeHost.Names[Kit] = "Treated Healing Kit";
|
||||
// Lesser (boost 100): (10 + 100) x 1.1 = 121 vs 80 missing x 2 x 1.1 = 176 in melee, 16%, under the
|
||||
// weapon-out bar of 30 (a Greater kit's boost 200 clears it).
|
||||
FakeHost.Names[StamKit] = "Lesser Stamina Kit";
|
||||
FakeHost.Names[ManaPot] = "Mana Elixir";
|
||||
FakeHost.Names[HealPot] = "Healing Elixir";
|
||||
if (wandWielded) FakeHost.Ints[(Wand, CurrentWieldedLocation)] = unchecked((int)HeldSlot);
|
||||
var host = FakeHost.Create(Player);
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 75, TopOffHP = 75, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 0, TopOffStam = 0, UsePotions = usePotions, EnableBuffing = false,
|
||||
KitMinSuccessPct = kitMinSuccess, StaminaKitMinSuccessPct = kitMinSuccess, PeaceModeForKits = false,
|
||||
};
|
||||
if (!noWand) S.ItemRules.Add(new ItemRule { Id = unchecked((int)Wand), Name = "Wand", Element = "Fire" });
|
||||
if (items.Contains(ManaPot)) S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)ManaPot), Name = "Mana Elixir", Type = "ManaPotion" });
|
||||
if (items.Contains(HealPot)) S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)HealPot), Name = "Healing Elixir", Type = "HealthPotion" });
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 40, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, S, sm, v);
|
||||
b.SetCharacterSkills(skills);
|
||||
b.MarkLiveBuffsReadyForTests();
|
||||
b.InCombatOverride = () => true;
|
||||
b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, carried));
|
||||
DateTime now = new DateTime(2026, 1, 1, 18, 0, 0);
|
||||
b.Clock = () => now;
|
||||
return b;
|
||||
}
|
||||
|
||||
private static readonly BindingFlags Np = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
|
||||
private static bool VitalCast(BuffManager b, string baseName)
|
||||
=> (bool)typeof(BuffManager).GetMethod("AttemptVitalCast", Np)!.Invoke(b, new object[] { baseName })!;
|
||||
|
||||
private static string Why(BuffManager b) => (string)typeof(BuffManager).GetField("_vitalWhy", Np)!.GetValue(b)!;
|
||||
|
||||
/// <summary>Everything a wand swap or stance change sends or logs.</summary>
|
||||
private static int SwapActivity() => FakeHost.CombatModeRequests.Count + FakeHost.Wields.Count + FakeHost.Uses.Count
|
||||
+ FakeHost.Logs.Count(l => l.Contains("[WieldGate] switching to", StringComparison.Ordinal));
|
||||
|
||||
private static void HealRefusedWithKit()
|
||||
{
|
||||
foreach (int mode in new[] { CombatMode.Melee, CombatMode.Missile, CombatMode.NonCombat })
|
||||
{
|
||||
var b = Rig(mode, new[] { Kit });
|
||||
int before = SwapActivity();
|
||||
Check.False(VitalCast(b, "Heal Self"), $"mode {mode}, kit carried: Heal Self not handled");
|
||||
Check.True(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), $"mode {mode}: the why says so: {Why(b)}");
|
||||
Check.Eq(SwapActivity(), before, $"mode {mode}: no stance change, wield or swap step");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, $"mode {mode}: nothing cast");
|
||||
}
|
||||
// A health potion alone (no kit) refuses it too.
|
||||
var p = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: true);
|
||||
Check.False(VitalCast(p, "Stamina to Health Self"), "health potion carried: Stamina to Health not handled");
|
||||
Check.Eq(SwapActivity(), 0, "and no swap");
|
||||
}
|
||||
|
||||
private static void KitDespiteMinSuccessAfterRefusal()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit }, kitMinSuccess: 95);
|
||||
Check.True(b.CheckVitals(), "40% under Heal At 75%: the chain acts");
|
||||
Check.Eq(FakeHost.UsesOn.Count, 1, "one kit use");
|
||||
Check.Eq(FakeHost.UsesOn[0].Source, Kit, "the kit Kit Min Success skipped");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("despite Kit Min Success", StringComparison.Ordinal)), "the last resort is logged");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 0, "no Magic stance asked for");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no Heal Self");
|
||||
}
|
||||
|
||||
private static void StanceOnlyWithCasterWielded()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit }, wandWielded: true);
|
||||
Check.False(Why(b).Contains("no wand swap", StringComparison.Ordinal), "rig");
|
||||
VitalCast(b, "Heal Self");
|
||||
Check.False(Why(b).Contains("no wand swap for a vital spell", StringComparison.Ordinal), "caster in hand: not refused by the gate: " + Why(b));
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count(m => m == CombatMode.Magic), 1, "the Magic stance change goes out");
|
||||
Check.Eq(FakeHost.Wields.Count, 0, "no wield");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "no use (no re-equip)");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("[WieldGate] switching to", StringComparison.Ordinal)), "no swap started");
|
||||
}
|
||||
|
||||
private static void SwapAllowedWithNothingElse()
|
||||
{
|
||||
// Control for HealRefusedWithKit: the same rig with nothing else to heal with.
|
||||
var b = Rig(CombatMode.Melee, Array.Empty<uint>(), usePotions: true);
|
||||
int before = SwapActivity();
|
||||
bool handled = VitalCast(b, "Heal Self");
|
||||
Check.True(handled, "no kit, no potion: Heal Self handled (its swap step in flight): " + Why(b));
|
||||
Check.True(SwapActivity() > before, "the wand swap started");
|
||||
// A potion only, with Use Potions off: nothing RynthAi may use, so the swap is allowed.
|
||||
var k = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: false);
|
||||
Check.True(VitalCast(k, "Heal Self"), "a potion Use Potions may not drink is no heal: the swap is allowed");
|
||||
}
|
||||
|
||||
private static void OtherVitalsRefused()
|
||||
{
|
||||
var s = Rig(CombatMode.Melee, new[] { StamKit });
|
||||
Check.False(VitalCast(s, "Revitalize Self"), "stamina kit carried: Revitalize not handled");
|
||||
Check.Eq(SwapActivity(), 0, "no swap for Revitalize");
|
||||
var sc = Rig(CombatMode.Melee, new[] { Kit });
|
||||
Check.True(VitalCast(sc, "Revitalize Self"), "control: a healing kit is no stamina restore: Revitalize may swap");
|
||||
|
||||
var m = Rig(CombatMode.Melee, new[] { ManaPot }, usePotions: true);
|
||||
m.InCombatOverride = () => true; // the potion alone no longer refuses it (out of a fight it may swap): the fight does
|
||||
Check.False(VitalCast(m, "Stamina to Mana Self"), "in a fight, mana potion carried: Stamina to Mana not handled");
|
||||
Check.Eq(SwapActivity(), 0, "no swap for Stamina to Mana in a fight");
|
||||
|
||||
// The script hook's heal goes through CastVital with the Healing label.
|
||||
var h = Rig(CombatMode.Melee, new[] { HealPot }, usePotions: true);
|
||||
int heal = SpellTable.Rows.First(r => r.Name.StartsWith("Heal Self", StringComparison.Ordinal)).Id;
|
||||
object[] args = { heal, Player, BuffManager.LabelHealing, "Heal Self (script)", false };
|
||||
bool handled = (bool)typeof(BuffManager).GetMethod("CastVital", Np)!.Invoke(h, args)!;
|
||||
Check.False(handled, "script heal, health potion carried: not handled");
|
||||
Check.False((bool)args[4], "not sent");
|
||||
Check.Eq(SwapActivity(), 0, "no swap for the script heal");
|
||||
}
|
||||
|
||||
private static void PureCasterUnaffected()
|
||||
{
|
||||
var b = Rig(CombatMode.Magic, new[] { Kit }, wandWielded: true);
|
||||
S.UseKitsInMagicMode = false; // the kit is skipped in Magic: the spell is the heal
|
||||
Check.True(b.CheckVitals(), "a caster in Magic under Heal At: acts");
|
||||
Check.True(FakeHost.Casts.Count > 0, "Heal Self is cast: " + Why(b));
|
||||
Check.Eq(FakeHost.UsesOn.Count, 0, "no kit");
|
||||
Check.Eq(FakeHost.Wields.Count, 0, "no wield");
|
||||
}
|
||||
|
||||
private static void BuffsStillSwap()
|
||||
{
|
||||
var b = Rig(CombatMode.Melee, new[] { Kit, HealPot }, usePotions: true);
|
||||
int before = SwapActivity();
|
||||
var ensure = typeof(BuffManager).GetMethod("EnsureMagicMode", Np)!;
|
||||
bool inMagic = (bool)ensure.Invoke(b, new object[] { true, false })!;
|
||||
Check.False(inMagic, "not in Magic yet");
|
||||
Check.True(SwapActivity() > before, "buffing starts the wand swap with a kit and potion carried");
|
||||
}
|
||||
}
|
||||
|
|
@ -26,10 +26,12 @@ internal static class VitalsTests
|
|||
r.Add("vitals: a recharge started in a fight, or under Re-stam At just after one, finishes to Re-stam To", RestamRunOutlivesFight);
|
||||
r.Add("vitals: a Re-stam To run counts casts sent, not the ticks spent waiting for one", RestamRunCountsSentCasts);
|
||||
r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst);
|
||||
r.Add("vitals: no wand swap for the between-fights stamina top-off; under Re-stam At, with a potion or in Magic it acts as before", NoWandSwapForStaminaTopOff);
|
||||
r.Add("vitals: a listed potion whose stack ran out is drunk from the next stack of that name", ListedPotionNextStack);
|
||||
r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait);
|
||||
r.Add("vitals: Heal Self known only above the tier Life Magic allows (vitae) is still cast", HealAboveAllowedTier);
|
||||
r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter);
|
||||
r.Add("vitals: health falling with nothing in the scan uses the fight's Heal At, not Top Off HP, for 5 s", BeingHitIsAFight);
|
||||
r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals);
|
||||
r.Add("vitals: no components for the top level - the next lower level is cast, not the same one again", NoComponentsFallsBack);
|
||||
// Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md).
|
||||
|
|
@ -112,6 +114,32 @@ internal static class VitalsTests
|
|||
// 2026-10-04, "nav and looting have priority over healing, almost dying in packs": the
|
||||
// arbiter only saw a heal on ticks where CheckVitals ran (never while looting kept the client
|
||||
// busy). Health under a line now says "wants vitals" by itself.
|
||||
// 2026-11-06: a mob behind a wall isn't in the scan, so a character it hit read as idle and every
|
||||
// hit put him under Top Off HP: kits for 45 s and nothing else ran.
|
||||
private static void BeingHitIsAFight()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 60, TopOffHP = 95, EmergencyHealAt = 0, StaminaToHealthAt = 0, UsePotions = false };
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
var v = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, v);
|
||||
b.SetCharacterSkills(skills);
|
||||
|
||||
Check.False(b.WantsVitalRecharge, "full health: nothing to do");
|
||||
v.CurrentHealth = 80;
|
||||
Check.False(b.WantsVitalRecharge, "hit down to 80%: a fight, and over Heal At 60");
|
||||
v.CurrentHealth = 50;
|
||||
Check.True(b.WantsVitalRecharge, "50% is under Heal At: heals");
|
||||
}
|
||||
|
||||
private static void HealthWinsArbiter()
|
||||
{
|
||||
BuffManager Make(byte lifeTraining, out PlayerVitalsCache vitals, out LegacyUiSettings s)
|
||||
|
|
@ -293,6 +321,56 @@ internal static class VitalsTests
|
|||
}
|
||||
}
|
||||
|
||||
// The owner, 2026-11-07: a melee character with no stamina kit or potion swapped weapons for the
|
||||
// wand and back (about 5.5 s) for every between-fights stamina top-off. Out of a fight and over
|
||||
// Re-stam At it now waits for regeneration; under Re-stam At, in Magic stance, or with a potion,
|
||||
// stamina is handled as before.
|
||||
private static void NoWandSwapForStaminaTopOff()
|
||||
{
|
||||
const uint Tincture = 0x80001234;
|
||||
BuffManager Rig(int mode, int stamina, bool potion, out PlayerVitalsCache vitals)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = mode;
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, STypeLife)] = (400, 2);
|
||||
if (potion) FakeHost.Names[Tincture] = "Stamina Tincture";
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 0, TopOffMana = 0, RestamAt = 30, RestamTo = 90, TopOffStam = 60,
|
||||
UsePotions = potion, EnableBuffing = false };
|
||||
if (potion) s.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Tincture), Name = "Stamina Tincture", Type = "Stamina" });
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = (uint)stamina, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, vitals) { InCombatOverride = () => false };
|
||||
b.SetCharacterSkills(skills);
|
||||
b.SetWorldObjectCache(FakeHost.MakeCache(host, Player, potion ? new[] { Tincture } : System.Array.Empty<uint>()));
|
||||
return b;
|
||||
}
|
||||
|
||||
var melee = Rig(CombatMode.Melee, 50, potion: false, out _);
|
||||
Check.False(melee.CheckVitals(), "melee, idle, 50% under Top Off 60, nothing but the spell: nothing to do");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no Revitalize");
|
||||
Check.False(FakeHost.Wields.Count > 0 || FakeHost.CombatModeRequests.Contains(CombatMode.Magic), "and no wand swap or Magic stance");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("no wand swap for it out of a fight")), "logged why");
|
||||
|
||||
melee = Rig(CombatMode.Melee, 25, potion: false, out _);
|
||||
Check.True(melee.CheckVitals(), "melee, idle, 25% under Re-stam At 30: the recharge goes (wand swap and Revitalize)");
|
||||
|
||||
var drink = Rig(CombatMode.Melee, 50, potion: true, out _);
|
||||
Check.True(drink.CheckVitals(), "melee, idle, 50% with a tincture: still topped off");
|
||||
Check.True(FakeHost.Uses.Contains(Tincture), "the tincture is drunk");
|
||||
|
||||
var caster = Rig(CombatMode.Magic, 50, potion: false, out _);
|
||||
Check.True(caster.CheckVitals(), "in Magic stance (no swap needed): the top-off casts as before");
|
||||
Check.True(FakeHost.Casts.Count > 0, "Revitalize is cast");
|
||||
}
|
||||
|
||||
// Report 2026-10-10: 200+ Stamina Tinctures, and RynthAi stopped drinking them whenever the stack
|
||||
// the rule was added from ran out, until the player added the next stack by hand.
|
||||
private static void ListedPotionNextStack()
|
||||
|
|
|
|||
145
Tools/RynthCore.RynthAiHostTests/Tests/VtRingImportTests.cs
Normal file
145
Tools/RynthCore.RynthAiHostTests/Tests/VtRingImportTests.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.MiniRemote;
|
||||
using RynthCore.Plugin.RynthAi.ProfileImport;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// A VTank .usd import brings VTank's ring options along with the monsters' Ring ticks (2026-11-06):
|
||||
// MinimumRingTargets -> Min Ring Targets, RingDistance (landblock units, x240 = yards, as every
|
||||
// VTank distance RynthAi reads) -> Ring Range, each held to the settings window's range. A value
|
||||
// the profile lacks leaves the setting alone. Only an import the player starts sets them.
|
||||
// Fixtures\vtank-rings*.usd: a MyMonsters table (DEFAULT with Ring on) and then the options.
|
||||
internal static class VtRingImportTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("vtank ring import: the options read, converted (landblock units x240) and held to the settings' range", ReadAndConvert);
|
||||
r.Add("vtank ring import (Hub): preview lists them, the import sets them and says so; none in the profile = left alone", HubImport);
|
||||
r.Add("vtank ring import (profile importer): set when the profiles agree, left alone when they differ or have none", ProfileImporter);
|
||||
}
|
||||
|
||||
private static string Fixture(string name) => Path.Combine(AppContext.BaseDirectory, "Fixtures", name);
|
||||
|
||||
private static void ReadAndConvert()
|
||||
{
|
||||
var r = VtRingSettings.Read(File.ReadAllLines(Fixture("vtank-rings.usd")));
|
||||
Check.Eq(r.MinRingTargets, 2, "MinimumRingTargets 2");
|
||||
Check.Eq(r.RingRange, 4, "RingDistance 0.0166667 landblock = 4 yards");
|
||||
Check.Eq(r.Describe(), "Min Ring Targets 2, Ring Range 4 (from the profile)", "the summary");
|
||||
Check.Eq(r.Clamped.Count, 0, "nothing held");
|
||||
|
||||
var none = VtRingSettings.Read(File.ReadAllLines(Fixture("vtank-rings-none.usd")));
|
||||
Check.False(none.Any, "a profile without them: none (AttackDistance and the rest are not ring options)");
|
||||
Check.Eq(none.Describe(), "", "nothing to say");
|
||||
|
||||
var clamp = VtRingSettings.Read(File.ReadAllLines(Fixture("vtank-rings-clamp.usd")));
|
||||
Check.Eq(clamp.MinRingTargets, 20, "MinimumRingTargets 30 held to 20");
|
||||
Check.Eq(clamp.RingRange, 50, "RingDistance 0.3 = 72 yards, held to 50");
|
||||
Check.Eq(string.Join("; ", clamp.Clamped), "Min Ring Targets 30 -> 20; Ring Range 72 -> 50", "the holds are noted");
|
||||
|
||||
var one = VtRingSettings.Read(File.ReadAllLines(Fixture("vtank-rings-mintargets-only.usd")));
|
||||
Check.Eq(one.MinRingTargets, 1, "MinimumRingTargets 0 held to 1");
|
||||
Check.Eq(one.RingRange, null, "no RingDistance: no Ring Range");
|
||||
|
||||
// The conversion is the meta path's: a meta's RingDistance gives the same Ring Range.
|
||||
string[] Lines(string d) => new[] { "s", "RingDistance", "d", d };
|
||||
Check.Eq(VtRingSettings.Read(Lines("0.0208333333333333")).RingRange, 5, "5/240 landblock = 5");
|
||||
Check.Eq(VtRingSettings.Read(Lines("0.00833333333333333")).RingRange, 2, "2/240 landblock = 2");
|
||||
Check.Eq(VtRingSettings.Read(Lines("0.0188333333333333")).RingRange, 5, "4.52 yards rounds to 5");
|
||||
Check.Eq(VtRingSettings.Read(Lines("7")).RingRange, 7, "a value over 1 is yards already (typed by hand), as the meta path reads it");
|
||||
Check.Eq(VtRingSettings.Read(Lines("0")).RingRange, 1, "0 held to 1");
|
||||
Check.Eq(VtRingSettings.Read(new[] { "x", "RingDistance", "d", "0.02" }).RingRange, null, "only an option row (an 's' line before the name)");
|
||||
}
|
||||
|
||||
private sealed class HubRig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { MinRingTargets = 4, RingRange = 5 };
|
||||
public readonly VTankUsdImporter Usd;
|
||||
public int Saves;
|
||||
|
||||
public HubRig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var host = FakeHost.Create(Player);
|
||||
string dir = Path.Combine(Program.TempRoot, "vtank-ring-import");
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
Directory.CreateDirectory(dir);
|
||||
var store = new MiniRemoteStore(dir);
|
||||
var cache = FakeHost.MakeCache(host, Player, Array.Empty<uint>());
|
||||
var ctx = new MiniRemoteContext(host, store.Load(), store, new MiniRemoteInventory(host, () => cache),
|
||||
new ServerHubClient(host), () => S)
|
||||
{ SaveCombatSettings = () => Saves++ };
|
||||
Usd = new VTankUsdImporter(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
private static void HubImport()
|
||||
{
|
||||
var rig = new HubRig();
|
||||
rig.Usd.Preview(Fixture("vtank-rings.usd"));
|
||||
Check.True(rig.Usd.Status.Contains("ring settings: Min Ring Targets 2 (now 4), Ring Range 4 (now 5)"), $"the preview lists them: {rig.Usd.Status}");
|
||||
Check.Eq((rig.S.MinRingTargets, rig.S.RingRange), (4, 5), "a preview changes nothing");
|
||||
rig.Usd.Apply();
|
||||
Check.Eq((rig.S.MinRingTargets, rig.S.RingRange), (2, 4), "the import sets them");
|
||||
Check.True(rig.Usd.Status.Contains("set Min Ring Targets 2, Ring Range 4 (from the profile)"), $"and says so: {rig.Usd.Status}");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Min Ring Targets 2, Ring Range 4 (from the profile)")), "in the chat too");
|
||||
Check.True(rig.S.MonsterRules.Any(m => m.UseRing), "the monsters' Ring ticks came along");
|
||||
Check.Eq(rig.Saves, 1, "saved once");
|
||||
|
||||
var none = new HubRig();
|
||||
none.S.MinRingTargets = 3; none.S.RingRange = 9;
|
||||
none.Usd.Preview(Fixture("vtank-rings-none.usd"));
|
||||
Check.True(none.Usd.Status.Contains("no ring settings in the profile"), $"the preview says there are none: {none.Usd.Status}");
|
||||
none.Usd.Apply();
|
||||
Check.Eq((none.S.MinRingTargets, none.S.RingRange), (3, 9), "none in the profile: left alone");
|
||||
Check.True(none.Usd.Status.Contains("ring settings left alone"), $"and says so: {none.Usd.Status}");
|
||||
|
||||
var half = new HubRig();
|
||||
half.Usd.Preview(Fixture("vtank-rings-mintargets-only.usd"));
|
||||
half.Usd.Apply();
|
||||
Check.Eq((half.S.MinRingTargets, half.S.RingRange), (1, 5), "only Min Ring Targets in the profile: Ring Range left alone");
|
||||
|
||||
var clamp = new HubRig();
|
||||
clamp.Usd.Preview(Fixture("vtank-rings-clamp.usd"));
|
||||
clamp.Usd.Apply();
|
||||
Check.Eq((clamp.S.MinRingTargets, clamp.S.RingRange), (20, 50), "held to the settings' range");
|
||||
}
|
||||
|
||||
private static void ProfileImporter()
|
||||
{
|
||||
var s = new LegacyUiSettings { MinRingTargets = 4, RingRange = 5 };
|
||||
var result = new VirindiTankProfileImporter.Result();
|
||||
VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings.usd"), s, result);
|
||||
Check.Eq((s.MinRingTargets, s.RingRange), (4, 5), "reading a profile changes nothing by itself");
|
||||
VirindiTankProfileImporter.ApplyRingSettings(s, result);
|
||||
Check.Eq((s.MinRingTargets, s.RingRange), (2, 4), "one profile: its values");
|
||||
Check.Eq(result.RingSettingsSet, "Min Ring Targets 2, Ring Range 4 (from the profile)", "the summary");
|
||||
Check.True(result.LogLines.Any(l => l.Contains("Ring settings: set Min Ring Targets 2, Ring Range 4")), "the import's lines say it");
|
||||
|
||||
// Two profiles (two characters) that disagree: neither wins.
|
||||
var s2 = new LegacyUiSettings { MinRingTargets = 4, RingRange = 5 };
|
||||
var r2 = new VirindiTankProfileImporter.Result();
|
||||
VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings.usd"), s2, r2);
|
||||
VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings-clamp.usd"), s2, r2);
|
||||
VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings-none.usd"), s2, r2);
|
||||
VirindiTankProfileImporter.ApplyRingSettings(s2, r2);
|
||||
Check.Eq((s2.MinRingTargets, s2.RingRange), (4, 5), "profiles that differ: left alone");
|
||||
Check.True(r2.LogLines.Any(l => l.Contains("the profiles differ") && l.Contains("left alone")), "and it says so");
|
||||
Check.Eq(r2.RingSettingsSet, "", "nothing set");
|
||||
|
||||
// Only profiles without ring options: nothing found, nothing said or set.
|
||||
var s3 = new LegacyUiSettings { MinRingTargets = 3, RingRange = 7 };
|
||||
var r3 = new VirindiTankProfileImporter.Result();
|
||||
VirindiTankProfileImporter.TryMergeUsdMyMonstersScf(Fixture("vtank-rings-none.usd"), s3, r3);
|
||||
VirindiTankProfileImporter.ApplyRingSettings(s3, r3);
|
||||
Check.Eq((s3.MinRingTargets, s3.RingRange), (3, 7), "none in the profiles: left alone");
|
||||
Check.False(r3.LogLines.Any(l => l.StartsWith("Ring settings")), "nothing to say");
|
||||
}
|
||||
}
|
||||
263
Tools/RynthCore.RynthAiHostTests/Tests/WieldBanTests.cs
Normal file
263
Tools/RynthCore.RynthAiHostTests/Tests/WieldBanTests.cs
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The false "it never reached your hand" ban: combat's wield of a weapon landed, buffing swapped
|
||||
/// it out for the wand before combat looked again, each of those wields counted as a failed try,
|
||||
/// and after the third the weapon was left out of the choice for 30 min. The engine's equipment
|
||||
/// list (FakeHost.Equipped, API v87) plays the server's wield messages here. A wield that truly
|
||||
/// never shows in the list must still be banned.
|
||||
/// </summary>
|
||||
internal static class WieldBanTests
|
||||
{
|
||||
private const uint Player = 0x50000C01;
|
||||
private const uint Blade = 0x800484AA, Wand = 0x80048401, Nodachi = 0x80048402;
|
||||
private const uint MeleeSlot = 0x00100000, HeldSlot = 0x01000000, ShieldSlot = 0x00200000;
|
||||
private const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("wield ban: a weapon seen wielded between combat's looks is not banned, its tries start over", SeenWieldedNotBanned);
|
||||
r.Add("wield ban: no ban while the equipment list shows the weapon at the give-up", ListShowsItAtGiveUp);
|
||||
r.Add("wield ban: a wield that never shows in the list is still banned", NeverShownStillBanned);
|
||||
r.Add("wield ban: one sighting, then three wields never seen: banned (a new run forgets the sighting)", SeenOnceThenNeverBanned);
|
||||
r.Add("wield ban: a weapon in the shield slot is not a main-hand sighting, it still rests", ShieldSlotNotASighting);
|
||||
r.Add("wield ban: the server's 'skill too low' still bans at once", SkillTooLowStillBans);
|
||||
r.Add("wield ban: the plugin's sampler call alone resets the tries (no heartbeat)", DirectSamplerResetsTries);
|
||||
r.Add("wield ban: RynthAiPlugin's tick samples wields before the buffing hold returns", PluginSamplesBeforeBuffHold);
|
||||
r.Add("wield ban: a stale try count stops the equipment list sampling", StaleCountStopsSampling);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly CombatManager C;
|
||||
private readonly MethodInfo _send = typeof(CombatManager).GetMethod("MarkWieldSent", F)!;
|
||||
private readonly MethodInfo _step = typeof(CombatManager).GetMethod("SwapStep", F)!;
|
||||
|
||||
public Rig(bool equipped = true, bool weenieErrors = false)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.EquippedCalls = equipped;
|
||||
FakeHost.WeenieErrorCalls = weenieErrors;
|
||||
FakeHost.Names[Blade] = "Test Blade";
|
||||
FakeHost.Names[Wand] = "Fire Wand";
|
||||
FakeHost.Names[Nodachi] = "Nodachi";
|
||||
var host = FakeHost.Create();
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Blade, Wand, Nodachi });
|
||||
C = new CombatManager(host, new LegacyUiSettings(), cache);
|
||||
C.SetPlayerId(Player);
|
||||
C.SwapTracker.ResolveMs = 0; // each look after a send resolves it (no real 2.5 s waits)
|
||||
Hold(Wand, HeldSlot);
|
||||
}
|
||||
|
||||
/// <summary>What the server says is wielded now: only <paramref name="id"/>.</summary>
|
||||
public void Hold(uint id, uint slot)
|
||||
{
|
||||
FakeHost.Equipped.Clear();
|
||||
FakeHost.Equipped[id] = slot;
|
||||
EquippedState.Invalidate();
|
||||
}
|
||||
|
||||
public void Send(uint id, uint from) => _send.Invoke(C, new object[] { unchecked((int)id), unchecked((int)from) });
|
||||
public WeaponSwapTracker.Step Step(uint id, uint inHand) =>
|
||||
(WeaponSwapTracker.Step)_step.Invoke(C, new object[] { unchecked((int)id), unchecked((int)inHand) })!;
|
||||
public bool Banned(uint id) => C.SkillTooLowFor(unchecked((int)id));
|
||||
public int Tries(uint id) => C.SwapTracker.TriesFor(unchecked((int)id));
|
||||
}
|
||||
|
||||
private static bool NeverReachedLogged() => FakeHost.Logs.Any(l => l.Contains("never reached your hand"));
|
||||
|
||||
/// <summary>A weapon that lands, is swapped out for the wand by buffing, and lands again is never banned: three times over.</summary>
|
||||
private static void SeenWieldedNotBanned()
|
||||
{
|
||||
var rig = new Rig();
|
||||
try
|
||||
{
|
||||
for (int i = 1; i <= 3; i++)
|
||||
{
|
||||
rig.Send(Blade, Wand); // combat sends the wield
|
||||
rig.Hold(Blade, MeleeSlot); // the server wields it
|
||||
rig.C.OnHeartbeat(); // a tick samples the equipment list
|
||||
Check.Eq(rig.Tries(Blade), 0, $"wield {i}: seen in hand, its try count starts over");
|
||||
rig.Hold(Wand, HeldSlot); // buffing swaps it out for the wand
|
||||
rig.Step(Blade, Wand); // combat looks: the wand is in hand
|
||||
}
|
||||
Check.False(rig.Banned(Blade), "three wields that landed: not left out of the weapon choice");
|
||||
Check.False(NeverReachedLogged(), "no 'never reached your hand' line");
|
||||
}
|
||||
finally { EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
/// <summary>The give-up itself reads the list, and a list holding the weapon is no ban.</summary>
|
||||
private static void ListShowsItAtGiveUp()
|
||||
{
|
||||
var rig = new Rig();
|
||||
try
|
||||
{
|
||||
for (int i = 1; i <= 3; i++)
|
||||
{
|
||||
rig.Send(Blade, Wand);
|
||||
// No tick samples between the wields here. At the third look the server's list
|
||||
// holds the weapon (the hand read combat passed in is stale).
|
||||
if (i == 3) { FakeHost.Equipped[Blade] = MeleeSlot; EquippedState.Invalidate(); }
|
||||
rig.Step(Blade, Wand);
|
||||
}
|
||||
Check.False(rig.Banned(Blade), "the list shows it wielded at the give-up: not banned");
|
||||
Check.False(NeverReachedLogged(), "no 'never reached your hand' line");
|
||||
|
||||
// Control: no equipment list from the engine, nothing is known: no ban either way (as before).
|
||||
var blind = new Rig(equipped: false);
|
||||
for (int i = 1; i <= 3; i++) { blind.Send(Blade, Wand); blind.Step(Blade, Wand); }
|
||||
Check.False(blind.Banned(Blade), "no equipment list: no 'never reached' ban");
|
||||
}
|
||||
finally { EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
/// <summary>A wield the client or server truly refuses (never in the list) still bans.</summary>
|
||||
private static void NeverShownStillBanned()
|
||||
{
|
||||
var rig = new Rig();
|
||||
try
|
||||
{
|
||||
for (int i = 1; i <= 3; i++)
|
||||
{
|
||||
rig.Send(Blade, Wand);
|
||||
rig.C.OnHeartbeat(); // ticks sample: only the wand, every time
|
||||
Check.Eq(rig.Tries(Blade), i, $"wield {i}: never seen, the try counts");
|
||||
rig.Step(Blade, Wand);
|
||||
}
|
||||
Check.True(rig.Banned(Blade), "three wields never seen in the list: left out of the weapon choice");
|
||||
Check.True(NeverReachedLogged(), "logged as 'never reached your hand'");
|
||||
}
|
||||
finally { EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A sighting counts for its own run of wields only. The weapon lands once (buffing swaps it
|
||||
/// out), then stops reaching the hand: three unseen wields still end in the ban, instead of
|
||||
/// three wields and an off-hand clear every 2 min forever.
|
||||
/// </summary>
|
||||
private static void SeenOnceThenNeverBanned()
|
||||
{
|
||||
var rig = new Rig();
|
||||
try
|
||||
{
|
||||
rig.Send(Blade, Wand);
|
||||
rig.Hold(Blade, MeleeSlot);
|
||||
rig.C.OnHeartbeat();
|
||||
Check.Eq(rig.Tries(Blade), 0, "the landed wield: seen, the count starts over");
|
||||
rig.Hold(Wand, HeldSlot);
|
||||
rig.Step(Blade, Wand);
|
||||
for (int i = 1; i <= 3; i++)
|
||||
{
|
||||
rig.Send(Blade, Wand);
|
||||
rig.C.OnHeartbeat(); // only the wand, every time
|
||||
rig.Step(Blade, Wand);
|
||||
}
|
||||
Check.True(rig.Banned(Blade), "three later wields never seen: left out of the weapon choice");
|
||||
Check.True(NeverReachedLogged(), "logged as 'never reached your hand'");
|
||||
}
|
||||
finally { EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only main-hand slots count (as InHandWeaponId reads them). A weapon chosen while it sits in
|
||||
/// the shield slot is not a landed wield: its tries count, and after three it rests instead
|
||||
/// of being sent again every 2.5 s.
|
||||
/// </summary>
|
||||
private static void ShieldSlotNotASighting()
|
||||
{
|
||||
var rig = new Rig();
|
||||
try
|
||||
{
|
||||
FakeHost.Equipped[Blade] = ShieldSlot; // the off-hand slot, next to the wand
|
||||
EquippedState.Invalidate();
|
||||
var last = WeaponSwapTracker.Step.Swap;
|
||||
for (int i = 1; i <= 3; i++)
|
||||
{
|
||||
rig.Send(Blade, Wand);
|
||||
rig.C.OnHeartbeat();
|
||||
Check.Eq(rig.Tries(Blade), i, $"wield {i}: the shield slot is no sighting, the try counts");
|
||||
last = rig.Step(Blade, Wand);
|
||||
}
|
||||
Check.Eq(last, WeaponSwapTracker.Step.Hold, "after three tries: rested, not sent again");
|
||||
Check.Eq(rig.Step(Blade, Wand), WeaponSwapTracker.Step.Hold, "still resting on the next look");
|
||||
}
|
||||
finally { EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
/// <summary>The server's own "skill too low" answer is untouched by the sightings: banned at once.</summary>
|
||||
private static void SkillTooLowStillBans()
|
||||
{
|
||||
var rig = new Rig(weenieErrors: true);
|
||||
try
|
||||
{
|
||||
rig.Send(Nodachi, Wand);
|
||||
FakeHost.WeenieError(CombatManager.SkillTooLowErr, 0x00A0, Nodachi);
|
||||
rig.C.OnHeartbeat();
|
||||
rig.Step(Nodachi, Wand);
|
||||
Check.True(rig.Banned(Nodachi), "the server refused it: left out of the weapon choice");
|
||||
}
|
||||
finally { EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
/// <summary>The sampler the plugin calls every tick works without combat's heartbeat.</summary>
|
||||
private static void DirectSamplerResetsTries()
|
||||
{
|
||||
var rig = new Rig();
|
||||
try
|
||||
{
|
||||
rig.Send(Blade, Wand);
|
||||
Check.Eq(rig.Tries(Blade), 1, "setup: one wield sent");
|
||||
rig.Hold(Blade, MeleeSlot);
|
||||
rig.C.NoteSwapWieldsSeen();
|
||||
Check.Eq(rig.Tries(Blade), 0, "the sampler alone sees it in hand: the count starts over");
|
||||
}
|
||||
finally { EquippedState.Invalidate(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Source pin. The buffing hold returns from OnTick before combat's heartbeat runs, so the
|
||||
/// plugin's own sampler call must come after the buff step and before that hold.
|
||||
/// </summary>
|
||||
private static void PluginSamplesBeforeBuffHold()
|
||||
{
|
||||
string? root = AppContext.BaseDirectory;
|
||||
while (root != null && !Directory.Exists(Path.Combine(root, "Plugins"))) root = Path.GetDirectoryName(root);
|
||||
Check.True(root != null, "found the repo (a Plugins folder above the test output)");
|
||||
if (root == null) return;
|
||||
string src = File.ReadAllText(Path.Combine(root, "Plugins", "RynthCore.Plugin.RynthAi", "RynthAiPlugin.cs"));
|
||||
int buffStep = src.IndexOf("Guard(TickStep.BuffsAndVitals, () => _buffManager?.OnHeartbeat());", StringComparison.Ordinal);
|
||||
int sample = src.IndexOf("_combatManager?.NoteSwapWieldsSeen();", StringComparison.Ordinal);
|
||||
int buffHold = src.IndexOf("if (settings.IsMacroRunning && _activity == BotActivity.Buffing)", StringComparison.Ordinal);
|
||||
Check.True(buffStep >= 0, "the buff step is in OnTick");
|
||||
Check.True(buffHold >= 0, "the buffing hold is in OnTick");
|
||||
Check.True(sample >= 0, "OnTick calls NoteSwapWieldsSeen");
|
||||
Check.True(sample > buffStep && sample < buffHold, "after the buff step and before the buffing hold's return");
|
||||
int holdReturn = buffHold >= 0 ? src.IndexOf("return;", buffHold, StringComparison.Ordinal) : -1;
|
||||
Check.True(holdReturn > buffHold, "the buffing hold returns early (what makes the call's place matter)");
|
||||
}
|
||||
|
||||
/// <summary>A try count left behind with no send for 2 min no longer keeps the sampler reading every tick.</summary>
|
||||
private static void StaleCountStopsSampling()
|
||||
{
|
||||
var tr = new WeaponSwapTracker();
|
||||
var t = new DateTime(2026, 11, 2, 12, 0, 0);
|
||||
tr.Sent(5, 1, t);
|
||||
tr.Next(5, 1, t.AddSeconds(3)); // not seen in 2.5 s: the try stays counted
|
||||
Check.Eq(tr.PendingId, 0, "setup: nothing in flight");
|
||||
Check.Eq(tr.TriesFor(5), 1, "setup: one try counted");
|
||||
Check.True(tr.HasAttemptsAt(t.AddSeconds(10)), "10 s after the send: sampled");
|
||||
Check.False(tr.HasAttemptsAt(t.AddMinutes(3)), "3 min after the last send: not sampled");
|
||||
tr.Sent(5, 1, t.AddMinutes(3));
|
||||
Check.True(tr.HasAttemptsAt(t.AddMinutes(3)), "a new send: sampled again");
|
||||
}
|
||||
}
|
||||
|
|
@ -37,6 +37,7 @@ internal static class WorldCacheTypedTests
|
|||
r.Add("world cache: corpses: named at once, and a Container-typed one named late is rescued", Corpses);
|
||||
r.Add("world cache: an Unknown whose type arrives late is filed as the item it is", LateType);
|
||||
r.Add("world cache: scrolls, slot-typed weapons, chests, lifestones; signs stay scenery", LootClasses);
|
||||
r.Add("world cache: a chest created before its position was known lands on the landscape once it has one", LooseChestWithoutPosition);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────
|
||||
|
|
@ -112,6 +113,32 @@ internal static class WorldCacheTypedTests
|
|||
Check.False(FakeHost.Logs.Any(l => l.Contains("stuck Unknown", StringComparison.Ordinal)), "nothing left for the Unknown re-probe");
|
||||
}
|
||||
|
||||
/// <summary>The Dreamweave dig's Unearthed Cache (2026-11-02): a container created with no position yet, nobody holding
|
||||
/// it. It was filed as carried for good, so "use <name>" and Loot by name never found it.</summary>
|
||||
private static void LooseChestWithoutPosition()
|
||||
{
|
||||
World();
|
||||
uint cache = _next++;
|
||||
FakeHost.Names[cache] = "Unearthed Cache";
|
||||
FakeHost.ItemTypes[cache] = TContainer;
|
||||
FakeHost.Containers[cache] = 0; // nobody holds it
|
||||
FakeHost.NotAttackable.Add(cache);
|
||||
uint bag = _next++; // a side pack we carry, also created before it had a position
|
||||
FakeHost.Names[bag] = "Caravaneer's Pack";
|
||||
FakeHost.ItemTypes[bag] = TContainer;
|
||||
FakeHost.Containers[bag] = Player;
|
||||
FakeHost.NotAttackable.Add(bag);
|
||||
|
||||
var c = Classify(cache, bag);
|
||||
Check.True(InInventory(c, cache), "no position yet: filed with what is carried (as before)");
|
||||
|
||||
FakeHost.Positions[cache] = (Here, 98f, 98f, 0f);
|
||||
FakeHost.Positions[bag] = (Here, 99f, 99f, 0f);
|
||||
Reclassify(c);
|
||||
Where(c, cache, AcObjectClass.Container, false, true, "the cache once it has a position");
|
||||
Where(c, bag, AcObjectClass.Container, true, false, "a pack we carry stays in the inventory");
|
||||
}
|
||||
|
||||
private static void OtherPlayersGear()
|
||||
{
|
||||
World();
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@
|
|||
<!-- Learned per-monster damage (System only), for the Aelrynth difficulty-tier tests. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\MonsterDamageStore.cs" Link="Linked\MonsterDamageStore.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\PlayerWeenies.cs" Link="Linked\PlayerWeenies.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\CreatureData\ShieldFacing.cs" Link="Linked\ShieldFacing.cs" />
|
||||
<!-- Loot: the measured loot-timer baseline and its [LootSettings] log line. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\LootBaseline.cs" Link="Linked\LootBaseline.cs" />
|
||||
<!-- RynthChat: the channel classifier (no dependencies). -->
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ internal static partial class Program
|
|||
TestLumChatLines();
|
||||
TestIltBankLum();
|
||||
TestIltDepositExpires();
|
||||
TestServerProfileBankLum();
|
||||
TestChatFallbackUntilBank();
|
||||
TestAelrynthAndRetailLum();
|
||||
TestLumLast5Min();
|
||||
|
|
@ -94,6 +95,29 @@ internal static partial class Program
|
|||
Eq(s.LumTotal, 400L, "an expired deposit line no longer eats income");
|
||||
}
|
||||
|
||||
// A server that banks earned luminance where the client can't read it: its server plugin reads the
|
||||
// bank once a minute and the tracker passes that reading in as the bank (2026-11-02). The same value
|
||||
// comes in on every poll in between; the character's luminance is never sent.
|
||||
private static void TestServerProfileBankLum()
|
||||
{
|
||||
var s = new SessionStats();
|
||||
s.Reset(S0);
|
||||
DateTime t = S0;
|
||||
void Polls(long bank, int seconds)
|
||||
{
|
||||
for (int i = 0; i < seconds * 2; i++) { t = t.AddSeconds(0.5); s.Sample(new SessionSample(1, null, bank, null, null, null), t); }
|
||||
}
|
||||
Polls(2_000_000, 60);
|
||||
Eq(s.LumTotal, 0L, "profile bank: the first reading is the baseline");
|
||||
Check(s.BankTracked, "profile bank: the bank is tracked");
|
||||
for (int minute = 1; minute <= 59; minute++) Polls(2_000_000 + minute * 10_000L, 60);
|
||||
Eq(s.LumTotal, 590_000L, "profile bank: each minute's rise counts once");
|
||||
Check(Math.Abs(s.View(t).LumPerHour - 590_000) < 1, $"profile bank: about 590,000 an hour ({s.View(t).LumPerHour:0})");
|
||||
Polls(100_000, 60);
|
||||
Eq(s.LumTotal, 590_000L, "profile bank: spending is a drop, not negative");
|
||||
Polls(150_000, 60);
|
||||
Eq(s.LumTotal, 640_000L, "profile bank: and the next rise counts");
|
||||
}
|
||||
// "You've banked" counts only until a bank property is read; then the bank covers it.
|
||||
private static void TestChatFallbackUntilBank()
|
||||
{
|
||||
|
|
|
|||
216
Tools/RynthDefective.Tests/BusyClearTests.cs
Normal file
216
Tools/RynthDefective.Tests/BusyClearTests.cs
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
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
|
||||
{
|
||||
// "Shortcuts clear a stuck busy state" (2026-11-04, DefSettings.ClearStuckBusy): when a press clears
|
||||
// the busy count first (BusyClearRule: only the count holds it, nothing real in flight), the use
|
||||
// controller's clear-then-use (once per press, logged), off by default, the setting, the command.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void BusyClearDecisions()
|
||||
{
|
||||
Check(!new DefSettings().ClearStuckBusy, "off by default");
|
||||
|
||||
// A count of 2 that moved a second ago, nothing of ours for a long time, no gesture, no RynthAi.
|
||||
var f = new BusyFacts(Count: 2, CountSteadyMs: 1000, Leftover: 0, SinceOwnSendMs: 60_000,
|
||||
Animating: false, AnimatingMs: 0, BotWaiting: null, BotSteadyMs: 0);
|
||||
bool Clear(in BusyFacts x, BusyHold hold = BusyHold.Busy, bool on = true, bool inFlight = false, bool answered = true, long sinceBusy = 60_000) =>
|
||||
BusyClearRule.ShouldClear(on, hold, x, inFlight, answered, sinceBusy);
|
||||
|
||||
Check(Clear(f), "only the count holds it: clear");
|
||||
Check(!Clear(f, on: false), "the option off: never");
|
||||
Check(!Clear(f, BusyHold.Animation) && !Clear(f, BusyHold.Bot) && !Clear(f, BusyHold.None), "held by something else, or not held: no");
|
||||
Check(!Clear(f with { Count = 0 }), "no count: nothing to clear");
|
||||
Check(!Clear(f, inFlight: true), "our own use in flight: no");
|
||||
Check(!Clear(f with { SinceOwnSendMs = 1000 }, answered: false), "our own last use, unanswered, just now: no (it may be the count)");
|
||||
Check(Clear(f with { SinceOwnSendMs = 1000 }, answered: true), "our own last use was answered: the count isn't it");
|
||||
Check(Clear(f with { SinceOwnSendMs = BusyRule.OwnTrustMs }, answered: false), "unanswered but long ago: not ours any more");
|
||||
Check(!Clear(f with { Animating = true, AnimatingMs = 100 }), "a gesture animating: no");
|
||||
Check(!Clear(f with { Animating = true, AnimatingMs = 60_000 }), "even one that has 'animated' for a minute: no");
|
||||
Check(!Clear(f with { BotPaced = true, BotPacedMs = 100 }), "RynthAi's own action unanswered: no");
|
||||
Check(!Clear(f with { BotPaced = true, BotPacedMs = 60_000 }), "even a stale one: no");
|
||||
Check(Clear(f with { BotPaced = false, BotWaiting = true, BotSteadyMs = 100 }),
|
||||
"RynthAi says it has nothing in flight: its 'waiting' bit is its copy of the count");
|
||||
Check(!Clear(f with { BotWaiting = true, BotSteadyMs = 1000 }), "a RynthAi that can't say, waiting on the server just now: no");
|
||||
Check(Clear(f with { BotWaiting = true, BotSteadyMs = BusyRule.BotTrustMs }), "its bit stuck for longer than any of its actions: yes");
|
||||
Check(!Clear(f, sinceBusy: 2000), "the server said 'too busy' 2 s ago: it really is busy, no");
|
||||
Check(Clear(f, sinceBusy: BusyClearRule.ServerBusyRecentMs), "5 s later: yes");
|
||||
}
|
||||
|
||||
private static void UseClearStuckBusy()
|
||||
{
|
||||
ItemRef kit = ItemRef.From(Kit(0x10));
|
||||
|
||||
// Off (the default): a login's count holds the press as before, and nothing is reset.
|
||||
Harness h = With(Kit(0x10));
|
||||
h.World.BusyCount = 2;
|
||||
h.Tick();
|
||||
h.Slot(kit);
|
||||
h.Ticks(3, 1000);
|
||||
Check(h.World.Sent.Count == 0 && h.World.Clears == 0, "off: held, nothing cleared");
|
||||
h.Tick(1000);
|
||||
Eq(string.Join("|", h.World.Sent), "useon 10 me", "off: it goes once the count is a leftover, as before");
|
||||
Eq(h.World.Clears, 0, "off: the count is never reset");
|
||||
|
||||
// On: the clear, then the use as soon as the reset reads.
|
||||
h = With(Kit(0x10));
|
||||
h.Use.Settings.ClearStuckBusy = true;
|
||||
h.World.BusyCount = 2;
|
||||
h.Tick();
|
||||
h.Slot(kit);
|
||||
h.Tick(50);
|
||||
Check(h.World.Clears == 1 && h.World.Sent.Count == 0, "on: cleared first, nothing sent yet");
|
||||
Check(h.Logged.Any(l => l.Contains("held only by the client's busy count (2") && l.Contains("as /ra clearbusy does")), "the clear is logged: " + string.Join(";", h.Logged));
|
||||
Check(h.Said.Any(s => s.Contains("clearing a stuck busy state")), "and on the status line");
|
||||
h.Tick(50);
|
||||
Eq(string.Join("|", h.World.Sent), "useon 10 me", "the reset read: the kit goes at once");
|
||||
Eq(h.World.Clears, 1, "once for the press");
|
||||
Eq(h.Warned.Count, 0, "no warning");
|
||||
|
||||
// The next press gets its own (once per press, not once ever).
|
||||
h.World.Answer();
|
||||
h.Tick(100);
|
||||
h.World.BusyCount = 1; // something raises it again
|
||||
h.Tick(300);
|
||||
h.Slot(kit);
|
||||
h.Tick(50);
|
||||
Eq(h.World.Clears, 2, "a new press held by the count: one more clear");
|
||||
h.Tick(50);
|
||||
Eq(h.World.Sent.Count, 2, "and it goes");
|
||||
|
||||
// The reset doesn't take: the press waits the settle time, then the count is a leftover and it goes.
|
||||
h = With(Kit(0x10));
|
||||
h.Use.Settings.ClearStuckBusy = true;
|
||||
h.World.ClearLands = false;
|
||||
h.World.BusyCount = 2;
|
||||
h.Tick();
|
||||
h.Slot(kit);
|
||||
h.Tick(50);
|
||||
h.Tick(100);
|
||||
Check(h.World.Clears == 1 && h.World.Sent.Count == 0, "the count still reads 2: waiting for the reset");
|
||||
h.Tick(UseController.ClearSettleMs);
|
||||
Eq(string.Join("|", h.World.Sent), "useon 10 me", "after the settle time it goes: what is left is a leftover");
|
||||
Eq(h.World.Clears, 1, "not cleared twice");
|
||||
Eq(h.Use.Busy.Leftover, 2, "2 is the leftover");
|
||||
|
||||
// An engine that can't reset: logged, and the usual rules.
|
||||
h = With(Kit(0x10));
|
||||
h.Use.Settings.ClearStuckBusy = true;
|
||||
h.World.CanClear = false;
|
||||
h.World.BusyCount = 2;
|
||||
h.Tick();
|
||||
h.Slot(kit);
|
||||
h.Ticks(3, 1000);
|
||||
Check(h.World.Sent.Count == 0 && h.Logged.Count(l => l.Contains("can't reset it")) == 1, "can't clear: said once in the log, held as usual");
|
||||
h.Tick(1000);
|
||||
Eq(h.World.Sent.Count, 1, "and goes when the usual rules let it");
|
||||
|
||||
// Never with something real in flight: a gesture, RynthAi's own action, the server's 'too busy'.
|
||||
h = With(Kit(0x10));
|
||||
h.Use.Settings.ClearStuckBusy = true;
|
||||
h.World.BusyCount = 2;
|
||||
h.World.Animating = true;
|
||||
h.Tick();
|
||||
h.Slot(kit);
|
||||
h.Ticks(3, 1000);
|
||||
Eq(h.World.Clears, 0, "a gesture animating: nothing cleared");
|
||||
|
||||
h = With(Kit(0x10));
|
||||
h.Use.Settings.ClearStuckBusy = true;
|
||||
h.World.YieldOn = true;
|
||||
h.World.BotOwnAction = true;
|
||||
h.World.BusyCount = 2;
|
||||
h.Tick();
|
||||
h.Slot(kit);
|
||||
h.Ticks(4, 1000);
|
||||
Eq(h.World.Clears, 0, "RynthAi's own action in flight: nothing cleared");
|
||||
|
||||
h = With(Kit(0x10));
|
||||
h.Use.Settings.ClearStuckBusy = true;
|
||||
h.Slot(kit);
|
||||
h.Tick();
|
||||
Eq(h.World.Sent.Count, 1, "sent");
|
||||
h.World.Answer(UseController.TooBusyError);
|
||||
h.World.BusyCount = 1;
|
||||
h.Tick(100);
|
||||
Check(h.Use.HasPending, "the server said 'too busy': one more try queued");
|
||||
h.Ticks(3, 1000);
|
||||
Eq(h.World.Clears, 0, "the server really is busy: nothing cleared for the retry");
|
||||
|
||||
// Our own last use answered, the count still up a moment (the engine's count catches up later):
|
||||
// the next press may clear it.
|
||||
h = With(Kit(0x10), Potion(0x11));
|
||||
h.Use.Settings.ClearStuckBusy = true;
|
||||
h.Slot(kit);
|
||||
h.Tick();
|
||||
h.World.BusyCount = 1;
|
||||
h.Tick(100);
|
||||
h.World.Answer();
|
||||
h.Tick(100);
|
||||
Check(!h.Use.InFlight, "the kit was answered");
|
||||
h.Slot(ItemRef.From(Potion(0x11)));
|
||||
h.Tick(300);
|
||||
Eq(h.World.Clears, 1, "the potion: the count is no action of ours in flight, cleared");
|
||||
h.Tick(50);
|
||||
Eq(h.World.Sent.Count, 2, "and the potion goes");
|
||||
}
|
||||
|
||||
private static void ClearBusySettingAndCommand()
|
||||
{
|
||||
// The character's file.
|
||||
var d = new DefData();
|
||||
d.Settings.ClearStuckBusy = true;
|
||||
Check(DefStore.Parse(JsonDocument.Parse(DefStore.ToJson(d)).RootElement).Settings.ClearStuckBusy, "saved and read: on");
|
||||
Check(!DefStore.Parse(JsonDocument.Parse("{\"settings\":{\"quantityBox\":true}}").RootElement).Settings.ClearStuckBusy, "a file from before: off");
|
||||
|
||||
// The command.
|
||||
DefCommand c = DefCommandParser.Parse("shortcuts clearbusy on");
|
||||
Check(c.Verb == DefVerb.Shortcuts && c.Text == "on", "/rdef shortcuts clearbusy on");
|
||||
Check(DefCommandParser.Parse("shortcuts clearbusy off").Text == "off", "off");
|
||||
Check(DefCommandParser.Parse("shortcuts ClearBusy OFF").Text == "off", "any case");
|
||||
c = DefCommandParser.Parse("shortcuts clearbusy");
|
||||
Check(c.Verb == DefVerb.Shortcuts && c.Text == "", "alone: says what it is");
|
||||
foreach (string wrong in new[] { "shortcuts", "shortcuts clearbusy maybe", "shortcuts frob on", "shortcuts clearbusy on now" })
|
||||
{
|
||||
c = DefCommandParser.Parse(wrong);
|
||||
Check(c.Verb == DefVerb.Error && c.Error.Contains("Usage", StringComparison.Ordinal), $"'/rdef {wrong}' answers how it's typed: {c.Error}");
|
||||
}
|
||||
Check(DefReplies.ClearBusy(true).Contains(": on") && DefReplies.ClearBusy(true).Contains("/ra clearbusy"), "the on reply says what it does");
|
||||
Check(DefReplies.ClearBusy(false).Contains(": off (the default)"), "the off reply");
|
||||
|
||||
// The settings window's box, and the script-window bar's.
|
||||
var b = new BarRig("clearbusy-settings");
|
||||
var host = new UiHost();
|
||||
UiWindow win = host.Add(new UiWindow("RynthDefective/Settings", "Defective Settings") { Visible = true, ShowInBar = false });
|
||||
var view = new BarSettingsView(b.S) { WindowShown = t => t == BarSettingsView.BarTitle ? true : null };
|
||||
win.Begin(); view.Draw(win); win.End();
|
||||
ParseAll(host, "settings window with the clear-busy box", out _);
|
||||
Check(Encoding.UTF8.GetString(win.Body).Contains("Shortcuts clear a stuck busy state"), "the box is in the settings");
|
||||
var w = new Windows("clearbusy-settings-events");
|
||||
w.Host.Add(win);
|
||||
int saves = b.R.Saves;
|
||||
w.SetBool(win, "set.clearbusy", true);
|
||||
Check(b.S.Settings.ClearStuckBusy && b.R.Saves > saves, "ticking it turns it on, saved");
|
||||
w.SetBool(win, "set.clearbusy", false);
|
||||
Check(!b.S.Settings.ClearStuckBusy, "and off");
|
||||
|
||||
var t = new Windows("clearbusy-old-bar");
|
||||
var panel = new SettingsPanel(t.S, () => { });
|
||||
UiWindow pw = t.Host.Add(new UiWindow("RynthDefective/Old", "Old") { Visible = true });
|
||||
pw.Begin(); panel.Draw(pw); pw.End();
|
||||
Check(Encoding.UTF8.GetString(pw.Body).Contains("Shortcuts clear a stuck busy state"), "the script-window bar's settings have it too");
|
||||
t.SetBool(pw, "set.clearbusy", true);
|
||||
Check(t.S.Settings.ClearStuckBusy, "and it works there");
|
||||
}
|
||||
}
|
||||
}
|
||||
152
Tools/RynthDefective.Tests/ClockTests.cs
Normal file
152
Tools/RynthDefective.Tests/ClockTests.cs
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthDefective.Clock;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthDefective.Tests
|
||||
{
|
||||
// The Day/Night timer (2026-11-04): Plugins/Shared/DerethClock.cs from a raw clock reading (no game).
|
||||
// With RynthAi's calendar offset the time of day is (raw + 3600) mod 7620 ticks, a tick a real second.
|
||||
internal static partial class Program
|
||||
{
|
||||
/// <summary>A raw clock reading <paramref name="into"/> ticks after Darktide began (a later day, so the raw is positive).</summary>
|
||||
private static double RawAt(double into, int day = 1) => DerethClock.TicksInDay * day + into - 3600;
|
||||
|
||||
private static void ClockDayNight()
|
||||
{
|
||||
Eq(DerethClock.TicksInDay, 7620.0, "a Dereth day is 7620 ticks");
|
||||
Eq(DerethClock.TicksInDay * DerethClock.SecondsPerTick / 60.0, 127.0, "= 2 h 7 min of real time");
|
||||
|
||||
// Darktide's start: night, dawn in 4 hours = 1905 s.
|
||||
DerethNow n = DerethClock.At(RawAt(0));
|
||||
Check(!n.IsDay, "Darktide: night");
|
||||
Eq(n.Hour, 0, "Darktide: hour 0");
|
||||
Eq(n.HourName, "Darktide", "Darktide: its name");
|
||||
Eq(n.SecondsToChange, 1905.0, "Darktide: dawn in 4 hours of 476.25 s");
|
||||
Eq(n.Next, "Day", "at night the day comes next");
|
||||
Eq(n.NextHourName, "Dawnsong", "at Dawnsong");
|
||||
|
||||
// Dawn itself: day for 8 hours, 3810 s.
|
||||
n = DerethClock.At(RawAt(1905));
|
||||
Check(n.IsDay, "Dawnsong: day");
|
||||
Eq(n.HourName, "Dawnsong", "Dawnsong: its name");
|
||||
Eq(n.SecondsToChange, 3810.0, "Dawnsong: dusk in 63.5 real minutes");
|
||||
Eq(n.NextHourName, "Evensong", "by day the night comes at Evensong");
|
||||
|
||||
// The examples: "Night in 23m", "Day in 4m 10s", "Day in 45s".
|
||||
n = DerethClock.At(RawAt(5715 - 1380));
|
||||
Check(n.IsDay, "23 min before dusk: day");
|
||||
Eq(n.HourName, "Midsong-and-Half", "23 min before dusk: hour 9");
|
||||
Eq(DerethClock.Label(n, n.SecondsToChange), "Night in 23m", "23 min before dusk");
|
||||
n = DerethClock.At(RawAt(5715 - 250));
|
||||
Eq(n.HourName, "Warmtide-and-Half", "the last day hour");
|
||||
Eq(DerethClock.Label(n, n.SecondsToChange), "Night in 4m 10s", "250 s before dusk");
|
||||
n = DerethClock.At(RawAt(1905 - 45));
|
||||
Check(!n.IsDay, "45 s before dawn: night");
|
||||
Eq(n.HourName, "Foredawn-and-Half", "the last night hour");
|
||||
Eq(DerethClock.Label(n, n.SecondsToChange), "Day in 45s", "45 s before dawn");
|
||||
|
||||
// Dusk itself: night through midnight to the next dawn, 3810 s.
|
||||
n = DerethClock.At(RawAt(5715));
|
||||
Check(!n.IsDay, "Evensong: night");
|
||||
Eq(n.HourName, "Evensong", "Evensong: its name");
|
||||
Eq(n.SecondsToChange, 3810.0, "Evensong: dawn in 63.5 real minutes (across midnight)");
|
||||
Eq(DerethClock.At(RawAt(7000)).SecondsToChange, 7620.0 - 7000 + 1905, "Gloaming: dawn across midnight");
|
||||
|
||||
// Whole days and the 10-year offset change nothing; a big clock keeps its precision.
|
||||
Eq(DerethClock.At(RawAt(735, day: 200_000)).SecondsToChange, DerethClock.At(RawAt(735)).SecondsToChange, "a later day: the same");
|
||||
|
||||
// Not readable yet.
|
||||
Check(!DerethClock.IsUsable(0), "0: the clock isn't set");
|
||||
Check(!DerethClock.IsUsable(double.NaN) && !DerethClock.IsUsable(-5) && !DerethClock.IsUsable(double.PositiveInfinity), "NaN, negative, infinite: not used");
|
||||
Check(DerethClock.IsUsable(123456.5), "a real reading is used");
|
||||
}
|
||||
|
||||
/// <summary>Against RynthAi's own meta expressions (getisday, getgamehour, getminutesuntilday/night), and the countdown's continuity.</summary>
|
||||
private static void ClockMatchesRynthAi()
|
||||
{
|
||||
const double hourTicks = 476.25;
|
||||
const int dayTicks = 7620;
|
||||
int mismatches = 0, jumps = 0, flips = 0;
|
||||
DerethNow prev = default;
|
||||
double prevRaw = 0;
|
||||
for (double raw = 10_000; raw < 10_000 + 2 * dayTicks; raw += 3.7)
|
||||
{
|
||||
// RynthAi (Meta/ExpressionEngine.cs), as it is written there.
|
||||
double ticks = raw - 210 + hourTicks * 8 + hourTicks * 16 * 30 * 12 * 10;
|
||||
int hour = (int)(ticks % dayTicks / hourTicks);
|
||||
bool isDay = hour >= 4 && hour < 12;
|
||||
double into = ticks % dayTicks;
|
||||
double untilDay = isDay ? 0 : into < 4 * hourTicks ? 4 * hourTicks - into : dayTicks - into + 4 * hourTicks;
|
||||
double untilNight = isDay ? 12 * hourTicks - into : 0;
|
||||
int minutes = (int)((isDay ? untilNight : untilDay) / 60);
|
||||
|
||||
DerethNow n = DerethClock.At(raw);
|
||||
if (n.Hour != hour || n.IsDay != isDay || (int)(n.SecondsToChange / 60) != minutes) mismatches++;
|
||||
|
||||
if (raw > 10_000)
|
||||
{
|
||||
if (n.IsDay != prev.IsDay)
|
||||
{
|
||||
flips++;
|
||||
// The change came when the countdown ran out.
|
||||
if (prev.SecondsToChange > raw - prevRaw + 1e-6) jumps++;
|
||||
}
|
||||
else if (Math.Abs(prev.SecondsToChange - (raw - prevRaw) - n.SecondsToChange) > 1e-6) jumps++; // a second a second
|
||||
}
|
||||
prev = n;
|
||||
prevRaw = raw;
|
||||
}
|
||||
Eq(mismatches, 0, "the hour, day or night and the minutes are RynthAi's");
|
||||
Eq(jumps, 0, "the countdown falls a second a real second, and the change comes when it runs out");
|
||||
Eq(flips, 4, "two days: two dawns and two dusks");
|
||||
}
|
||||
|
||||
private static void ClockCountdownText()
|
||||
{
|
||||
Eq(DerethClock.Countdown(0), "0s", "0");
|
||||
Eq(DerethClock.Countdown(0.2), "1s", "a part second rounds up: never 0s before the change");
|
||||
Eq(DerethClock.Countdown(45), "45s", "under a minute: seconds");
|
||||
Eq(DerethClock.Countdown(59.5), "1m 0s", "59.5 s rounds up to a minute");
|
||||
Eq(DerethClock.Countdown(250), "4m 10s", "under 10 minutes: minutes and seconds");
|
||||
Eq(DerethClock.Countdown(599), "9m 59s", "just under 10 minutes");
|
||||
Eq(DerethClock.Countdown(600), "10m", "10 minutes: minutes only");
|
||||
Eq(DerethClock.Countdown(601), "11m", "over 10 minutes: whole minutes rounded up");
|
||||
Eq(DerethClock.Countdown(1380), "23m", "23 minutes");
|
||||
Eq(DerethClock.Countdown(3600), "1h 0m", "an hour");
|
||||
Eq(DerethClock.Countdown(3810), "1h 4m", "the longest wait: 63.5 minutes");
|
||||
Eq(DerethClock.Countdown(-3), "0s", "a stale reading past the change: 0s, not negative");
|
||||
}
|
||||
|
||||
private static void ClockWindowAndCommand()
|
||||
{
|
||||
// The window counts down from when the tick read the clock.
|
||||
var v = new DayNightView(true, DerethClock.At(RawAt(5715 - 100)), 1000);
|
||||
Eq(v.SecondsLeft(1000), 100.0, "at the reading");
|
||||
Eq(v.SecondsLeft(3500), 97.5, "2.5 s later");
|
||||
Eq(v.SecondsLeft(1_000_000), 0.0, "long after: 0, not negative");
|
||||
Check(!DayNightView.NotReady.Ready, "before the world: not ready");
|
||||
Eq(DayNightWindow.NotInWorld, "—", "out of world it shows a dash");
|
||||
Check(DayNightWindow.Tip(DayNightView.NotReady, 0).Contains("in the world", StringComparison.Ordinal), "tooltip out of world");
|
||||
string tip = DayNightWindow.Tip(v, 100);
|
||||
Check(tip.Contains("Day now (Warmtide-and-Half)", StringComparison.Ordinal) && tip.Contains("Night comes at Evensong, in 1 min 40 s", StringComparison.Ordinal), "tooltip: " + tip);
|
||||
|
||||
// /rdef daynight [show|hide]: parsed, and every answer says what happened.
|
||||
Eq(DefCommandParser.Parse("daynight").Text, "", "alone: toggle");
|
||||
Eq(DefCommandParser.Parse("daynight show").Text, "show", "show");
|
||||
Eq(DefCommandParser.Parse("DayNight ON").Text, "show", "on = show, any case");
|
||||
Eq(DefCommandParser.Parse("daynight hide").Text, "hide", "hide");
|
||||
Eq(DefCommandParser.Parse("daynight off").Text, "hide", "off = hide");
|
||||
DefCommand bad = DefCommandParser.Parse("daynight soon");
|
||||
Check(bad.Verb == DefVerb.Error && bad.Error.Contains("Usage", StringComparison.Ordinal), "a wrong word: the usage");
|
||||
Check(DefCommandParser.Usage.Contains("daynight", StringComparison.Ordinal), "in the usage");
|
||||
|
||||
DerethNow dusk = DerethClock.At(RawAt(5715));
|
||||
Eq(DefReplies.DayNight(1, dusk), (true, "Day/Night timer shown. Night now (Evensong); day in 1h 4m of real time."), "shown, with the time");
|
||||
Eq(DefReplies.DayNight(0, null), (true, "Day/Night timer hidden."), "hidden, out of world: no time");
|
||||
var old = DefReplies.DayNight(-1, dusk);
|
||||
Check(!old.Ok && old.Text.Contains("v90", StringComparison.Ordinal) && old.Text.Contains("day in 1h 4m", StringComparison.Ordinal),
|
||||
"an engine without the window: why, and the time still");
|
||||
}
|
||||
}
|
||||
}
|
||||
269
Tools/RynthDefective.Tests/ExtraBarTests.cs
Normal file
269
Tools/RynthDefective.Tests/ExtraBarTests.cs
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthDefective;
|
||||
using RynthCore.Plugin.RynthDefective.Items;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
using RynthCore.Plugin.RynthDefective.ShortcutBar;
|
||||
using RynthCore.Plugin.RynthDefective.Ui;
|
||||
using RynthCore.Plugin.RynthDefective.Use;
|
||||
using RynthCore.Plugin.RynthDefective.Views;
|
||||
|
||||
namespace RynthDefective.Tests
|
||||
{
|
||||
// The extra Shortcuts bars (2026-11-04, ExtraBar): adding and removing them (at most 3, the lowest
|
||||
// free number), their own slots filled and used like the main bar's own, the character's file, the
|
||||
// /rdef bars command, what an extra bar's window draws, and the settings window's rows for them.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void ExtraBarsAddRemoveCap()
|
||||
{
|
||||
var d = new DefData();
|
||||
Eq(d.ExtraBars.Count, 0, "none by default");
|
||||
var numbers = new List<int>();
|
||||
for (int i = 0; i < ExtraBar.Max; i++) numbers.Add(d.AddExtraBar()?.Number ?? 0);
|
||||
Eq(string.Join(",", numbers), "2,3,4", "three bars, numbered 2-4 (the main bar is 1)");
|
||||
Check(d.AddExtraBar() == null && d.ExtraBars.Count == ExtraBar.Max, "a fourth is refused: the cap");
|
||||
Check(ExtraBar.Max + 5 <= 8, "the cap fits the engine's 8 windows for a plugin (RynthDefective draws 5 others, Day/Night included)");
|
||||
Check(d.RemoveExtraBar(3) && d.Extra(3) == null && d.ExtraBars.Count == 2, "remove bar 3");
|
||||
Check(!d.RemoveExtraBar(3), "removing it again: nothing to remove");
|
||||
Eq(d.AddExtraBar()?.Number, 3, "the next added takes the free number (its window comes back where it was)");
|
||||
Eq(string.Join(",", d.ExtraBars.Select(b => b.Number)), "2,3,4", "kept in number order");
|
||||
ExtraBar b2 = d.Extra(2)!;
|
||||
Eq(b2.SlotCount, ExtraBar.DefaultSlots, "10 slots to start");
|
||||
Eq(b2.Slots.Count, ExtraBar.SlotsMax, "always 24 slots kept (fewer shown hides them)");
|
||||
Eq(b2.Title, "Shortcuts 2", "its window's title");
|
||||
Eq(ExtraBar.SurfaceOf(4), "window:bar4", "its surface");
|
||||
|
||||
// The session's words for it, and the saves.
|
||||
var rig = new Rig("xbars");
|
||||
string m = rig.S.AddBar(out int n);
|
||||
Check(n == 2 && rig.S.Data.Extra(2) != null && rig.Saves == 1, "session: bar 2 added and saved");
|
||||
Check(m.Contains("Shortcuts bar 2 added") && m.Contains("drag items"), "it says how to fill it: " + m);
|
||||
for (int i = 0; i < 2; i++) rig.S.AddBar(out _);
|
||||
int saves = rig.Saves;
|
||||
m = rig.S.AddBar(out n);
|
||||
Check(n == 0 && rig.Saves == saves && rig.S.Data.ExtraBars.Count == 3, "at the cap: not added, not saved");
|
||||
Check(m.Contains("Remove one first") && m.Contains("8 windows"), "and it says why: " + m);
|
||||
|
||||
m = rig.S.RemoveBar(1);
|
||||
Check(m.Contains("can't be removed") && rig.S.Data.ExtraBars.Count == 3, "bar 1 is the Shortcuts bar itself: " + m);
|
||||
m = rig.S.RemoveBar(9);
|
||||
Check(m.StartsWith("There is no Shortcuts bar 9", StringComparison.Ordinal) && m.Contains("Extra Shortcuts bars: 2"), "no such bar: it lists them: " + m);
|
||||
rig.Inv = new List<CarriedItem> { Kit(0x7400_0001u) };
|
||||
rig.S.SetFromId(1, 0x7400_0001u, bar: 4);
|
||||
m = rig.S.RemoveBar(4);
|
||||
Check(rig.S.Data.Extra(4) == null && m.Contains("1 of its slots") && m.Contains("forgotten"), "a bar that held something: says it's forgotten: " + m);
|
||||
m = rig.S.RemoveBar(3);
|
||||
Check(m == "Shortcuts bar 3 removed.", "an empty one: " + m);
|
||||
Check(rig.S.DescribeBars().Contains("2 (10 slots, 0 set)") && !rig.S.DescribeBars().Contains("3 (10 slots") && rig.S.DescribeBars().Contains("2 more can be added"), "the list: " + rig.S.DescribeBars());
|
||||
|
||||
m = rig.S.SetBarSlots(2, 12);
|
||||
Check(rig.S.Data.Extra(2)!.SlotCount == 12 && m == "Shortcuts bar 2 shows 12 slots.", "bar 2 shows 12: " + m);
|
||||
m = rig.S.SetBarSlots(2, 99);
|
||||
Check(rig.S.Data.Extra(2)!.SlotCount == ExtraBar.SlotsMax && m.Contains("1 to 24"), "too many: the most: " + m);
|
||||
Check(rig.S.SetBarSlots(7, 3).StartsWith("There is no Shortcuts bar 7", StringComparison.Ordinal), "slots of a bar that isn't there");
|
||||
|
||||
var none = new Rig("xbars-none");
|
||||
Check(none.S.DescribeBars().Contains("/rdef bars add"), "no bars: how to add one");
|
||||
}
|
||||
|
||||
private static void ExtraBarsSlots()
|
||||
{
|
||||
var rig = new Rig("xbar-slots");
|
||||
var kit = Kit(0x7410_0001u);
|
||||
var potion = Potion(0x7410_0002u);
|
||||
rig.Inv = new List<CarriedItem> { kit, potion };
|
||||
rig.S.AddBar(out _);
|
||||
|
||||
rig.Selected = kit.Id;
|
||||
string m = rig.S.SetFromSelected(1, bar: 2);
|
||||
Check(rig.S.Data.Extra(2)!.Slots[0].Item?.Id == kit.Id && rig.S.Data.Slots[0].Empty, "the selected kit goes in bar 2's slot 1, not the main bar's");
|
||||
Check(m.StartsWith("Bar 2 slot 1: Peerless Healing Kit", StringComparison.Ordinal), "named by its bar: " + m);
|
||||
m = rig.S.SetFromId(3, potion.Id, bar: 2);
|
||||
Check(rig.S.Data.Extra(2)!.Slots[2].Item?.Id == potion.Id && m.StartsWith("Bar 2 slot 3:", StringComparison.Ordinal), "an item dropped on bar 2's slot 3");
|
||||
m = rig.S.SetSpell(2, 1, bar: 2); // the spellbook can't be read here: any spell id goes in
|
||||
Check(rig.S.Data.Extra(2)!.Slots[1].IsSpell && m.StartsWith("Bar 2 slot 2:", StringComparison.Ordinal), "a spell in bar 2's slot 2: " + m);
|
||||
Check(rig.S.SetFromId(1, potion.Id, bar: 3).StartsWith("There is no Shortcuts bar 3", StringComparison.Ordinal), "a bar that isn't there");
|
||||
Check(rig.S.SetFromId(25, potion.Id, bar: 2) == "Bar 2 has no slot 25.", "a slot past 24");
|
||||
Check(rig.S.Data.Slots.All(s => s.Empty), "the main bar's own slots are untouched");
|
||||
|
||||
// Pressing: through the use controller, as the main bar's own slots.
|
||||
Check(rig.S.UseSlot(1, bar: 2) == null && rig.S.Use.Pending?.Item?.Id == kit.Id && rig.S.Use.Pending?.Source == "bar 2 slot 1", "a click uses bar 2's kit: " + rig.S.Use.Pending?.Source);
|
||||
rig.S.Use.Reset();
|
||||
Check(rig.S.UseSlot(2, bar: 2) == null && rig.S.Use.Pending?.Spell == 1, "a spell slot casts");
|
||||
rig.S.Use.Reset();
|
||||
m = rig.S.UseSlot(4, bar: 2)!;
|
||||
Check(m.StartsWith("Bar 2 slot 4 is empty", StringComparison.Ordinal) && m.Contains("right-click"), "an empty one says how to fill it: " + m);
|
||||
Check(rig.S.UseSlot(1, bar: 5)!.StartsWith("There is no Shortcuts bar 5", StringComparison.Ordinal), "a bar that isn't there");
|
||||
|
||||
m = rig.S.ClearSlot(3, bar: 2);
|
||||
Check(rig.S.Data.Extra(2)!.Slots[2].Empty && m == "Bar 2 slot 3 cleared.", "cleared: " + m);
|
||||
|
||||
// The slots follow their items: the kit used up, the next of its name is the one.
|
||||
var kit2 = Kit(0x7410_0009u);
|
||||
rig.Inv = new List<CarriedItem> { kit2, potion };
|
||||
Check(rig.S.Maintain(rig.Inv) && rig.S.Data.Extra(2)!.Slots[0].Item?.Id == kit2.Id, "an extra bar's slot follows its item like the main bar's");
|
||||
|
||||
// The main bar's own slots still read as before.
|
||||
Check(rig.S.SetFromId(1, potion.Id) == "Slot 1: Health Potion (used when pressed).", "the main bar's words unchanged: " + rig.S.SetFromId(1, potion.Id));
|
||||
Check(rig.S.UseSlot(43) == "There is no slot 43.", "and its limits");
|
||||
}
|
||||
|
||||
private static void ExtraBarsStore()
|
||||
{
|
||||
var st = new DefStore(Path.Combine(_temp, "xbar-store"));
|
||||
var d = new DefData();
|
||||
ExtraBar a = d.AddExtraBar()!;
|
||||
a.SlotCount = 12;
|
||||
a.Slots[0].Item = ItemRef.From(Kit(0x7420_0001u));
|
||||
a.Slots[0].Mode = UseMode.OnSelf;
|
||||
a.Slots[11] = new DefSlot { SpellId = 1, SpellName = "Strength Other I" };
|
||||
a.Slots[23].Item = ItemRef.From(Potion(0x7420_0002u)); // past the shown count: kept
|
||||
d.AddExtraBar();
|
||||
ExtraBar c = d.AddExtraBar()!;
|
||||
c.SlotCount = 3;
|
||||
d.RemoveExtraBar(3); // bars 2 and 4 are left
|
||||
d.Slots[0].Item = ItemRef.From(Potion(0x7420_0003u));
|
||||
|
||||
Check(st.Save("TestServer", "Test", d) == null, "saved");
|
||||
DefData r = st.Load("TestServer", "Test", out string? problem);
|
||||
Check(problem == null, "read back");
|
||||
Eq(string.Join(",", r.ExtraBars.Select(b => b.Number)), "2,4", "bars 2 and 4");
|
||||
ExtraBar ra = r.Extra(2)!, rc = r.Extra(4)!;
|
||||
Check(ra.SlotCount == 12 && rc.SlotCount == 3, "their slot counts");
|
||||
Check(ra.Slots[0].Item?.Id == 0x7420_0001u && ra.Slots[0].Mode == UseMode.OnSelf, "an item and its mode");
|
||||
Check(ra.Slots[11].SpellId == 1 && ra.Slots[11].SpellName.Length > 0, "a spell slot");
|
||||
Check(ra.Slots[23].Item?.Id == 0x7420_0002u, "a slot past the shown count is kept");
|
||||
Check(ra.Slots.Count == ExtraBar.SlotsMax && rc.Filled == 0, "24 slots each; bar 4 empty");
|
||||
Check(r.Slots[0].Item?.Id == 0x7420_0003u, "the main bar's own slots alongside");
|
||||
Eq(DefStore.ToJson(r), DefStore.ToJson(d), "the round trip writes the same file");
|
||||
|
||||
// A file from before the extra bars: none. Odd entries: skipped, clamped, capped.
|
||||
var old = DefStore.Parse(JsonDocument.Parse("{\"slots\":[]}").RootElement);
|
||||
Eq(old.ExtraBars.Count, 0, "a file from before has none");
|
||||
string odd = "{\"extraBars\":[\"x\", {\"number\":1}, {\"number\":9}, {\"number\":3,\"slotCount\":99,\"slots\":[{\"item\":{\"id\":5,\"name\":\"Arrow\"}}]},"
|
||||
+ "{\"number\":3}, {\"number\":2,\"slotCount\":0}, {\"number\":4,\"slots\":\"none\"}, {\"number\":5}, {\"number\":4}]}";
|
||||
DefData o = DefStore.Parse(JsonDocument.Parse(odd).RootElement);
|
||||
Eq(string.Join(",", o.ExtraBars.Select(b => b.Number)), "2,3,4", "bad numbers (1, 9 and 5) and repeats skipped, sorted, at most 3");
|
||||
Check(o.Extra(3)!.SlotCount == ExtraBar.SlotsMax && o.Extra(3)!.Slots[0].Item?.Name == "Arrow", "too many slots: the most; its item read");
|
||||
Check(o.Extra(2)!.SlotCount == ExtraBar.SlotsMin, "too few: one");
|
||||
Check(o.Extra(4)!.Slots.All(s => s.Empty) && o.Extra(4)!.SlotCount == ExtraBar.DefaultSlots, "slots that aren't a list: empty, the default count");
|
||||
}
|
||||
|
||||
private static void ExtraBarsCommands()
|
||||
{
|
||||
DefCommand c = DefCommandParser.Parse("bars");
|
||||
Check(c.Verb == DefVerb.Bars && c.Text == "list", "/rdef bars lists");
|
||||
Check(DefCommandParser.Parse("bars list").Text == "list", "/rdef bars list");
|
||||
Check(DefCommandParser.Parse("bars add").Text == "add", "/rdef bars add");
|
||||
c = DefCommandParser.Parse("bars remove 3");
|
||||
Check(c.Verb == DefVerb.Bars && c.Text == "remove" && c.Slot == 3, "/rdef bars remove 3");
|
||||
c = DefCommandParser.Parse("bars slots 2 12");
|
||||
Check(c.Verb == DefVerb.Bars && c.Text == "slots" && c.Slot == 2 && c.Count == 12, "/rdef bars slots 2 12");
|
||||
c = DefCommandParser.Parse("bars show 4");
|
||||
Check(c.Verb == DefVerb.Bars && c.Text == "show" && c.Slot == 4, "/rdef bars show 4");
|
||||
Check(DefCommandParser.Parse("bars hide 4").Text == "show", "hide is the same toggle");
|
||||
foreach (string wrong in new[] { "bars remove", "bars remove two", "bars slots 2", "bars slots 2 99", "bars slots 2 0", "bars show", "bars frob", "bars add 2" })
|
||||
{
|
||||
c = DefCommandParser.Parse(wrong);
|
||||
Check(c.Verb == DefVerb.Error && (c.Error.Contains("e.g.", StringComparison.Ordinal) || c.Error.Contains("Usage", StringComparison.Ordinal)),
|
||||
$"'/rdef {wrong}' answers how it's typed: {c.Error}");
|
||||
}
|
||||
Check(DefCommandParser.Usage.Contains("bars"), "the usage line has it");
|
||||
|
||||
// The surfaces the engine draws them by.
|
||||
Check(RynthDefectivePlugin.TryExtraSurface("window:bar2", out int s2) && s2 == 2, "window:bar2 is bar 2");
|
||||
Check(RynthDefectivePlugin.TryExtraSurface(ExtraBar.SurfaceOf(4), out int s5) && s5 == 4, "window:bar4 is bar 4");
|
||||
foreach (string not in new[] { "window:bar", "window:bar1", "window:bar6", "window:bar22", "window:panels", "window:barx" })
|
||||
Check(!RynthDefectivePlugin.TryExtraSurface(not, out _), $"{not} is no extra bar");
|
||||
}
|
||||
|
||||
private static void ExtraBarSnapshot()
|
||||
{
|
||||
var rig = new Rig("xbar-snap");
|
||||
var kit = Kit(0x7430_0001u);
|
||||
rig.Inv = new List<CarriedItem> { kit };
|
||||
rig.S.AddBar(out _);
|
||||
rig.S.AddBar(out _);
|
||||
rig.S.SetFromId(2, kit.Id, bar: 3);
|
||||
rig.S.SetSpell(5, 1, bar: 3);
|
||||
|
||||
BarSnapshot v = BarSnapshotBuilder.BuildExtra(rig.S, 3, rig.Inv, canCast: true);
|
||||
Check(v.Ready && v.Bar == 3 && v.Slots.Length == ExtraBar.DefaultSlots, "bar 3: ready, 10 slots");
|
||||
Check(v.MinSlots == ExtraBar.SlotsMin && v.MaxSlots == ExtraBar.SlotsMax, "its edit buttons go 1-24");
|
||||
Check(v.Slots.All(s => !s.Retail && s.Key.Length == 0 && s.AllKeys.Length == 0), "no game slots, no keys");
|
||||
Check(v.Slots[1].ObjectId == kit.Id && v.Slots[1].Count == "28", "slot 2: the kit and its uses left");
|
||||
Check(v.Slots[1].Tooltip.Contains("Click: use it on you") && !v.Slots[1].Tooltip.Contains("press the key") && !v.Slots[1].Tooltip.Contains("No key yet"),
|
||||
"its tooltip: clicks, no keys: " + v.Slots[1].Tooltip);
|
||||
Check(v.Slots[4].SpellId == 1 && !v.Slots[4].Tooltip.Contains("press the key"), "slot 5: the spell");
|
||||
Check(v.Slots[0].Empty && v.Slots[0].Tooltip.Contains("Drag an item"), "an empty slot says how to fill it");
|
||||
Eq(string.Join(",", v.Extras.Select(e => e.Number + ":" + e.Filled)), "2:0,3:2", "the bars there are, for the menus");
|
||||
Check(v.CanAddBar, "two more can be added");
|
||||
rig.S.SetBarSlots(3, 2);
|
||||
Eq(BarSnapshotBuilder.BuildExtra(rig.S, 3, rig.Inv, true).Slots.Length, 2, "fewer slots shown");
|
||||
Check(!BarSnapshotBuilder.BuildExtra(rig.S, 4, rig.Inv, true).Ready, "a bar that isn't there: not ready");
|
||||
rig.S.AddBar(out _);
|
||||
rig.S.AddBar(out _);
|
||||
Check(!BarSnapshotBuilder.BuildExtra(rig.S, 2, rig.Inv, true).CanAddBar, "at three: no more");
|
||||
Check(BarSnapshot.NotReady.Bar == 0 && BarSnapshot.NotReady.MaxSlots == DefSettings.BarSlotsMax, "the main bar's limits by default");
|
||||
}
|
||||
|
||||
private static void ExtraBarSettings()
|
||||
{
|
||||
var b = new BarRig("xbar-settings");
|
||||
var host = new UiHost();
|
||||
UiWindow win = host.Add(new UiWindow("RynthDefective/Settings", "Defective Settings") { Visible = true, ShowInBar = false });
|
||||
var view = new BarSettingsView(b.S);
|
||||
var shown = new Dictionary<string, bool> { [BarSettingsView.BarTitle] = true };
|
||||
view.WindowShown = t => shown.TryGetValue(t, out bool v) ? v : null;
|
||||
view.ShowWindow = (t, v) => shown[t] = v;
|
||||
int adds = 0;
|
||||
var removed = new List<int>();
|
||||
view.AddBar = () => { adds++; b.S.AddBar(out _); };
|
||||
view.RemoveBar = n => { removed.Add(n); b.S.RemoveBar(n); };
|
||||
void Draw() { win.Begin(); view.Draw(win); win.End(); }
|
||||
string Text() => Encoding.UTF8.GetString(win.Body);
|
||||
var w = new Windows("xbar-settings-events");
|
||||
w.Host.Add(win);
|
||||
|
||||
Draw();
|
||||
ParseAll(host, "settings window with no extra bars", out _);
|
||||
Check(Text().Contains("More shortcut bars") && Text().Contains("Add a shortcut bar"), "the section and its Add button");
|
||||
w.Click(win, "set.xbar.add");
|
||||
Eq(adds, 1, "Add a shortcut bar adds one");
|
||||
Draw();
|
||||
Check(Text().Contains("Shortcuts bar 2: opening..."), "not hosted yet: opening");
|
||||
shown[ExtraBar.TitleOf(2)] = false;
|
||||
Draw();
|
||||
ParseAll(host, "settings window with bar 2", out int ops);
|
||||
Check(ops < 1500, "inside the engine's limits");
|
||||
w.SetBool(win, "set.xbar.2.shown", true);
|
||||
Check(shown[ExtraBar.TitleOf(2)], "its box shows it");
|
||||
w.SetInt(win, "set.xbar.2.slots", 15);
|
||||
Check(b.S.Data.Extra(2)!.SlotCount == 15, "its slider sets its slots");
|
||||
w.Click(win, "set.xbar.2.remove");
|
||||
Draw();
|
||||
Check(Text().Contains("Remove Shortcuts bar 2?") && removed.Count == 0, "Remove asks first");
|
||||
w.Click(win, "set.xbar.2.no");
|
||||
Draw();
|
||||
Check(!Text().Contains("Remove Shortcuts bar 2?") && b.S.Data.Extra(2) != null, "Keep it keeps it");
|
||||
w.Click(win, "set.xbar.2.remove");
|
||||
Draw();
|
||||
w.Click(win, "set.xbar.2.yes");
|
||||
Check(removed.SequenceEqual(new[] { 2 }) && b.S.Data.Extra(2) == null, "Remove it removes it");
|
||||
|
||||
for (int i = 0; i < ExtraBar.Max; i++) b.S.AddBar(out _);
|
||||
Draw();
|
||||
Check(!Text().Contains("Add a shortcut bar") && Text().Contains("as many as there can be"), "at three: no Add button, and why");
|
||||
|
||||
// An engine without the Shortcuts bar: no section.
|
||||
shown.Remove(BarSettingsView.BarTitle);
|
||||
Draw();
|
||||
Check(!Text().Contains("More shortcut bars"), "no Shortcuts bar on this engine: no extra bars either");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -73,6 +73,9 @@ namespace RynthDefective.Tests
|
|||
Run("busy rule with RynthAi holding: its own action and our last use hold, the rest of the count doesn't", BusyRulePaced);
|
||||
Run("use: the player's turn - after a death the press goes next, RynthAi holds and is let go", UsePlayersTurn);
|
||||
Run("use: just after a portal the client takes nothing for a few seconds - the press waits and goes when it can", UseAfterPortal);
|
||||
Run("busy clear rule: only a count with nothing real in flight is cleared", BusyClearDecisions);
|
||||
Run("use: shortcuts clear a stuck busy state - off by default, then clear once per press and use", UseClearStuckBusy);
|
||||
Run("store, command and settings: shortcuts clear a stuck busy state", ClearBusySettingAndCommand);
|
||||
Run("spells: the table's names and flags, the name search", SpellTableAndSearch);
|
||||
Run("spells: whom a cast goes to", SpellCastTarget);
|
||||
Run("spells: a slot casts, Magic mode first, refusals", SpellUse);
|
||||
|
|
@ -98,6 +101,12 @@ namespace RynthDefective.Tests
|
|||
Run("bar: making it independent offers to copy the game's 18 slots", BarIndependentCopy);
|
||||
Run("store: the independent bar setting; files from before read it off", BarStoreIndependent);
|
||||
Run("window: the settings window parses and its switches reach their code", BarSettingsWindow);
|
||||
Run("extra bars: add and remove, the lowest free number, at most 4", ExtraBarsAddRemoveCap);
|
||||
Run("extra bars: their own slots filled, used and kept like the main bar's own", ExtraBarsSlots);
|
||||
Run("store: the extra bars saved and read; files from before and odd ones", ExtraBarsStore);
|
||||
Run("extra bars: /rdef bars parsing", ExtraBarsCommands);
|
||||
Run("extra bars: what an extra bar's window draws (no game slots, no keys)", ExtraBarSnapshot);
|
||||
Run("window: the settings window's rows for the extra bars", ExtraBarSettings);
|
||||
Run("corpses: the server's lines", CorpseLinesParse);
|
||||
Run("corpses: a death, the server's line before or after it, nothing dropped", CorpseDeaths);
|
||||
Run("corpses: a corpse in view is the death beside it, else one found", CorpseSeen);
|
||||
|
|
@ -117,6 +126,10 @@ namespace RynthDefective.Tests
|
|||
Run("quantity: a server's bank - its values, pack + bank, one that can't be read, max", QtyBankRules);
|
||||
Run("quantity: buy and max with no bank, a bank that covers it, one that doesn't, one that can't be read", QtyBankBuy);
|
||||
Run("store: the quantity box setting; files from before read it on", QtyStore);
|
||||
Run("day/night: day or night, the hour and the real seconds to dawn or dusk", ClockDayNight);
|
||||
Run("day/night: the same as RynthAi's meta expressions, a countdown with no jumps", ClockMatchesRynthAi);
|
||||
Run("day/night: the countdown text (23m, 4m 10s, 45s)", ClockCountdownText);
|
||||
Run("day/night: the window's view and tooltip, /rdef daynight and its answers", ClockWindowAndCommand);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -257,6 +270,20 @@ namespace RynthDefective.Tests
|
|||
Releases++;
|
||||
BotHeldNow = false;
|
||||
}
|
||||
/// <summary>
|
||||
/// The busy-count resets asked for ("Shortcuts clear a stuck busy state"). CanClear false: an engine
|
||||
/// without ForceResetBusyCount. ClearLands false: the reset doesn't take. It lands on the next tick.
|
||||
/// </summary>
|
||||
public int Clears;
|
||||
public bool CanClear = true, ClearLands = true;
|
||||
private bool _clearPending;
|
||||
public bool ClearBusyCount()
|
||||
{
|
||||
if (!CanClear) return false;
|
||||
Clears++;
|
||||
_clearPending = ClearLands;
|
||||
return true;
|
||||
}
|
||||
public int UseDoneSeq { get; set; } = 1;
|
||||
public int CombatMode { get; set; } = Stance.NonCombat;
|
||||
public int RefusalSeq { get; set; }
|
||||
|
|
@ -307,7 +334,11 @@ namespace RynthDefective.Tests
|
|||
return true;
|
||||
}
|
||||
|
||||
public void Advance(long ms) => NowMs += ms;
|
||||
public void Advance(long ms)
|
||||
{
|
||||
NowMs += ms;
|
||||
if (_clearPending) { BusyCount = 0; _clearPending = false; } // the engine resets on the game's next tick
|
||||
}
|
||||
public void Answer(uint error = 0)
|
||||
{
|
||||
UseDoneSeq++;
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ namespace RynthDefective.Tests
|
|||
{
|
||||
// Wrong words: the parser's error is the reply, with an example or the usage.
|
||||
string[] wrong = { "use", "set", "set x", "set 0", "spell 3", "spell", "clear", "clear x", "bind 3", "bind", "unbind", "unbind x", "slots", "slots 99",
|
||||
"qty 0", "qty lots", "split 0", "give someone", "give -1", "buy 0 Mana Scarab" };
|
||||
"qty 0", "qty lots", "split 0", "give someone", "give -1", "buy 0 Mana Scarab", "bars remove", "bars slots 2", "bars frob", "shortcuts", "shortcuts clearbusy maybe", "daynight later" };
|
||||
foreach (string w in wrong)
|
||||
{
|
||||
DefCommand c = DefCommandParser.Parse(w);
|
||||
|
|
@ -105,6 +105,9 @@ namespace RynthDefective.Tests
|
|||
("Stamina Kit", DefVerb.Use), ("corpses", DefVerb.Corpses), ("corpses clear", DefVerb.Corpses),
|
||||
("qty", DefVerb.Quantity), ("qty 25", DefVerb.Quantity), ("split", DefVerb.Split), ("split 25 into Sack", DefVerb.Split),
|
||||
("give 10", DefVerb.Give), ("buy 25 Mana Scarab", DefVerb.Buy), ("buy max", DefVerb.Buy),
|
||||
("daynight", DefVerb.DayNight), ("daynight show", DefVerb.DayNight), ("daynight hide", DefVerb.DayNight),
|
||||
("bars", DefVerb.Bars), ("bars add", DefVerb.Bars), ("bars remove 2", DefVerb.Bars), ("bars slots 2 12", DefVerb.Bars),
|
||||
("bars show 3", DefVerb.Bars), ("shortcuts clearbusy on", DefVerb.Shortcuts), ("shortcuts clearbusy", DefVerb.Shortcuts),
|
||||
};
|
||||
var seen = new HashSet<DefVerb>();
|
||||
foreach (var (typed, verb) in right)
|
||||
|
|
|
|||
|
|
@ -13,7 +13,8 @@
|
|||
(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; the quantity box
|
||||
(counts, max and half, a vendor's price and the most you can buy, every refusal, split / give / buy
|
||||
against a scripted world).
|
||||
against a scripted world); the Day/Night timer's clock (day or night, the real seconds to the next dawn or
|
||||
dusk, the countdown text, /rdef daynight).
|
||||
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)
|
||||
-->
|
||||
|
|
@ -41,6 +42,8 @@
|
|||
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
|
||||
<!-- The Day/Night timer's clock math (2026-11-04). -->
|
||||
<Compile Include="..\..\Plugins\Shared\DerethClock.cs" Link="Shared\DerethClock.cs" />
|
||||
<!-- The server plugin's bank values for the quantity box's buys (2026-10-31). -->
|
||||
<Compile Include="..\..\Plugins\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\ServerStateClient.cs" Link="Shared\ServerStateClient.cs" />
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ using RynthNav.Baker;
|
|||
using RynthNav.Routing;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
internal static class Program
|
||||
internal static partial class Program
|
||||
{
|
||||
private static int _fails, _asserts;
|
||||
private static void Check(bool cond, string msg)
|
||||
|
|
@ -57,6 +57,7 @@ internal static class Program
|
|||
Run(nameof(RealMeshView), RealMeshView);
|
||||
Run(nameof(DungeonFileAndLayer), DungeonFileAndLayer);
|
||||
Run(nameof(RealDungeons), RealDungeons);
|
||||
RunRouteMaker(); // RouteMakerTests.cs
|
||||
}
|
||||
finally { try { Directory.Delete(_root, true); } catch { } }
|
||||
Console.WriteLine();
|
||||
|
|
|
|||
317
Tools/RynthNav.GraphTests/RouteMakerTests.cs
Normal file
317
Tools/RynthNav.GraphTests/RouteMakerTests.cs
Normal file
|
|
@ -0,0 +1,317 @@
|
|||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
using RynthNav.Routing;
|
||||
|
||||
// The route maker on the navmesh (LoopMaker, TilePathFinder's route maker options), on floors baked here
|
||||
// and on the real map when it's installed (read only): a loop's points (walkable, out of buildings, away
|
||||
// from portals, reachable, in an order whose legs don't cross), its legs (round a pond, never through a
|
||||
// portal's circle, round a building's rooms, off walls), what is dropped and why, and a path through
|
||||
// given points (each leg walked; a point or a leg that can't be, named).
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunRouteMaker()
|
||||
{
|
||||
Run(nameof(LoopOnOpenGround), LoopOnOpenGround);
|
||||
Run(nameof(LoopLegsGoRoundAPond), LoopLegsGoRoundAPond);
|
||||
Run(nameof(LoopDropsWhatItCantReach), LoopDropsWhatItCantReach);
|
||||
Run(nameof(LegsNeverThroughAPortal), LegsNeverThroughAPortal);
|
||||
Run(nameof(LegsRoundABuildingAndOffWalls), LegsRoundABuildingAndOffWalls);
|
||||
Run(nameof(PathThroughGivenPoints), PathThroughGivenPoints);
|
||||
Run(nameof(RealLoopsNearHoltburg), RealLoopsNearHoltburg);
|
||||
}
|
||||
|
||||
private static double MinGap(IReadOnlyList<WorldPt> path, double x, double y)
|
||||
{
|
||||
double best = double.MaxValue;
|
||||
for (int i = 1; i < path.Count; i++) best = Math.Min(best, PortalAvoid.SegmentDistance(x, y, path[i - 1].X, path[i - 1].Y, path[i].X, path[i].Y));
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Does any stretch of the path pass through the box (sampled every half yard)?</summary>
|
||||
private static bool Enters(IReadOnlyList<WorldPt> path, double x0, double y0, double x1, double y1)
|
||||
{
|
||||
for (int i = 1; i < path.Count; i++)
|
||||
{
|
||||
WorldPt a = path[i - 1], b = path[i];
|
||||
int n = Math.Max(1, (int)(a.FlatDistance(b) * 2));
|
||||
for (int k = 0; k <= n; k++)
|
||||
{
|
||||
double x = a.X + (b.X - a.X) * k / n, y = a.Y + (b.Y - a.Y) * k / n;
|
||||
if (x > x0 && x < x1 && y > y0 && y < y1) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void CheckLoopRules(LoopMaker.Result r, TilePathFinder mesh, BuildingOutlines? buildings, IReadOnlyList<PortalAvoid.Spot> portals, string what)
|
||||
{
|
||||
Check(r.Ok && r.Route != null, $"{what}: a loop ({r.Error})");
|
||||
if (!r.Ok || r.Route == null) return;
|
||||
Check(r.Points.Count >= 3 && r.Legs.Count == r.Points.Count, $"{what}: {r.Points.Count} points, a leg from each");
|
||||
foreach (WorldPt p in r.Points)
|
||||
{
|
||||
Check(mesh.Snap(p, 1.0, out _, out _), $"{what}: point {NavCoords.Fmt(p.Ns, p.Ew)} is on walkable ground");
|
||||
if (buildings != null) Check(buildings.Inside(p.X, p.Y, 2.9) < 0, $"{what}: point {NavCoords.Fmt(p.Ns, p.Ew)} is out of every building");
|
||||
foreach (PortalAvoid.Spot s in portals)
|
||||
Check(Math.Sqrt((p.X - s.X) * (p.X - s.X) + (p.Y - s.Y) * (p.Y - s.Y)) >= 20 - 0.01, $"{what}: point 20 yd or more from {s.Name}");
|
||||
}
|
||||
Check(RouteShape.Crossings(r.Points, closed: true) == 0, $"{what}: walked in an order where no two legs cross");
|
||||
for (int i = 0; i < r.Legs.Count; i++)
|
||||
{
|
||||
List<WorldPt> leg = r.Legs[i];
|
||||
Check(leg[0].FlatDistance(r.Points[i]) < 1 && leg[^1].FlatDistance(r.Points[(i + 1) % r.Points.Count]) < 2.5, $"{what}: leg {i + 1} joins its two points");
|
||||
foreach (PortalAvoid.Spot s in portals)
|
||||
Check(MinGap(leg, s.X, s.Y) >= s.R - 0.06, $"{what}: leg {i + 1} keeps out of {s.Name}'s circle ({MinGap(leg, s.X, s.Y):F2} yd)");
|
||||
}
|
||||
Check(r.Route.RouteType == NavRouteType.Circular && r.Route.Points.Count >= r.Points.Count, $"{what}: a circular nav, a waypoint at least per point");
|
||||
Check(Math.Abs(RouteInfo.Length(r.Route) - r.Yards) < 2, $"{what}: its length is the nav file's ({r.Yards:F0} yd)");
|
||||
NavRouteParser back = NavRouteParser.LoadFromLines(r.Route.ToLines());
|
||||
Check(back.LoadWarning == null && back.Points.Count == r.Route.Points.Count && back.RouteType == NavRouteType.Circular, $"{what}: RynthAi reads it back");
|
||||
}
|
||||
|
||||
private static void LoopOnOpenGround()
|
||||
{
|
||||
// 3 x 3 tiles of open ground; a building's outline where the north point would go, a portal where the east one would.
|
||||
string dir = Bake("loopopen", (0, 0, 576, 576));
|
||||
var centre = new WorldPt(288, 288, double.NaN);
|
||||
var buildings = BuildingOutlines.FromPolygons(new[] { new (double, double)[] { (270, 350), (306, 350), (306, 386), (270, 386) } });
|
||||
var portals = new List<PortalAvoid.Spot> { new(368, 288, PortalAvoid.MapRadius, "Unwanted Portal") };
|
||||
var mesh = new TilePathFinder(dir, null, portals);
|
||||
var opt = new LoopMaker.LoopOptions { Radius = 80, Points = 8, WallClearance = 1.0 };
|
||||
LoopMaker.Result r = LoopMaker.Loop(mesh, centre, opt, buildings, portals);
|
||||
CheckLoopRules(r, mesh, buildings, portals, "open ground");
|
||||
Check(r.Points.Count == 8 && r.DroppedPoints.Count == 0, $"every point placed ({r.Points.Count}, {r.DroppedPoints.Count} dropped)");
|
||||
Check(r.Points.All(p => Math.Abs(p.FlatDistance(r.Centre) - 80) < 45), "the points round the circle");
|
||||
Check(r.Yards > 2 * Math.PI * 80 * 0.6 && r.Yards < 2 * Math.PI * 80 * 1.3, $"a lap of about the circle ({r.Yards:F0} yd)");
|
||||
Console.WriteLine($" open ground: {r.Points.Count} points, {r.Route?.Points.Count} waypoints, {r.Yards:F0} yd a lap, {mesh.TilesRead} tiles");
|
||||
|
||||
// Default point count, and the order starts north and goes clockwise.
|
||||
var r2 = LoopMaker.Loop(new TilePathFinder(dir, null, null), centre, new LoopMaker.LoopOptions { Radius = 40 }, null, Array.Empty<PortalAvoid.Spot>());
|
||||
Check(r2.Ok && r2.Asked == RouteShape.DefaultPoints(40), $"no point count: {RouteShape.DefaultPoints(40)} by default ({r2.Asked})");
|
||||
Check(r2.Ok && RouteShape.Bearing(r2.Centre, r2.Points[0]) < 30 && RouteShape.Bearing(r2.Centre, r2.Points[1]) > RouteShape.Bearing(r2.Centre, r2.Points[0]), "north first, clockwise");
|
||||
Check(r2.Notes.Any(n => n.Contains("worldmap.vec")), "without building outlines it says so");
|
||||
|
||||
// No ground at the centre: refused, saying where.
|
||||
var none = LoopMaker.Loop(new TilePathFinder(dir, null, null), new WorldPt(5000, 5000, double.NaN), opt, null, Array.Empty<PortalAvoid.Spot>());
|
||||
Check(!none.Ok && none.Error.Contains("navmesh"), "no tiles at the centre: " + none.Error);
|
||||
}
|
||||
|
||||
private static void LoopLegsGoRoundAPond()
|
||||
{
|
||||
// Open ground with a pond (x 300..330, y 340..365) right on the straight leg from the north point to the north-east one.
|
||||
string dir = Bake("looppond", (0, 0, 576, 340), (0, 340, 300, 576), (330, 340, 576, 576), (300, 365, 330, 576));
|
||||
var mesh = new TilePathFinder(dir, null, null);
|
||||
LoopMaker.Result r = LoopMaker.Loop(mesh, new WorldPt(288, 288, double.NaN), new LoopMaker.LoopOptions { Radius = 80, Points = 8 }, null, Array.Empty<PortalAvoid.Spot>());
|
||||
CheckLoopRules(r, mesh, null, Array.Empty<PortalAvoid.Spot>(), "pond");
|
||||
bool anyNear = false;
|
||||
foreach (List<WorldPt> leg in r.Legs)
|
||||
{
|
||||
Check(!Enters(leg, 300.5, 340.5, 329.5, 364.5), "no leg walks through the pond");
|
||||
anyNear |= Enters(leg, 296, 336, 334, 369);
|
||||
}
|
||||
Check(anyNear, "a leg goes round its edge (it was in the way)");
|
||||
Check(!Enters(r.Route!.Points.Select(p => WorldPt.FromMap(p.NS, p.EW)).ToList(), 300.5, 340.5, 329.5, 364.5), "nor does the saved route");
|
||||
}
|
||||
|
||||
private static void LoopDropsWhatItCantReach()
|
||||
{
|
||||
// The main ground ends at x = 375; past 20 yd of water (to 395) an island no walk reaches.
|
||||
string dir = Bake("loopisland", (0, 0, 375, 576), (395, 0, 576, 576));
|
||||
var mesh = new TilePathFinder(dir, null, null);
|
||||
LoopMaker.Result r = LoopMaker.Loop(mesh, new WorldPt(340, 288, double.NaN), new LoopMaker.LoopOptions { Radius = 100, Points = 8 }, null, Array.Empty<PortalAvoid.Spot>());
|
||||
CheckLoopRules(r, mesh, null, Array.Empty<PortalAvoid.Spot>(), "island");
|
||||
Check(r.Points.All(p => p.X < 376), "every point on the main ground");
|
||||
Check(r.DroppedPoints.Count >= 1 && r.DroppedPoints.Any(d => d.Why.Contains("not reachable")), $"the east is dropped: {string.Join("; ", r.DroppedPoints.Select(d => d.Why))}");
|
||||
Check(r.Points.Count + r.DroppedPoints.Count == 8, "kept + dropped = asked");
|
||||
|
||||
// Too little ground for a loop: refused, with why.
|
||||
string tiny = Bake("looptiny", (100, 100, 112, 112));
|
||||
var t = LoopMaker.Loop(new TilePathFinder(tiny, null, null), new WorldPt(106, 106, double.NaN), new LoopMaker.LoopOptions { Radius = 60, Points = 6 }, null, Array.Empty<PortalAvoid.Spot>());
|
||||
Check(!t.Ok && (t.Error.Contains("could be placed") || t.Error.Contains("ground")), "a speck of ground: no loop: " + t.Error);
|
||||
}
|
||||
|
||||
private static void LegsNeverThroughAPortal()
|
||||
{
|
||||
// Two rooms joined only by a corridor 12 yd wide with a portal in the middle of it.
|
||||
string dir = Bake("portalcorridor", (0, 0, 150, 192), (150, 90, 250, 102), (250, 0, 400, 192));
|
||||
var portals = new List<PortalAvoid.Spot> { new(200, 96, PortalAvoid.MapRadius, "Blocking Portal") };
|
||||
var a = new WorldPt(75, 96, double.NaN);
|
||||
var b = new WorldPt(325, 96, double.NaN);
|
||||
|
||||
var loose = new TilePathFinder(dir, null, portals);
|
||||
loose.LoadArea(0, 0, 400, 192);
|
||||
List<WorldPt>? through = loose.Leg(a, b, out string n1);
|
||||
Check(through != null && MinGap(through, 200, 96) < PortalAvoid.MapRadius, "the plain planner walks through it when there's no way round (saveroute's behaviour, unchanged): " + n1);
|
||||
|
||||
var strict = new TilePathFinder(dir, null, portals) { StrictPortals = true };
|
||||
strict.LoadArea(0, 0, 400, 192);
|
||||
List<WorldPt>? none = strict.Leg(a, b, out string note);
|
||||
Check(none == null && note.Contains("Blocking Portal"), "strict: no leg, and the portal is named: " + note);
|
||||
var walk = new TilePathFinder(dir, null, portals) { StrictPortals = true, NoGaps = true };
|
||||
Check(walk.Walk(a, b, false, out string wn) == null && wn.Contains("Blocking Portal"), "strict walk with no gaps allowed: none either: " + wn);
|
||||
|
||||
// A loop round the first room never uses the corridor, and its legs keep out of the circle.
|
||||
var room = new TilePathFinder(dir, null, portals);
|
||||
LoopMaker.Result r = LoopMaker.Loop(room, new WorldPt(75, 96, double.NaN), new LoopMaker.LoopOptions { Radius = 60, Points = 6 }, null, portals);
|
||||
CheckLoopRules(r, room, null, portals, "beside a portal");
|
||||
Check(r.Points.All(p => p.X < 151), "all its points in the first room");
|
||||
|
||||
// A live portal (one the client sees) counts the same.
|
||||
var live = new List<PortalAvoid.Spot> { new(200, 96, PortalAvoid.LiveRadius, "Live Portal") };
|
||||
var liveStrict = new TilePathFinder(dir, null, null, live) { StrictPortals = true };
|
||||
liveStrict.LoadArea(0, 0, 400, 192);
|
||||
Check(liveStrict.Leg(a, b, out string ln) == null && ln.Contains("Live Portal"), "a live portal blocks it too: " + ln);
|
||||
}
|
||||
|
||||
private static void LegsRoundABuildingAndOffWalls()
|
||||
{
|
||||
// Two strips of ground joined by a building (a room with a narrow way in from each strip, the two not
|
||||
// in line: its floor is navmesh too) and, the long way, a lane at the west end. In line, Recast made
|
||||
// one thin polygon from strip to strip straight through the room, and a leg's own two polygons are
|
||||
// always allowed, so a leg along that line couldn't be kept out.
|
||||
string dir = Bake("building", (0, 0, 384, 60), (0, 132, 384, 192), (0, 60, 30, 132),
|
||||
(170, 68, 214, 124), (172, 58, 184, 70), (200, 122, 212, 134));
|
||||
var a = new WorldPt(300, 30, double.NaN);
|
||||
var b = new WorldPt(300, 162, double.NaN);
|
||||
var through = new TilePathFinder(dir, null, null);
|
||||
through.LoadArea(0, 0, 384, 192);
|
||||
List<WorldPt>? direct = through.Leg(a, b, out _);
|
||||
Check(direct != null && Enters(direct, 172, 64, 212, 128), "without outlines the leg goes through the building");
|
||||
|
||||
var outline = BuildingOutlines.FromPolygons(new[] { new (double, double)[] { (168, 62), (216, 62), (216, 130), (168, 130) } });
|
||||
var round = new TilePathFinder(dir, null, null) { AvoidArea = (x, y) => outline.Inside(x, y) >= 0 };
|
||||
round.LoadArea(0, 0, 384, 192);
|
||||
List<WorldPt>? outside = round.Leg(a, b, out string note);
|
||||
Check(outside != null && !Enters(outside, 172, 64, 212, 128), "with the outline it goes round by the lane: " + note);
|
||||
Check(outside != null && outside.Any(p => p.X < 32), "...the west lane");
|
||||
// A building that is the only way: through it all the same (keeping off buildings gives way).
|
||||
string only = Bake("buildingonly", (0, 0, 384, 60), (0, 132, 384, 192), (170, 68, 214, 124), (172, 58, 184, 70), (200, 122, 212, 134));
|
||||
var must = new TilePathFinder(only, null, null) { AvoidArea = (x, y) => outline.Inside(x, y) >= 0 };
|
||||
must.LoadArea(0, 0, 384, 192);
|
||||
Check(must.Leg(a, b, out _) != null, "when the building is the only way, through it");
|
||||
|
||||
// Walls: the corners round the end of the wall come off it by the clearance, onto the ground.
|
||||
string wall = Bake("wallcorner", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192));
|
||||
var from = new WorldPt(100, 20, double.NaN);
|
||||
var to = new WorldPt(480, 20, double.NaN);
|
||||
var plain = new TilePathFinder(wall, null, null);
|
||||
plain.LoadArea(0, 0, 576, 192);
|
||||
var pushed = new TilePathFinder(wall, null, null) { WallClearance = 1.0 };
|
||||
pushed.LoadArea(0, 0, 576, 192);
|
||||
List<WorldPt>? p0 = plain.Leg(from, to, out _), p1 = pushed.Leg(from, to, out _);
|
||||
Check(p0 != null && p1 != null && p0.Count == p1.Count, "the same corners with and without the clearance");
|
||||
if (p0 != null && p1 != null && p0.Count == p1.Count)
|
||||
{
|
||||
double moved = 0;
|
||||
for (int i = 1; i < p0.Count - 1; i++) moved = Math.Max(moved, p0[i].FlatDistance(p1[i]));
|
||||
Check(moved > 0.9 && moved < 1.1, $"a corner moved by the clearance ({moved:F2} yd)");
|
||||
Check(p1.All(p => pushed.Snap(p, 0.2, out _, out _)), "every corner still on walkable ground");
|
||||
Check(p0[0].FlatDistance(p1[0]) < 0.01 && p0[^1].FlatDistance(p1[^1]) < 0.01, "the ends never move");
|
||||
}
|
||||
}
|
||||
|
||||
private static void PathThroughGivenPoints()
|
||||
{
|
||||
// The wall again: from the south of tile 0 to the south of tile 2 the only way is round the north.
|
||||
string dir = Bake("pathwall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192), (700, 0, 760, 60));
|
||||
BuildGraph(dir, out NavGraph g);
|
||||
g.BuildComponents();
|
||||
var pts = new List<WorldPt> { new(100, 20, double.NaN), new(480, 20, double.NaN), new(500, 120, double.NaN) };
|
||||
var mesh = new TilePathFinder(dir, g, null) { WallClearance = 1.0 };
|
||||
LoopMaker.Result r = LoopMaker.Path(mesh, pts, NavRouteType.Once, 30, Array.Empty<PortalAvoid.Spot>());
|
||||
Check(r.Ok && r.Legs.Count == 2, $"two legs ({r.Error})");
|
||||
Check(r.Ok && r.Legs[0].Any(p => p.Y > 150), "the first goes north through the passage");
|
||||
Check(r.Ok && r.Route!.RouteType == NavRouteType.Once && r.Route.Points.Count >= 4, "a once route");
|
||||
Check(r.Ok && NavCoords.Distance(r.Route!.Points[0].NS, r.Route.Points[0].EW, pts[0].Ns, pts[0].Ew) < 3
|
||||
&& NavCoords.Distance(r.Route.Points[^1].NS, r.Route.Points[^1].EW, pts[2].Ns, pts[2].Ew) < 3, "it starts and ends at the given points");
|
||||
var back = NavRouteParser.LoadFromLines(r.Route!.ToLines());
|
||||
Check(back.LoadWarning == null && back.Points.Count == r.Route.Points.Count, "RynthAi reads it back");
|
||||
|
||||
var loop = LoopMaker.Path(new TilePathFinder(dir, g, null), pts, NavRouteType.Circular, 30, Array.Empty<PortalAvoid.Spot>());
|
||||
Check(loop.Ok && loop.Legs.Count == 3 && loop.Route!.RouteType == NavRouteType.Circular, "a loop also walks back from the last point to the first");
|
||||
var line = LoopMaker.Path(new TilePathFinder(dir, g, null), pts, NavRouteType.Linear, 30, Array.Empty<PortalAvoid.Spot>());
|
||||
Check(line.Ok && line.Legs.Count == 2 && line.Route!.RouteType == NavRouteType.Linear, "a line doesn't");
|
||||
|
||||
// A point with no ground, a leg that can't be walked, a point in a portal's circle: refused, named.
|
||||
var off = LoopMaker.Path(new TilePathFinder(dir, g, null), new List<WorldPt> { pts[0], new(288, 50, double.NaN), pts[1] }, NavRouteType.Once, 30, Array.Empty<PortalAvoid.Spot>());
|
||||
Check(!off.Ok && off.Error.StartsWith("point 2"), "a point in the gap: " + off.Error);
|
||||
var island = LoopMaker.Path(new TilePathFinder(dir, g, null), new List<WorldPt> { pts[1], new(730, 30, double.NaN) }, NavRouteType.Once, 30, Array.Empty<PortalAvoid.Spot>());
|
||||
Check(!island.Ok && island.Error.StartsWith("leg 1"), "a leg to an island: " + island.Error);
|
||||
var portal = new List<PortalAvoid.Spot> { new(480, 22, PortalAvoid.MapRadius, "Some Portal") };
|
||||
var inPortal = LoopMaker.Path(new TilePathFinder(dir, g, portal), pts, NavRouteType.Once, 30, portal);
|
||||
Check(!inPortal.Ok && inPortal.Error.StartsWith("point 2") && inPortal.Error.Contains("Some Portal"), "a point at a portal: " + inPortal.Error);
|
||||
}
|
||||
|
||||
/// <summary>Yards of the legs inside building outlines (sampled every half yard).</summary>
|
||||
private static double YardsInBuildings(IEnumerable<List<WorldPt>> legs, BuildingOutlines b)
|
||||
{
|
||||
double inside = 0;
|
||||
foreach (List<WorldPt> leg in legs)
|
||||
for (int i = 1; i < leg.Count; i++)
|
||||
{
|
||||
WorldPt p = leg[i - 1], q = leg[i];
|
||||
int n = Math.Max(1, (int)(p.FlatDistance(q) * 2));
|
||||
for (int k = 0; k < n; k++)
|
||||
if (b.Inside(p.X + (q.X - p.X) * (k + 0.5) / n, p.Y + (q.Y - p.Y) * (k + 0.5) / n) >= 0) inside += p.FlatDistance(q) / n;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real map (read only, when it's installed): loops by Holtburg (in town, among its buildings and
|
||||
/// portals, and out on the open ground east of it) with the real building outlines and the Atlas's
|
||||
/// portals, with and without keeping the legs off building floors. Prints the sizes and times.
|
||||
/// </summary>
|
||||
private static void RealLoopsNearHoltburg()
|
||||
{
|
||||
string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData";
|
||||
if (!File.Exists(Path.Combine(dir, "nav_A9B4.tile"))) { Console.WriteLine(" (no real NavData here: skipped)"); return; }
|
||||
BuildingOutlines? buildings = BuildingOutlines.Load(Path.Combine(dir, BuildingOutlines.FileName));
|
||||
var portals = new List<PortalAvoid.Spot>();
|
||||
string tsv = Path.Combine(dir, "portals.tsv");
|
||||
if (File.Exists(tsv))
|
||||
foreach (string line in File.ReadLines(tsv))
|
||||
{
|
||||
string[] f = line.Split('\t');
|
||||
if (f.Length < 5 || !double.TryParse(f[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double ns)
|
||||
|| !double.TryParse(f[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double ew)) continue;
|
||||
portals.Add(new PortalAvoid.Spot(NavCoords.WorldX(ew), NavCoords.WorldY(ns), PortalAvoid.MapRadius, f[4]));
|
||||
}
|
||||
Console.WriteLine($" {buildings?.Count ?? 0} building outlines, {portals.Count} portals");
|
||||
foreach (var (name, ns, ew, radius) in new[] { ("Holtburg", 42.08, 33.6, 60.0), ("east of Holtburg", 42.0, 34.6, 150.0) })
|
||||
{
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
var near = portals.Where(p => Math.Abs(p.X - NavCoords.WorldX(ew)) < radius + 300 && Math.Abs(p.Y - NavCoords.WorldY(ns)) < radius + 300).ToList();
|
||||
var mesh = new TilePathFinder(dir, null, near) { };
|
||||
LoopMaker.Result r = LoopMaker.Loop(mesh, WorldPt.FromMap(ns, ew, double.NaN), new LoopMaker.LoopOptions { Radius = radius, WallClearance = 1.0 }, buildings, near);
|
||||
long ms = sw.ElapsedMilliseconds;
|
||||
Console.WriteLine($" {name}, {radius:F0} yd: {(r.Ok ? $"{r.Points.Count} of {r.Asked} points, {r.Route?.Points.Count} waypoints, {r.Yards:F0} yd a lap" : r.Error)}, "
|
||||
+ $"{r.DroppedPoints.Count} dropped{(r.DroppedPoints.Count > 0 ? $" ({string.Join("; ", r.DroppedPoints.Select(d => d.Why).Distinct())})" : "")}, {mesh.TilesRead} tiles, {ms} ms");
|
||||
CheckLoopRules(r, mesh, buildings, near, name);
|
||||
Check(ms < 30000, $"{name}: in reasonable time ({ms} ms)");
|
||||
if (buildings == null || !r.Ok) continue;
|
||||
// The same loop with the legs free to cross building floors: they go through at least as much.
|
||||
LoopMaker.Result free = LoopMaker.Loop(new TilePathFinder(dir, null, near), WorldPt.FromMap(ns, ew, double.NaN),
|
||||
new LoopMaker.LoopOptions { Radius = radius, WallClearance = 1.0, LegsRoundBuildings = false }, buildings, near);
|
||||
double kept = YardsInBuildings(r.Legs, buildings), loose = free.Ok ? YardsInBuildings(free.Legs, buildings) : double.NaN;
|
||||
Console.WriteLine($" legs inside building outlines: {kept:F0} yd kept off them, {loose:F0} yd free ({free.Yards:F0} yd a lap)");
|
||||
Check(!free.Ok || kept <= loose + 1, $"{name}: keeping legs off buildings doesn't put more of them inside ({kept:F0} vs {loose:F0} yd)");
|
||||
}
|
||||
|
||||
// A path from Holtburg out east and back up north, on the route graph, never through a portal's circle.
|
||||
string graphFile = Path.Combine(dir, NavGraph.FileName);
|
||||
if (!File.Exists(graphFile)) return;
|
||||
NavGraph g = NavGraph.Load(graphFile);
|
||||
g.BuildComponents();
|
||||
var pts = new List<WorldPt> { WorldPt.FromMap(42.0, 33.9, double.NaN), WorldPt.FromMap(41.6, 35.2, double.NaN), WorldPt.FromMap(42.4, 35.6, double.NaN) };
|
||||
var sw2 = System.Diagnostics.Stopwatch.StartNew();
|
||||
var finder = new TilePathFinder(dir, g, portals) { StrictPortals = true, WallClearance = 1.0 };
|
||||
LoopMaker.Result p = LoopMaker.Path(finder, pts, NavRouteType.Once, 30, portals);
|
||||
Console.WriteLine($" a path east of Holtburg: {(p.Ok ? $"{p.Legs.Count} legs, {p.Route?.Points.Count} waypoints, {p.Yards:F0} yd" : p.Error)}, {finder.TilesRead} tiles, {sw2.ElapsedMilliseconds} ms");
|
||||
Check(p.Ok && p.Legs.Count == 2, "the real path: two legs " + p.Error);
|
||||
if (p.Ok)
|
||||
foreach (List<WorldPt> leg in p.Legs)
|
||||
foreach (PortalAvoid.Spot s in portals.Where(s => Math.Abs(s.X - pts[1].X) < 1000 && Math.Abs(s.Y - pts[1].Y) < 1000))
|
||||
Check(MinGap(leg, s.X, s.Y) >= s.R - 0.06, $"the real path keeps out of {s.Name}");
|
||||
}
|
||||
}
|
||||
|
|
@ -36,6 +36,16 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavCoords.cs" Link="Linked\NavCoords.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TownNet.cs" Link="Linked\TownNet.cs" />
|
||||
<Compile Include="..\RynthNav.PortalGraph\PortalRoute.cs" Link="Linked\PortalRoute.cs" />
|
||||
<!-- The route maker on the navmesh (RouteMakerTests): loops, legs, paths, and what they're written as. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\LoopMaker.cs" Link="Linked\LoopMaker.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AreaFilter.cs" Link="Linked\AreaFilter.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RouteShape.cs" Link="Linked\RouteShape.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\BuildingOutlines.cs" Link="Linked\BuildingOutlines.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RouteRequest.cs" Link="Linked\RouteRequest.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RouteInfo.cs" Link="Linked\RouteInfo.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RouteJobs.cs" Link="Linked\RouteJobs.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavRouteExport.cs" Link="Linked\NavRouteExport.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\LegacyUi\NavRouteParser.cs" Link="Linked\NavRouteParser.cs" />
|
||||
<!-- "RynthNav.Path" v2 (FindPathEx, Raycast) and the walker's planning steps it shares; the contract it answers. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavPathQuery.cs" Link="Linked\NavPathQuery.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthNavPathApi.cs" Link="Linked\RynthNavPathApi.cs" />
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ internal static partial class Program
|
|||
RunTravelPlan();
|
||||
RunTripExport();
|
||||
RunAutoRunGate();
|
||||
RunRouteMaker();
|
||||
RunSteering();
|
||||
|
||||
Console.WriteLine();
|
||||
|
|
|
|||
513
Tools/RynthNav.RouteTests/RouteMakerTests.cs
Normal file
513
Tools/RynthNav.RouteTests/RouteMakerTests.cs
Normal file
|
|
@ -0,0 +1,513 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthNav.RouteTests;
|
||||
|
||||
// The route maker's parts that need no navmesh (RynthNavPlugin.RouteMaker.cs): what a /rnav command and
|
||||
// the "RynthNav.Routes" JSON are read as and what they refuse (RouteRequest), the job table and its
|
||||
// states (RouteJobTable), a loop's order and the joined legs as a nav file RynthAi reads back
|
||||
// (RouteShape), what a saved nav is (RouteInfo, on a made-up file and the real NavProfiles when they're
|
||||
// here, read only), a plan's figures (TripSummary) and the building outlines file (BuildingOutlines).
|
||||
// The navmesh side (choosing loop points, joining legs) is in RynthNav.GraphTests.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunRouteMaker()
|
||||
{
|
||||
Run(nameof(RouteNameRules), RouteNameRules);
|
||||
Run(nameof(RouteJsonRequests), RouteJsonRequests);
|
||||
Run(nameof(RouteJsonRefusals), RouteJsonRefusals);
|
||||
Run(nameof(RouteChatCommands), RouteChatCommands);
|
||||
Run(nameof(RouteJobStates), RouteJobStates);
|
||||
Run(nameof(LoopOrderNoCrossings), LoopOrderNoCrossings);
|
||||
Run(nameof(LoopNavWrittenAndReadBack), LoopNavWrittenAndReadBack);
|
||||
Run(nameof(RouteInfoOnASampleFile), RouteInfoOnASampleFile);
|
||||
Run(nameof(RouteInfoOnRealNavProfiles), RouteInfoOnRealNavProfiles);
|
||||
Run(nameof(PlanSummaryFigures), PlanSummaryFigures);
|
||||
Run(nameof(BuildingOutlinesFile), BuildingOutlinesFile);
|
||||
}
|
||||
|
||||
private static RouteRequest? Json(string json) => RouteRequest.FromJson(json, out _);
|
||||
|
||||
private static string JsonError(string json)
|
||||
{
|
||||
RouteRequest? r = RouteRequest.FromJson(json, out string error);
|
||||
return r == null ? error : "";
|
||||
}
|
||||
|
||||
// ── Names ────────────────────────────────────────────────────────────
|
||||
|
||||
private static void RouteNameRules()
|
||||
{
|
||||
// saveroute's rules, the same for every make op: chat and JSON.
|
||||
Check(RouteRequest.FromCommand("makeloop", "Hunt 1 radius 50", out _)?.Name == "Hunt 1", "a plain name");
|
||||
Check(RouteRequest.FromCommand("makeloop", "Hunt 1.nav radius 50", out _)?.Name == "Hunt 1", ".nav is dropped");
|
||||
Check(RouteRequest.FromCommand("makeloop", "a\\b radius 50", out string e1) == null && e1.Contains("file name"), "a path isn't a name: " + e1);
|
||||
Check(RouteRequest.FromCommand("makeloop", "a:b radius 50", out _) == null, "nor characters a file can't have");
|
||||
Check(RouteRequest.FromCommand("makeloop", ".. radius 50", out _) == null, "nor ..");
|
||||
Check(RouteRequest.FromCommand("makeloop", new string('x', 101) + " radius 50", out _) == null, "nor over 100 characters");
|
||||
Check(RouteRequest.FromCommand("routeinfo", "", out string e2) == null && e2.Length > 0, "routeinfo needs a name");
|
||||
Check(Json("{\"op\":\"info\",\"name\":\"../x\"}") == null, "JSON: a path is refused too");
|
||||
Check(Json("{\"op\":\"makeloop\",\"name\":\"\",\"radius\":50}") == null, "JSON: an empty name is refused");
|
||||
Check(Json("{\"op\":\"makeloop\",\"name\":\"Loop A\",\"radius\":50}")?.Overwrite == false, "never overwrite unless asked");
|
||||
Check(Json("{\"op\":\"makeloop\",\"name\":\"Loop A\",\"radius\":50,\"overwrite\":true}")?.Overwrite == true, "overwrite: true asks");
|
||||
Check(RouteRequest.FromCommand("makeloop", "Loop A radius 50 overwrite", out _)?.Overwrite == true, "chat: overwrite at the end");
|
||||
Check(RouteRequest.FromCommand("makeloop", "Loop A radius 50", out _)?.Overwrite == false, "chat: not without it");
|
||||
|
||||
// An existing file stays unless overwrite (the same NavRouteExport.Save the jobs use).
|
||||
string dir = Path.Combine(Path.GetTempPath(), "rnav-maker-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var a = new NavRouteParser { RouteType = NavRouteType.Circular };
|
||||
a.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1, EW = 1 });
|
||||
a.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1.1, EW = 1 });
|
||||
Check(NavRouteExport.Save(dir, "Loop A", a, false, out string file, out _, out _), "a new loop is written");
|
||||
var b = new NavRouteParser { RouteType = NavRouteType.Once };
|
||||
b.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 5, EW = 5 });
|
||||
Check(!NavRouteExport.Save(dir, "Loop A", b, false, out _, out bool exists, out _) && exists, "the same name: refused");
|
||||
Check(NavRouteParser.Load(file).RouteType == NavRouteType.Circular, "and the file is the first one still");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
// ── JSON in ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void RouteJsonRequests()
|
||||
{
|
||||
RouteRequest? p = Json("{\"op\":\"plan\",\"to\":\"Holtburg\",\"portals\":true}");
|
||||
Check(p != null && p.Op == RouteOp.Plan && p.To == "Holtburg" && p.Portals == true && !p.Show && !p.FromChat, "plan to a place, portals on");
|
||||
RouteRequest? pc = Json("{\"op\":\"plan\",\"to\":{\"ns\":42.1234,\"ew\":-33.5}}");
|
||||
Check(pc != null && pc.Portals == null, "plan without portals: the switch");
|
||||
Check(pc != null && NavCoords.TryParseLoc(pc.To, out double tns, out double tew) && Math.Abs(tns - 42.1234) < 1e-9 && Math.Abs(tew + 33.5) < 1e-9,
|
||||
"coordinates kept exactly as text /rnav go reads: " + pc?.To);
|
||||
|
||||
RouteRequest? mr = Json("{\"op\":\"makeroute\",\"name\":\"To Holtburg\",\"to\":\"Holtburg\",\"overwrite\":true,\"show\":true}");
|
||||
Check(mr != null && mr.Op == RouteOp.MakeRoute && mr.Name == "To Holtburg" && mr.Overwrite && mr.Show, "makeroute");
|
||||
|
||||
RouteRequest? ml = Json("{\"op\":\"makeloop\",\"name\":\"Hunt\",\"radius\":80,\"points\":8}");
|
||||
Check(ml != null && ml.Op == RouteOp.MakeLoop && ml.Here && ml.Radius == 80 && ml.Points == 8, "makeloop here (no at)");
|
||||
RouteRequest? mla = Json("{\"op\":\"makeloop\",\"name\":\"Hunt\",\"at\":{\"ns\":10.5,\"ew\":-20.25},\"radius\":20}");
|
||||
Check(mla != null && !mla.Here && mla.AtNs == 10.5 && mla.AtEw == -20.25 && mla.Points == 0, "makeloop at coordinates, default points");
|
||||
RouteRequest? mls = Json("{\"op\":\"makeloop\",\"name\":\"Hunt\",\"at\":\"10.5N, 20.25W\",\"radius\":250}");
|
||||
Check(mls != null && !mls.Here && mls.AtNs == 10.5 && mls.AtEw == -20.25, "makeloop at a coordinate string, radius at the cap");
|
||||
Check(Json("{\"op\":\"makeloop\",\"name\":\"Hunt\",\"at\":\"here\",\"radius\":20}")?.Here == true, "at here");
|
||||
|
||||
RouteRequest? mp = Json("{\"op\":\"makepath\",\"name\":\"Ridge\",\"type\":\"loop\",\"points\":[{\"ns\":1,\"ew\":2},\"1.1N, 2.1E\",{\"ns\":1.2,\"ew\":2}]}");
|
||||
Check(mp != null && mp.PathType == NavRouteType.Circular && mp.Path.Count == 3 && mp.Path[1] == (1.1, 2.1), "makepath loop with mixed points");
|
||||
Check(Json("{\"op\":\"makepath\",\"name\":\"R\",\"type\":\"line\",\"points\":[\"1N 1E\",\"1.1N 1E\"]}")?.PathType == NavRouteType.Linear, "type line = linear");
|
||||
Check(Json("{\"op\":\"makepath\",\"name\":\"R\",\"points\":[\"1N 1E\",\"1.1N 1E\"]}")?.PathType == NavRouteType.Once, "no type = once");
|
||||
|
||||
RouteRequest? at = Json("{\"op\":\"atlas\",\"search\":\" holt \",\"max\":5}");
|
||||
Check(at != null && at.Search == "holt" && at.Max == 5, "atlas");
|
||||
Check(Json("{\"op\":\"atlas\",\"search\":\"holt\"}")?.Max == RouteLimits.DefaultAtlas, "atlas: max defaults");
|
||||
Check(Json("{\"op\":\"info\",\"name\":\"Hunt.nav\"}")?.Name == "Hunt", "info");
|
||||
Check(Json("{\"op\":\"go\",\"to\":\"Holtburg\"}")?.Op == RouteOp.Go, "go");
|
||||
Check(Json("{\"op\":\"stop\"}")?.Op == RouteOp.Stop && Json("{\"op\":\"WHERE\"}")?.Op == RouteOp.Where, "stop, where (any case)");
|
||||
Check(Json("{\"op\":\"where\",\"something\":\"new\"}") != null, "unknown fields are ignored");
|
||||
}
|
||||
|
||||
private static void RouteJsonRefusals()
|
||||
{
|
||||
string[] bad =
|
||||
{
|
||||
"", " ", "not json", "[1,2]", "{}", "{\"op\":3}", "{\"op\":\"teleport\"}",
|
||||
"{\"op\":\"plan\"}", "{\"op\":\"plan\",\"to\":\"\"}", "{\"op\":\"plan\",\"to\":5}", "{\"op\":\"plan\",\"to\":{\"ns\":1}}",
|
||||
"{\"op\":\"plan\",\"to\":{\"ns\":200,\"ew\":1}}", "{\"op\":\"plan\",\"to\":\"150N, 2E\"}", "{\"op\":\"plan\",\"to\":\"X\",\"portals\":\"yes\"}",
|
||||
"{\"op\":\"makeroute\",\"to\":\"X\"}", "{\"op\":\"makeroute\",\"name\":\"A\"}",
|
||||
"{\"op\":\"makeloop\",\"name\":\"A\"}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":\"80\"}",
|
||||
"{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":19}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":251}",
|
||||
"{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"points\":2}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"points\":17}",
|
||||
"{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"points\":4.5}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"at\":\"there\"}",
|
||||
"{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"at\":{\"ns\":1,\"ew\":-300}}", "{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":80,\"overwrite\":1}",
|
||||
"{\"op\":\"makepath\",\"name\":\"A\",\"points\":[\"1N 1E\"]}", "{\"op\":\"makepath\",\"name\":\"A\",\"points\":\"1N 1E; 2N 2E\"}",
|
||||
"{\"op\":\"makepath\",\"name\":\"A\",\"type\":\"zigzag\",\"points\":[\"1N 1E\",\"2N 2E\"]}",
|
||||
"{\"op\":\"makepath\",\"name\":\"A\",\"points\":[\"1N 1E\",\"somewhere\"]}",
|
||||
"{\"op\":\"makepath\",\"name\":\"A\",\"points\":[\"1N 1E\",\"90N 90E\"]}",
|
||||
"{\"op\":\"atlas\"}", "{\"op\":\"atlas\",\"search\":\" \"}", "{\"op\":\"atlas\",\"search\":\"a\",\"max\":0}", "{\"op\":\"atlas\",\"search\":\"a\",\"max\":51}",
|
||||
"{\"op\":\"info\"}", "{\"op\":\"go\"}",
|
||||
};
|
||||
foreach (string b in bad)
|
||||
{
|
||||
string why = JsonError(b);
|
||||
Check(why.Length > 0, $"refused: {b}");
|
||||
}
|
||||
var many = new System.Text.StringBuilder("{\"op\":\"makepath\",\"name\":\"A\",\"points\":[");
|
||||
for (int i = 0; i < RouteLimits.MaxPathPoints + 1; i++) many.Append(i > 0 ? "," : "").Append("{\"ns\":1,\"ew\":").Append(1 + i * 0.01).Append('}');
|
||||
Check(JsonError(many.Append("]}").ToString()).Contains("too many"), "33 points: too many");
|
||||
Check(JsonError("{\"op\":\"where\",\"pad\":\"" + new string('x', RouteLimits.MaxJson) + "\"}").Contains("characters"), "a request over 16 KB");
|
||||
Check(JsonError("{\"op\":\"teleport\"}").Contains("makeloop"), "an unknown op lists the ones there are");
|
||||
Check(JsonError("{\"op\":\"makeloop\",\"name\":\"A\",\"radius\":300}").Contains("20-250"), "out of range says the range");
|
||||
Check(RouteRequest.UsageFor("{\"op\":\"makeloop\"}").Contains("\"radius\""), "the usage for a known op is its JSON form");
|
||||
Check(RouteRequest.UsageFor("junk").Contains("makepath"), "...and the op list otherwise");
|
||||
string err = RouteJson.Error("why \"quoted\"", "use \\ this");
|
||||
using JsonDocument d = JsonDocument.Parse(err);
|
||||
Check(d.RootElement.GetProperty("error").GetString() == "why \"quoted\"" && d.RootElement.GetProperty("usage").GetString() == "use \\ this", "the refusal is valid JSON, escaped");
|
||||
}
|
||||
|
||||
// ── Chat in ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void RouteChatCommands()
|
||||
{
|
||||
RouteRequest? a = RouteRequest.FromCommand("makeroute", "To Town to Holtburg", out string e0);
|
||||
Check(a != null && a.Op == RouteOp.MakeRoute && a.Name == "To Town" && a.To == "Holtburg" && a.FromChat && a.Show, "makeroute <name> to <place>: " + e0);
|
||||
RouteRequest? b = RouteRequest.FromCommand("makeroute", "Cragstone run to Portal to Cragstone overwrite", out _);
|
||||
Check(b != null && b.Name == "Cragstone run" && b.To == "Portal to Cragstone" && b.Overwrite, "the first \" to \" ends the name; overwrite at the end");
|
||||
RouteRequest? c = RouteRequest.FromCommand("makeroute", "\"Go to the hill\" to 42.1N, 33.6E", out _);
|
||||
Check(c != null && c.Name == "Go to the hill" && c.To == "42.1N, 33.6E", "a quoted name may hold \" to \"");
|
||||
Check(RouteRequest.FromCommand("makeroute", "Holtburg", out string e1) == null && e1.Contains(" to "), "makeroute without to: refused");
|
||||
Check(RouteRequest.FromCommand("makeroute", "A to 150N, 2E", out _) == null, "makeroute to coordinates off the map: refused");
|
||||
|
||||
RouteRequest? l1 = RouteRequest.FromCommand("makeloop", "Hunt at the lake radius 60", out _);
|
||||
Check(l1 != null && l1.Name == "Hunt at the lake" && l1.Here && l1.Radius == 60 && l1.Points == 0, "a name with 'at' in it, round here");
|
||||
RouteRequest? l2 = RouteRequest.FromCommand("makeloop", "Hunt at 42.1N, 33.6E radius 80 points 6 overwrite", out string e2);
|
||||
Check(l2 != null && l2.Name == "Hunt" && !l2.Here && l2.AtNs == 42.1 && l2.AtEw == 33.6 && l2.Radius == 80 && l2.Points == 6 && l2.Overwrite, "at coords, points, overwrite: " + e2);
|
||||
RouteRequest? l3 = RouteRequest.FromCommand("makeloop", "Hunt radius 40 at 1.5S 2.5W", out _);
|
||||
Check(l3 != null && !l3.Here && l3.AtNs == -1.5 && l3.AtEw == -2.5, "the options in any order");
|
||||
RouteRequest? l4 = RouteRequest.FromCommand("makeloop", "Hunt here radius 40", out _);
|
||||
Check(l4 != null && l4.Here && l4.Name == "Hunt", "here");
|
||||
Check(RouteRequest.FromCommand("makeloop", "Hunt", out string e3) == null && e3.Contains("radius"), "no radius: refused (" + e3 + ")");
|
||||
Check(RouteRequest.FromCommand("makeloop", "Hunt radius 500", out string e4) == null && e4.Contains("20-250"), "radius over the cap: refused (" + e4 + ")");
|
||||
Check(RouteRequest.FromCommand("makeloop", "Hunt radius 50 points 40", out string e5) == null && e5.Contains("3-16"), "too many points: refused");
|
||||
Check(RouteRequest.FromCommand("makeloop", "Hunt radius fifty", out _) == null, "radius not a number: refused");
|
||||
Check(RouteRequest.FromCommand("makeloop", "Hunt at 999N 2E radius 50", out string e6) == null && e6.Contains("off the map"), "at coordinates off the map: refused (" + e6 + ")");
|
||||
RouteRequest? l5 = RouteRequest.FromCommand("makeloop", "Hunt at nowhere radius 50", out _);
|
||||
Check(l5 != null && l5.Name == "Hunt at nowhere" && l5.Here, "'at' followed by words, not coordinates, is part of the name");
|
||||
Check(RouteRequest.FromCommand("makeloop", "radius 50", out _) == null, "no name: refused");
|
||||
RouteRequest? lq = RouteRequest.FromCommand("makeloop", "\"Hunt at 42N 33E\" radius 60 overwrite", out string eq);
|
||||
Check(lq != null && lq.Name == "Hunt at 42N 33E" && lq.Here && lq.Radius == 60 && lq.Overwrite, "a quoted name holds anything: " + eq);
|
||||
Check(RouteRequest.FromCommand("makeloop", "\"Hunt radius 60", out string eq2) == null && eq2.Contains("quote"), "an unclosed quote: refused");
|
||||
|
||||
RouteRequest? p1 = RouteRequest.FromCommand("makepath", "Ridge walk loop 42.1N 33.6E; 42.3N, 33.9E; 42.0N 34.0E overwrite", out string e7);
|
||||
Check(p1 != null && p1.Name == "Ridge walk" && p1.PathType == NavRouteType.Circular && p1.Path.Count == 3 && p1.Overwrite
|
||||
&& p1.Path[0] == (42.1, 33.6) && p1.Path[2] == (42.0, 34.0), "makepath name, type, points, overwrite: " + e7);
|
||||
RouteRequest? p2 = RouteRequest.FromCommand("makepath", "Route 1 42 33; 42.1 33.1", out _);
|
||||
Check(p2 != null && p2.Name == "Route 1" && p2.PathType == NavRouteType.Once && p2.Path.Count == 2, "a number in the name; no type = once");
|
||||
RouteRequest? p3 = RouteRequest.FromCommand("makepath", "Back and forth line 1N 1E; 1.1N 1E;", out _);
|
||||
Check(p3 != null && p3.PathType == NavRouteType.Linear && p3.Path.Count == 2, "line; a trailing ; is fine");
|
||||
Check(RouteRequest.FromCommand("makepath", "Solo 1N 1E", out string e8) == null && e8.Contains("at least"), "one point: refused");
|
||||
Check(RouteRequest.FromCommand("makepath", "Bad 1N 1E; up the hill", out string e9) == null && e9.Contains("point 2"), "a point that isn't coordinates: refused, naming it");
|
||||
Check(RouteRequest.FromCommand("makepath", "Far 0N 0E; 80N 80E", out string e10) == null && e10.Contains("leg 1"), "a leg too long: refused, naming it");
|
||||
Check(RouteRequest.FromCommand("makepath", "Nothing", out _) == null, "no points: refused");
|
||||
RouteRequest? pq = RouteRequest.FromCommand("makepath", "\"Ridge, east\" loop 1N 1E; 1.1N 1E", out string e11);
|
||||
Check(pq != null && pq.Name == "Ridge, east" && pq.PathType == NavRouteType.Circular && pq.Path.Count == 2, "makepath with a quoted name: " + e11);
|
||||
|
||||
Check(RouteRequest.FromCommand("routeinfo", "Hunt", out _)?.Op == RouteOp.Info, "routeinfo");
|
||||
Check(RouteRequest.FromCommand("routeinfo", "\"Hunt\" extra", out _) == null, "routeinfo takes only the name");
|
||||
Check(RouteRequest.Usage(RouteOp.MakeLoop, chat: true).StartsWith("/rnav makeloop"), "the chat usage line");
|
||||
}
|
||||
|
||||
// ── Jobs ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void RouteJobStates()
|
||||
{
|
||||
var t = new RouteJobTable(5000);
|
||||
RouteJob? j1 = t.Add(Json("{\"op\":\"where\"}")!, 100, out string err);
|
||||
Check(j1 != null && j1.Id == 5000 && j1.State == RouteJobState.Queued && err == "", "a new job is queued, with the first id");
|
||||
RouteJob? j2 = t.Add(Json("{\"op\":\"stop\"}")!, 100, out _);
|
||||
Check(j2 != null && j2.Id == 5001, "ids go up");
|
||||
Check(t.Queued().Count == 2 && t.Queued()[0] == j1, "the queue, oldest first");
|
||||
|
||||
using (JsonDocument a = JsonDocument.Parse(t.Accepted(j1!)))
|
||||
Check(a.RootElement.GetProperty("id").GetInt32() == 5000 && a.RootElement.GetProperty("state").GetString() == "queued"
|
||||
&& a.RootElement.GetProperty("op").GetString() == "where" && a.RootElement.GetProperty("result").ValueKind == JsonValueKind.Null,
|
||||
"Request's answer: id, op, queued, no result yet");
|
||||
|
||||
t.Start(j1!, "working on it", 110);
|
||||
using (JsonDocument w = JsonDocument.Parse(t.PollJson(5000, out bool known)))
|
||||
Check(known && w.RootElement.GetProperty("state").GetString() == "working" && w.RootElement.GetProperty("detail").GetString() == "working on it", "working");
|
||||
t.Update(j1!, "nearly", "{\"partial\":1}");
|
||||
t.Finish(j1!, true, "done it", "{\"answer\":42}", 120);
|
||||
using (JsonDocument d = JsonDocument.Parse(t.PollJson(5000, out _)))
|
||||
Check(d.RootElement.GetProperty("state").GetString() == "done" && d.RootElement.GetProperty("result").GetProperty("answer").GetInt32() == 42, "done, with the result");
|
||||
t.Finish(j1!, false, "changed my mind", null, 130);
|
||||
Check(j1!.State == RouteJobState.Done && j1.Detail == "done it", "a finished job stays as it ended");
|
||||
t.Start(j1, "again", 140);
|
||||
Check(j1.State == RouteJobState.Done, "...and can't be started again");
|
||||
|
||||
t.Finish(j2!, false, "no player position yet", RouteJson.Error("no player position yet", ""), 150);
|
||||
using (JsonDocument f = JsonDocument.Parse(t.PollJson(5001, out _)))
|
||||
Check(f.RootElement.GetProperty("state").GetString() == "failed" && f.RootElement.GetProperty("result").GetProperty("error").GetString() == "no player position yet", "failed, with why");
|
||||
using (JsonDocument u = JsonDocument.Parse(t.PollJson(4999, out bool k2)))
|
||||
Check(!k2 && u.RootElement.GetProperty("state").GetString() == "unknown" && u.RootElement.GetProperty("error").GetString()!.Length > 0, "an id never given: unknown");
|
||||
|
||||
// The last 32: finished jobs make room, oldest first; 32 unfinished refuse a 33rd.
|
||||
var full = new RouteJobTable(1);
|
||||
var first = full.Add(Json("{\"op\":\"where\"}")!, 0, out _)!;
|
||||
full.Finish(first, true, "ok", null, 1);
|
||||
for (int i = 1; i < RouteJobTable.Capacity; i++) full.Add(Json("{\"op\":\"where\"}")!, i, out _);
|
||||
Check(full.Count == RouteJobTable.Capacity, "32 kept");
|
||||
RouteJob? next = full.Add(Json("{\"op\":\"where\"}")!, 99, out _);
|
||||
Check(next != null && full.Get(first.Id) == null && full.Count == RouteJobTable.Capacity, "the 33rd drops the oldest finished job");
|
||||
RouteJob? refused = full.Add(Json("{\"op\":\"where\"}")!, 100, out string why);
|
||||
Check(refused == null && why.Contains("32"), "with all 32 unfinished, a new one is refused: " + why);
|
||||
Check(!full.PollJson(first.Id, out bool gone).Contains("\"done\"") && !gone, "a dropped job is unknown");
|
||||
Check(RouteJobTable.StateName(RouteJobState.Working) == "working" && RouteJobTable.StateName(RouteJobState.Failed) == "failed", "state names");
|
||||
|
||||
// A go job's end, from the goto's own lines (FinishGoto, Entrance, a stop).
|
||||
Check(RouteJobTable.GoOutcome("arrived", out string o1) && o1 == "arrived", "arrived: done");
|
||||
Check(RouteJobTable.GoOutcome(Entrance.ArrivedText("Matron Hive", "Dungeon"), out string o2) && o2 == "arrived", "into a dungeon: arrived");
|
||||
Check(RouteJobTable.GoOutcome(Entrance.ArrivedText("Portal to X", "Portal"), out string o3) && o3 == "arrived", "through a portal: arrived");
|
||||
Check(RouteJobTable.GoOutcome("stopped", out string o4) && o4 == "stopped", "a stop: done, stopped");
|
||||
Check(!RouteJobTable.GoOutcome("stopped: no progress for 30 s, 12u short (off navmesh)", out string o5) && o5 == "failed", "the watchdog: failed");
|
||||
Check(!RouteJobTable.GoOutcome(Entrance.NoTeleportText("Matron Hive"), out _), "a portal that didn't take you in: failed");
|
||||
Check(!RouteJobTable.GoOutcome("stopped: logged out", out _) && !RouteJobTable.GoOutcome("recall step lost — stopped", out _), "logged out, a lost recall: failed");
|
||||
}
|
||||
|
||||
// ── Loops: order and the nav file ────────────────────────────────────
|
||||
|
||||
private static void LoopOrderNoCrossings()
|
||||
{
|
||||
var c = new WorldPt(5000, 5000, 0);
|
||||
var rnd = new Random(7);
|
||||
for (int trial = 0; trial < 50; trial++)
|
||||
{
|
||||
int n = 3 + rnd.Next(14);
|
||||
var pts = new List<WorldPt>();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
double a = rnd.NextDouble() * 2 * Math.PI, r = 30 + rnd.NextDouble() * 120;
|
||||
pts.Add(new WorldPt(c.X + Math.Sin(a) * r, c.Y + Math.Cos(a) * r, 0));
|
||||
}
|
||||
int[] order = RouteShape.OrderLoop(pts, c);
|
||||
Check(order.Length == n && order.Distinct().Count() == n, $"trial {trial}: every point once");
|
||||
var loop = order.Select(i => pts[i]).ToList();
|
||||
Check(RouteShape.Crossings(loop, closed: true) == 0, $"trial {trial}: no two legs cross ({n} points)");
|
||||
}
|
||||
// A star-shaped set given in a tangled order comes out round the centre, from the north, clockwise.
|
||||
var star = new List<WorldPt> { new(5100, 5000, 0), new(4900, 5000, 0), new(5000, 5100, 0), new(5000, 4900, 0) }; // E, W, N, S
|
||||
int[] o = RouteShape.OrderLoop(star, c);
|
||||
Check(o.SequenceEqual(new[] { 2, 0, 3, 1 }), "N, E, S, W: " + string.Join(",", o));
|
||||
Check(RouteShape.Crossings(new List<WorldPt> { new(0, 0, 0), new(10, 10, 0), new(10, 0, 0), new(0, 10, 0) }, closed: true) == 1, "a bow tie crosses once");
|
||||
Check(RouteShape.DefaultPoints(20) == 4 && RouteShape.DefaultPoints(80) == 11 && RouteShape.DefaultPoints(250) == 12, "default points: about one per 45 yd, 4 to 12");
|
||||
}
|
||||
|
||||
private static void LoopNavWrittenAndReadBack()
|
||||
{
|
||||
// Three legs round a triangle, the last back to the start; corners and heights along them.
|
||||
WorldPt a = WorldPt.FromMap(10, 10, 50), b = WorldPt.FromMap(10.3, 10, 52), cc = WorldPt.FromMap(10.15, 10.3, 51);
|
||||
List<WorldPt> Leg(WorldPt p, WorldPt q)
|
||||
{
|
||||
var l = new List<WorldPt>();
|
||||
for (int i = 0; i <= 40; i++) { double t = i / 40.0; l.Add(new WorldPt(p.X + (q.X - p.X) * t + Math.Sin(t * Math.PI) * 6, p.Y + (q.Y - p.Y) * t, p.H + (q.H - p.H) * t)); }
|
||||
return l;
|
||||
}
|
||||
var legs = new List<IReadOnlyList<WorldPt>> { Leg(a, b), Leg(b, cc), Leg(cc, a) };
|
||||
NavRouteParser route = RouteShape.Assemble(legs, NavRouteType.Circular, RouteShape.LoopSpacing, out double yards);
|
||||
Check(route.RouteType == NavRouteType.Circular, "a circular route");
|
||||
Check(NavCoords.Distance(route.Points[0].NS, route.Points[0].EW, a.Ns, a.Ew) < 0.01, "it starts at the first point");
|
||||
Check(NavCoords.Distance(route.Points[^1].NS, route.Points[^1].EW, a.Ns, a.Ew) > 1, "and doesn't repeat it at the end (RynthAi walks back to it)");
|
||||
Check(route.Points.All(p => p.Type == NavPointType.Point), "all walking points");
|
||||
double gap = 0;
|
||||
for (int i = 0; i < route.Points.Count; i++)
|
||||
{
|
||||
NavPoint p = route.Points[i], q = route.Points[(i + 1) % route.Points.Count];
|
||||
gap = Math.Max(gap, NavCoords.Distance(p.NS, p.EW, q.NS, q.EW));
|
||||
}
|
||||
Check(gap <= RouteShape.LoopSpacing + 0.5, $"a point at least every {RouteShape.LoopSpacing} yd ({gap:F1})");
|
||||
Check(route.Points.Count < 3 * 41, "thinned, not every input point");
|
||||
Check(route.Points.All(p => p.Z > 49.0 / 240 && p.Z < 53.0 / 240), "heights as nav Z (metres / 240)");
|
||||
Check(Math.Abs(yards - RouteInfo.Length(route)) < 1.0, $"its yards are the file's walking length, the lap closed ({yards:F1} / {RouteInfo.Length(route):F1})");
|
||||
|
||||
string dir = Path.Combine(Path.GetTempPath(), "rnav-loop-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
Check(NavRouteExport.Save(dir, "Triangle", route, false, out string file, out _, out string err), "saved: " + err);
|
||||
NavRouteParser back = NavRouteParser.Load(file);
|
||||
Check(back.LoadWarning == null && back.RouteType == NavRouteType.Circular && back.Points.Count == route.Points.Count, "RynthAi's reader takes it whole");
|
||||
bool same = true;
|
||||
for (int i = 0; i < back.Points.Count; i++)
|
||||
same &= back.Points[i].Type == NavPointType.Point && Math.Abs(back.Points[i].NS - route.Points[i].NS) < 1e-9
|
||||
&& Math.Abs(back.Points[i].EW - route.Points[i].EW) < 1e-9 && Math.Abs(back.Points[i].Z - route.Points[i].Z) < 1e-9;
|
||||
Check(same, "every point the same after the round trip");
|
||||
string[] lines = File.ReadAllLines(file);
|
||||
Check(lines[0] == "uTank2 NAV 1.2" && lines[1] == "1" && lines[2] == route.Points.Count.ToString(), "the VTank header: type 1 (circular), the count");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
|
||||
// Once and linear keep both ends.
|
||||
var once = RouteShape.Assemble(new List<IReadOnlyList<WorldPt>> { Leg(a, b) }, NavRouteType.Once, 30, out _);
|
||||
Check(NavCoords.Distance(once.Points[^1].NS, once.Points[^1].EW, b.Ns, b.Ew) < 0.01 && once.RouteType == NavRouteType.Once, "once ends at the last point");
|
||||
}
|
||||
|
||||
// ── routeinfo ────────────────────────────────────────────────────────
|
||||
|
||||
private static void RouteInfoOnASampleFile()
|
||||
{
|
||||
// A trip: walk 3 points, a recall, walk 2, a portal, walk 2 more (in a dungeon landblock), a chat and a pause.
|
||||
var r = new NavRouteParser { RouteType = NavRouteType.Once };
|
||||
void P(NavPointType t, double ns, double ew, Action<NavPoint>? f = null) { var p = new NavPoint { Type = t, NS = ns, EW = ew }; f?.Invoke(p); r.Points.Add(p); }
|
||||
P(NavPointType.Point, 10.0, 10.0); P(NavPointType.Point, 10.1, 10.0); P(NavPointType.Point, 10.1, 10.1);
|
||||
P(NavPointType.Recall, 10.1, 10.1, p => p.SpellId = 1635);
|
||||
P(NavPointType.Point, 40.0, 40.0); P(NavPointType.Point, 40.0, 40.2);
|
||||
P(NavPointType.PortalNPC, 40.0, 40.25, p => { p.TargetName = "Portal to Somewhere"; p.ObjectClass = 14; });
|
||||
P(NavPointType.Point, 61.87, -100.98); P(NavPointType.Point, 61.88, -100.97);
|
||||
P(NavPointType.Chat, 61.88, -100.97, p => p.ChatCommand = "@lifestone");
|
||||
P(NavPointType.Pause, 61.88, -100.97, p => p.PauseTimeMs = 20000);
|
||||
uint dunLb = WorldPt.FromMap(61.87, -100.98).Landblock;
|
||||
string dir = Path.Combine(Path.GetTempPath(), "rnav-info-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
Check(NavRouteExport.Save(dir, "Sample", r, false, out string file, out _, out _), "the sample is written");
|
||||
NavRouteParser back = NavRouteParser.Load(file);
|
||||
RouteInfo info = RouteInfo.Describe(back, "Sample", file, lb => lb == dunLb, true, 10.0, 10.05,
|
||||
id => id == 1635 ? "Lifestone Recall" : null);
|
||||
Check(info.Type == "once" && info.Points == 11, "type and points");
|
||||
Check(info.Waypoints == 7 && info.Recalls == 1 && info.Portals == 1 && info.Chats == 1 && info.Pauses == 1, "the points by kind");
|
||||
// Walks: 10.0->10.1 (24 yd), 10.1,10.0->10.1,10.1 (24), 40,40->40,40.2 (48), 40,40.2->portal (12), the dungeon pair (~3.4).
|
||||
double dun = NavCoords.Distance(61.87, -100.98, 61.88, -100.97);
|
||||
Near(info.Yards, 24 + 24 + 48 + 12 + dun, 0.5, "yards: the walks only, not across the recall or the portal");
|
||||
Near(info.MinNs, 10.0, 1e-9, "box: south edge"); Near(info.MaxNs, 61.88, 1e-9, "box: north edge");
|
||||
Near(info.MinEw, -100.98, 1e-9, "box: west edge"); Near(info.MaxEw, 40.25, 1e-9, "box: east edge");
|
||||
Near(info.CentreNs, (10.0 + 61.88) / 2, 1e-9, "centre ns");
|
||||
Near(info.CentreEw, (-100.98 + 40.25) / 2, 1e-9, "centre ew");
|
||||
Check(info.HasStart && info.StartNs == 10.0 && info.StartEw == 10.0, "the start is the first point");
|
||||
Near(info.StartYards, NavCoords.Distance(10.0, 10.05, 10.0, 10.0), 0.01, "the player's distance to the start");
|
||||
Check(info.Landblocks.Contains(WorldPt.FromMap(10, 10).Landblock) && info.Landblocks.Contains(dunLb) && info.Landblocks.Contains(WorldPt.FromMap(40, 40.1).Landblock), "landblocks it covers");
|
||||
Check(info.Landblocks.SequenceEqual(info.Landblocks.OrderBy(x => x)) && info.Landblocks.Distinct().Count() == info.Landblocks.Count, "each once, in order");
|
||||
Check(!info.Dungeon && info.DungeonLandblocks.SequenceEqual(new[] { dunLb }), "partly in a dungeon (2 of 7 points): not a dungeon route, the landblock listed");
|
||||
Check(info.PortalNames.SequenceEqual(new[] { "Portal to Somewhere" }) && info.RecallNames.SequenceEqual(new[] { "Lifestone Recall" })
|
||||
&& info.ChatCommands.SequenceEqual(new[] { "@lifestone" }), "portals, recalls and commands used");
|
||||
Check(info.NearestIndex == 0 || info.NearestIndex == 2, "the nearest waypoint to the player");
|
||||
|
||||
using JsonDocument d = JsonDocument.Parse(RouteJson.Write(info.WriteJson));
|
||||
JsonElement e = d.RootElement;
|
||||
Check(e.GetProperty("type").GetString() == "once" && e.GetProperty("points").GetInt32() == 11 && e.GetProperty("counts").GetProperty("portals").GetInt32() == 1, "JSON: type, points, counts");
|
||||
Check(e.GetProperty("box").GetProperty("minEw").GetDouble() == -100.98 && e.GetProperty("centre").TryGetProperty("ew", out _), "JSON: box and centre");
|
||||
Check(e.GetProperty("landblocks").EnumerateArray().Any(x => x.GetString() == dunLb.ToString("X4")), "JSON: landblocks as hex");
|
||||
Check(e.GetProperty("dungeon").GetBoolean() == false && e.GetProperty("portals")[0].GetString() == "Portal to Somewhere", "JSON: dungeon, portals");
|
||||
Check(e.GetProperty("start").GetProperty("yards").ValueKind == JsonValueKind.Number, "JSON: the start's distance");
|
||||
List<string> lines = info.ChatLines();
|
||||
Check(lines.Count >= 4 && lines[0].StartsWith("routeinfo Sample: once, 11 point(s)") && lines.Any(l => l.Contains("portals: Portal to Somewhere")), "chat lines: " + lines[0]);
|
||||
|
||||
// A dungeon route: most of it in dungeon landblocks; no distance from a player on the landscape.
|
||||
var dr = new NavRouteParser { RouteType = NavRouteType.Circular };
|
||||
foreach (double k in new[] { 0.0, 0.01, 0.02, 0.03 }) dr.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 61.87 + k, EW = -100.98 });
|
||||
RouteInfo di = RouteInfo.Describe(dr, "Crypt", "", lb => lb == dunLb, true, 10, 10, null);
|
||||
Check(di.Dungeon && di.Type == "circular" && double.IsNaN(di.StartYards) && di.NearestIndex < 0, "a dungeon route: no map distance from the player");
|
||||
Near(di.Yards, 0.03 * 240 * 2, 0.01, "a circular route's yards include the way back to the start");
|
||||
RouteInfo none = RouteInfo.Describe(new NavRouteParser { RouteType = NavRouteType.Once }, "Empty", "", null, false, 0, 0, null);
|
||||
Check(none.Points == 0 && !none.HasBox && none.Landblocks.Count == 0, "an empty route");
|
||||
Check(RouteInfo.Describe(r, "x", "", null, false, 0, 0, null).RecallNames[0] == "spell 1635", "a spell the caller can't name");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
private static HashSet<uint>? _realDungeons, _realMap;
|
||||
|
||||
/// <summary>
|
||||
/// A dungeon landblock as the plugin judges one for routeinfo (RynthNavPlugin.RouteMaker.cs InfoWork):
|
||||
/// the Atlas's dungeon landblocks, and those with a dungeon navmesh and no places on the map.
|
||||
/// </summary>
|
||||
private static bool RealDungeon(string navData, uint lb)
|
||||
{
|
||||
if (_realDungeons == null || _realMap == null)
|
||||
{
|
||||
string loc = Path.Combine(navData, "locations.json");
|
||||
Atlas atlas = File.Exists(loc) ? Atlas.Load(loc) : Atlas.Empty;
|
||||
_realDungeons = atlas.DungeonLandblocks();
|
||||
_realMap = new HashSet<uint>();
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
if (l.OnMap && l.Cell.Length == 8 && uint.TryParse(l.Cell.AsSpan(0, 4), System.Globalization.NumberStyles.HexNumber, null, out uint m)) _realMap.Add(m);
|
||||
}
|
||||
return _realDungeons.Contains(lb) || (!_realMap.Contains(lb) && File.Exists(Path.Combine(navData, $"dun_{lb:X4}.tile"))); // DungeonTileFile.FileName (needs Detour: not linked here)
|
||||
}
|
||||
|
||||
/// <summary>The real NavProfiles (read only, when here): every route RynthAi has describes without a throw and adds up.</summary>
|
||||
private static void RouteInfoOnRealNavProfiles()
|
||||
{
|
||||
string dir = Environment.GetEnvironmentVariable("RYNTHAI_NAVPROFILES") ?? @"C:\Games\RynthSuite\RynthAi\NavProfiles";
|
||||
if (!Directory.Exists(dir)) { Console.WriteLine(" (no NavProfiles here: skipped)"); return; }
|
||||
string navData = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData";
|
||||
Func<uint, bool>? dungeon = File.Exists(Path.Combine(navData, "locations.json")) ? lb => RealDungeon(navData, lb) : null;
|
||||
int files = 0, dungeons = 0, points = 0;
|
||||
foreach (string f in Directory.EnumerateFiles(dir, "*.nav"))
|
||||
{
|
||||
files++;
|
||||
NavRouteParser route = NavRouteParser.Load(f);
|
||||
RouteInfo info = RouteInfo.Describe(route, Path.GetFileNameWithoutExtension(f), f, dungeon, true, 42, 33, null);
|
||||
points += info.Points;
|
||||
if (info.Dungeon) dungeons++;
|
||||
Check(info.Points == route.Points.Count && info.Waypoints + info.Portals + info.Recalls + info.Chats + info.Pauses + info.Others == info.Points,
|
||||
$"route #{files}: the kinds add up");
|
||||
Check(double.IsFinite(info.Yards) && info.Yards >= 0, $"route #{files}: a length");
|
||||
Check(info.Points == 0 || info.HasBox, $"route #{files}: a box");
|
||||
using JsonDocument d = JsonDocument.Parse(RouteJson.Write(info.WriteJson));
|
||||
Check(d.RootElement.GetProperty("points").GetInt32() == info.Points, $"route #{files}: its JSON parses");
|
||||
}
|
||||
Console.WriteLine($" {files} real nav file(s), {points} points in all, {dungeons} read as dungeon routes{(dungeon == null ? " (no Atlas here: none can be)" : "")}");
|
||||
}
|
||||
|
||||
// ── plan's figures ───────────────────────────────────────────────────
|
||||
|
||||
private static void PlanSummaryFigures()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "Lifestone Recall", 0, 20, 20),
|
||||
new(20.5, 20, true, false, "Portal to Far", -1, 50, 50),
|
||||
new(50.4, 50.3, false, false, "walk"),
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List<TripRecall> { new("Lifestone Recall", 1635, "", 13) });
|
||||
TripPath path = TripPathBuilder.Build(trip, FakeWalk, null);
|
||||
TripSummary s = TripSummary.Of(trip, path);
|
||||
Check(s.Steps.Select(x => x.Kind).SequenceEqual(new[] { "recall", "portal", "walk" }), "kinds: recall, portal, walk");
|
||||
Check(s.Steps[0].Name == "Lifestone Recall" && s.Steps[1].Name == "Portal to Far" && s.Steps[2].Name == "Far Goal", "names: the recall, the portal, the goal");
|
||||
Check(s.Steps[0].Yards == 0 && s.Steps[1].Yards > 120 && s.Steps[2].Yards > 96, "yards: none for a recall, the walked path for the rest");
|
||||
Check(s.Steps[0].LandNs == 20 && s.Steps[1].LandNs == 50 && double.IsNaN(s.Steps[2].LandNs), "where the teleports land");
|
||||
Check(s.Teleports == 2 && s.CastSeconds == 13, "two teleports, the recall's cast time");
|
||||
Near(s.Yards, s.Steps.Sum(x => x.Yards), 1e-9, "the yards add up");
|
||||
Near(s.Minutes, (s.Yards / PortalRoute.RunUnitsPerSecond + 2 * PortalRoute.TeleportOverheadUnits / PortalRoute.RunUnitsPerSecond + 13) / 60, 1e-9, "minutes: running, teleports, casting");
|
||||
TripSummary straight = TripSummary.Of(trip, null);
|
||||
Near(straight.Steps[1].Yards, NavCoords.Distance(20, 20, 20.5, 20), 0.01, "without a path: the straight line");
|
||||
using JsonDocument d = JsonDocument.Parse(RouteJson.Write(w => { w.WriteStartObject(); s.WriteFields(w); w.WriteEndObject(); }));
|
||||
Check(d.RootElement.GetProperty("steps").GetArrayLength() == 3 && d.RootElement.GetProperty("teleports").GetInt32() == 2
|
||||
&& d.RootElement.GetProperty("steps")[1].GetProperty("land").GetProperty("ns").GetDouble() == 50, "plan JSON fields");
|
||||
Check(d.RootElement.GetProperty("steps")[2].TryGetProperty("land", out _) == false, "a walk has no landing");
|
||||
}
|
||||
|
||||
// ── worldmap.vec ─────────────────────────────────────────────────────
|
||||
|
||||
private static void BuildingOutlinesFile()
|
||||
{
|
||||
string dir = Path.Combine(Path.GetTempPath(), "rnav-vec-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
// Two buildings (in map cells, 24 yd): a square at cells (10..11, 10..11) and a triangle; then a road.
|
||||
string file = Path.Combine(dir, BuildingOutlines.FileName);
|
||||
using (var w = new BinaryWriter(File.Create(file)))
|
||||
{
|
||||
w.Write(new[] { (byte)'R', (byte)'V', (byte)'E', (byte)'C' }); w.Write(1u); w.Write(2u); w.Write(1u);
|
||||
w.Write((byte)4); foreach (var (x, y) in new[] { (10f, 10f), (11f, 10f), (11f, 11f), (10f, 11f) }) { w.Write(x); w.Write(y); }
|
||||
w.Write((byte)3); foreach (var (x, y) in new[] { (20f, 20f), (21f, 20f), (20f, 21f) }) { w.Write(x); w.Write(y); }
|
||||
w.Write((ushort)0); w.Write((ushort)0); w.Write((ushort)1); w.Write((ushort)0);
|
||||
}
|
||||
BuildingOutlines? b = BuildingOutlines.Load(file);
|
||||
Check(b != null && b.Count == 2, "two buildings read");
|
||||
Check(b!.Inside(10.5 * 24, 10.5 * 24) == 0, "inside the square");
|
||||
Check(b.Inside(11.2 * 24, 10.5 * 24) == -1, "4.8 yd outside: not inside");
|
||||
Check(b.Inside(11.2 * 24, 10.5 * 24, margin: 5) == 0, "...but within a 5 yd margin");
|
||||
Check(b.Inside(20.2 * 24, 20.2 * 24) == 1 && b.Inside(20.9 * 24, 20.9 * 24) == -1, "the triangle, not its bounding box");
|
||||
Check(b.Inside(-5, -5) == -1, "off the map: none");
|
||||
File.WriteAllBytes(Path.Combine(dir, "bad.vec"), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 });
|
||||
Check(BuildingOutlines.Load(Path.Combine(dir, "bad.vec")) == null && BuildingOutlines.Load(Path.Combine(dir, "none.vec")) == null, "a bad or missing file: null");
|
||||
var fromPolys = BuildingOutlines.FromPolygons(new[] { new (double, double)[] { (0, 0), (10, 0), (10, 10), (0, 10) } });
|
||||
Check(fromPolys.Inside(5, 5) == 0 && fromPolys.Inside(15, 5) == -1, "outlines given in world units");
|
||||
|
||||
string real = Path.Combine(Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData", BuildingOutlines.FileName);
|
||||
if (File.Exists(real))
|
||||
{
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
BuildingOutlines? all = BuildingOutlines.Load(real);
|
||||
Console.WriteLine($" the real {BuildingOutlines.FileName}: {all?.Count} buildings in {sw.ElapsedMilliseconds} ms");
|
||||
Check(all != null && all.Count > 1000, "the real file reads (thousands of buildings)");
|
||||
}
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
}
|
||||
|
|
@ -39,6 +39,14 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PathMarkers.cs" Link="Linked\PathMarkers.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavRouteExport.cs" Link="Linked\NavRouteExport.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\Nav3DText.cs" Link="Linked\Nav3DText.cs" />
|
||||
<!-- The route maker's parts that need no navmesh (RouteMakerTests): requests, jobs, loop order and
|
||||
the nav file, routeinfo, a plan's figures, the building outlines. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RouteRequest.cs" Link="Linked\RouteRequest.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RouteJobs.cs" Link="Linked\RouteJobs.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RouteShape.cs" Link="Linked\RouteShape.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RouteInfo.cs" Link="Linked\RouteInfo.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripSummary.cs" Link="Linked\TripSummary.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\BuildingOutlines.cs" Link="Linked\BuildingOutlines.cs" />
|
||||
<!-- RynthAi's own nav reader/writer: the saved route is read back the way RynthAi reads it. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\LegacyUi\NavRouteParser.cs" Link="Linked\NavRouteParser.cs" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
Loading…
Reference in a new issue