RynthSuite as of 2026-11-29 (internal 46bae49): release 2026.11.28.1
This commit is contained in:
parent
25552fa794
commit
598f49c899
131 changed files with 11825 additions and 329 deletions
|
|
@ -24,6 +24,42 @@ internal static partial class Program
|
|||
TestAttrPetEssence();
|
||||
TestAttrNativeAndWire();
|
||||
TestAttrVocab();
|
||||
TestAttrWeaponSpecials();
|
||||
}
|
||||
|
||||
// 2026-11-27 (spotted by SilentKelpie, Forgejo rynth PR #12): ACE's tinks, rare, attuned, bonded and max
|
||||
// level; elemental damage bonus and absorb magic; the weapon specials; life resist and overpower ratings.
|
||||
private static void TestAttrWeaponSpecials()
|
||||
{
|
||||
LootItemFacts f = Sword();
|
||||
f.Ints[171] = 3; f.Ints[17] = 30012; f.Ints[114] = 1; f.Ints[33] = 1; f.Ints[319] = 5; f.Ints[204] = 12;
|
||||
f.Ints[292] = 2; f.Ints[378] = 1; f.Ints[388] = 2; f.Ints[389] = 3;
|
||||
f.Doubles[147] = 0.4; f.Doubles[136] = 3; f.Doubles[155] = 0.1; f.Doubles[157] = 0.5; f.Doubles[159] = 0.25;
|
||||
LootItemRuleDraft d = BuildOk(f);
|
||||
List<LootItemAttribute> rows = d.Attributes;
|
||||
Eq(string.Join(",", rows.Select(r => r.Group).Distinct()), "Item,Weapon / Armor,Weapon specials,Ratings,Spells,Requirements",
|
||||
"specials: their group sits after Weapon / Armor");
|
||||
Eq(string.Join(",", rows.Where(r => r.Group == LootItemAttributes.GroupSpecials).Select(r => r.Label)),
|
||||
"Biting Strike,Crushing Blow,Armor Cleaving,Resistance Cleaving,Cleaving", "specials: the rows, in order");
|
||||
foreach (string id in new[] { "L:171", "L:17", "L:114", "L:33", "L:319", "L:204", "D:159", "L:378", "L:388", "L:389" })
|
||||
Check(rows.Any(r => r.Id == id), "specials: row " + id);
|
||||
Eq(rows.Single(r => r.Id == "L:171").Ops[0], LootItemAttributeOp.AtMost, "specials: times tinkered defaults to at most");
|
||||
Check(!rows.Any(r => r.On), "specials: none ticked by default");
|
||||
|
||||
LootItemRuleDraft like = BuildOk(f, new() { Match = LootItemMatch.Like });
|
||||
Check(!like.Attributes.Any(r => r.On && (r.Group == LootItemAttributes.GroupSpecials || r.Id is "L:171" or "L:17" or "L:378")),
|
||||
"specials: 'items like this' still ticks only what it always did");
|
||||
|
||||
var c = Pick(("D:147", true, LootItemAttributeOp.AtLeast, "0.3"), ("L:17", true, LootItemAttributeOp.AtLeast, "1"),
|
||||
("L:171", true, LootItemAttributeOp.AtMost, ""));
|
||||
LootItemRuleDraft picked = BuildOk(f, new() { Choices = c });
|
||||
string conds = string.Join(" ; ", picked.Rule.Conditions.Skip(2).Select(Lines));
|
||||
Eq(conds, "2:3|171 ; 3:1|17 ; 5:0.3|147", "specials: tinks at most 3, any rare, Biting Strike at least 0.3 (row order)");
|
||||
Check(LootRuleText.Summary(picked.Rule).Contains("CriticalFrequency (Biting Strike) >= 0.3"), "specials: the summary names the key: " + LootRuleText.Summary(picked.Rule));
|
||||
Check(LootItemRules.IntKeys.Contains(292) && LootItemRules.DoubleKeys.Contains(147), "specials: RynthAi reads the new keys into the facts");
|
||||
|
||||
// An item without them: no such rows.
|
||||
Check(!BuildOk(Sword()).Attributes.Any(r => r.Group == LootItemAttributes.GroupSpecials), "specials: none on an ordinary sword");
|
||||
}
|
||||
|
||||
private static LootItemFacts Sword() => new()
|
||||
|
|
@ -181,7 +217,17 @@ internal static partial class Program
|
|||
|
||||
private static void TestAttrVocab()
|
||||
{
|
||||
Eq(LootRuleText.ValueName(353, "4"), "Armor Rending", "vocab: imbue names");
|
||||
Eq(LootRuleText.ValueName(179, "4"), "Armor Rending", "vocab: imbue names (ImbuedEffect is 179)");
|
||||
Eq(LootRuleText.ValueName(353, "9"), "Crossbow", "vocab: 353 is the weapon type");
|
||||
Eq(LootRuleText.ValueName(353, "4"), "Mace", "vocab: 353 = 4 is a mace, not Armor Rending");
|
||||
Check(LootRuleText.ValueTableIsFlags(179) && !LootRuleText.ValueTableIsFlags(353), "vocab: imbues are flags, weapon type isn't");
|
||||
// The checklist: Imbue reads 179, Weapon type 353 (an Armor Rending sword was "Imbue: value 2" before).
|
||||
var imbued = Sword();
|
||||
imbued.Ints[179] = 4;
|
||||
imbued.Ints[353] = 2;
|
||||
List<LootItemAttribute> rows = BuildOk(imbued).Attributes;
|
||||
Check(rows.Any(r => r.Id == "L:179" && r.Label == "Imbue" && r.ItemText == "Armor Rending"), "attr: the Imbue row is 179, by name");
|
||||
Check(rows.Any(r => r.Id == "L:353" && r.Label == "Weapon type" && r.ItemText == "Sword"), "attr: 353 is the weapon type row");
|
||||
Eq(LootRuleText.ValueName(362, "3"), "Naturalist", "vocab: summoning mastery");
|
||||
Check(LootRuleText.LongKeys.Any(k => k.Id == 9053) && LootRuleText.LongKeys.Any(k => k.Id == 9075), "vocab: pet keys named");
|
||||
Check(LootRuleText.LongKeys.Any(k => k.Id == 92 && k.Name.StartsWith("UsesRemaining")), "vocab: 92 is uses remaining");
|
||||
|
|
|
|||
63
Tools/RynthCore.LootSdkTests/LootSlayerTextTests.cs
Normal file
63
Tools/RynthCore.LootSdkTests/LootSlayerTextTests.cs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Loot.VTank;
|
||||
|
||||
namespace RynthCore.LootSdkTests;
|
||||
|
||||
// The slayer bonus from the item text (2026-11-27; spotted by SilentKelpie, Forgejo rynth PR #12): ACE never
|
||||
// sends float 138, servers built on ACECustom write "- Shadow Slayer: 1.5x Damage". The loot readers fall back
|
||||
// to the text when no value was sent; a sent value wins; the Loot Editor says where the test can't work.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunSlayerTextTests()
|
||||
{
|
||||
Console.WriteLine("\n-- Slayer damage bonus from the item text --");
|
||||
|
||||
Eq(SlayerText.BonusOf("Property Details:\n- Shadow Slayer: 1.5x Damage\n- Biting Strike"), 1.5, "slayer: the line's multiplier");
|
||||
Eq(SlayerText.BonusOf("Olthoi Slayer: 2x"), 2.0, "slayer: no dash, a whole multiplier");
|
||||
Eq(SlayerText.BonusOf("- Drudge Slayer: 1.25x Damage", "- All Creatures Slayer: 2.1x Damage"), 2.1, "slayer: the best of several texts");
|
||||
Eq(SlayerText.BonusOf("A fine blade.", null, ""), 0.0, "slayer: no line, 0");
|
||||
Eq(SlayerText.BonusOf("Slayer of drudges, 2x the fun"), 0.0, "slayer: prose mentioning a slayer is not a bonus line");
|
||||
|
||||
var f = new LootItemFacts { Name = "Shadow Slayer Sword", ObjectClass = (int)AcObjectClass.MeleeWeapon, ItemText = "- Shadow Slayer: 1.5x Damage" };
|
||||
Eq(f.Double(SlayerText.SlayerDamageBonusKey), 1.5, "slayer facts: nothing sent, the text's bonus");
|
||||
f.Doubles[SlayerText.SlayerDamageBonusKey] = 3.0;
|
||||
Eq(f.Double(SlayerText.SlayerDamageBonusKey), 3.0, "slayer facts: a sent value wins");
|
||||
f.Doubles.Remove(SlayerText.SlayerDamageBonusKey);
|
||||
f.Doubles[62] = 1.2;
|
||||
Eq(f.Double(62), 1.2, "slayer facts: other keys unchanged");
|
||||
Eq(f.Double(63), 0.0, "slayer facts: an unsent other key is still 0, whatever the text");
|
||||
Eq(new LootItemFacts().Double(SlayerText.SlayerDamageBonusKey), 0.0, "slayer facts: no text, no bonus");
|
||||
|
||||
// The Loot Editor's hint.
|
||||
var slayerRule = new VTankLootRule { Name = "Any slayer bonus", Action = VTankLootAction.Keep, CustomExpression = string.Empty };
|
||||
slayerRule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.ObjectClass, "0", new[] { "1" }));
|
||||
slayerRule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.DoubleValKeyGE, "0", new[] { "1.01", "138" }));
|
||||
var plain = new VTankLootRule { Name = "Any slayer type", Action = VTankLootAction.Keep, CustomExpression = string.Empty };
|
||||
plain.Conditions.Add(new VTankLootCondition(VTankNodeTypes.LongValKeyGE, "0", new[] { "1", "166" }));
|
||||
Check(LootRuleText.Hints(slayerRule).Count == 1 && LootRuleText.Hints(slayerRule)[0].Contains("use Slayer type"), "slayer hint: a rule testing the bonus gets it");
|
||||
Check(LootRuleText.Hints(plain).Count == 0, "slayer hint: a Slayer type rule doesn't");
|
||||
List<string> ph = LootRuleText.ProfileHints(new[] { plain, slayerRule });
|
||||
Check(ph.Count == 1 && ph[0].StartsWith("1 rule(s) test Slayer damage bonus (Any slayer bonus)"), "slayer hint: the profile line names the rule: " + string.Join("|", ph));
|
||||
|
||||
var profile = new VTankLootProfile { FileVersion = 1, Rules = { plain, slayerRule } };
|
||||
string dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthLootSlayerTests_" + Guid.NewGuid().ToString("N"));
|
||||
System.IO.Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
string path = System.IO.Path.Combine(dir, "slayer-hint.utl");
|
||||
System.IO.File.WriteAllText(path, VTankLootWriter.Serialize(profile));
|
||||
var s = new LootEditSession();
|
||||
Check(s.Open(path), "slayer hint: the profile opens: " + s.Message);
|
||||
Check(s.Message.Contains("Slayer damage bonus can only be read on servers that write it in the item text"), "slayer hint: opening it says so: " + s.Message);
|
||||
var p2 = new VTankLootProfile { FileVersion = 1, Rules = { plain } };
|
||||
string path2 = System.IO.Path.Combine(dir, "slayer-none.utl");
|
||||
System.IO.File.WriteAllText(path2, VTankLootWriter.Serialize(p2));
|
||||
Check(s.Open(path2) && !s.Message.Contains("Slayer damage bonus"), "slayer hint: not for a profile without the test: " + s.Message);
|
||||
}
|
||||
finally { try { System.IO.Directory.Delete(dir, recursive: true); } catch { } }
|
||||
}
|
||||
}
|
||||
|
|
@ -49,6 +49,7 @@ internal static partial class Program
|
|||
RunLootAddAttributeTests();
|
||||
RunUnknownNodeTests();
|
||||
RunPerDayTests();
|
||||
RunSlayerTextTests();
|
||||
|
||||
Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed.");
|
||||
|
||||
|
|
|
|||
|
|
@ -105,6 +105,8 @@ internal static unsafe class FakeHost
|
|||
/// <summary>Every SetAutoRun call, in order; AutoRun is the last value sent.</summary>
|
||||
public static readonly List<bool> AutoRunCalls = new();
|
||||
public static bool AutoRun;
|
||||
/// <summary>An engine without SetAutoRun and TurnToHeading (the back-away's jump fallback).</summary>
|
||||
public static bool NoTurnOrAutoRun;
|
||||
public static int Jumps;
|
||||
/// <summary>Runs inside CastSpell, after the cast is recorded (a UseDone that lands during the send).</summary>
|
||||
public static Action? AfterCastSpell;
|
||||
|
|
@ -326,7 +328,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(); NativeAttackCalls = false; CancelAttackCalls = false; CancelAttacks = 0; Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
|
||||
AutoRunCalls.Clear(); AutoRun = false; NoTurnOrAutoRun = 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;
|
||||
|
|
@ -396,8 +398,11 @@ internal static unsafe class FakeHost
|
|||
api.GetObjectStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int>)&GetObjectState;
|
||||
if (InstanceIds.Count > 0)
|
||||
api.GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&GetObjectInstanceIdProperty;
|
||||
api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&SetAutoRun;
|
||||
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&TurnToHeading;
|
||||
if (!NoTurnOrAutoRun)
|
||||
{
|
||||
api.SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&SetAutoRun;
|
||||
api.TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&TurnToHeading;
|
||||
}
|
||||
api.GetPlayerHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float*, int>)&GetPlayerHeading;
|
||||
api.JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&JumpNonAutonomous;
|
||||
if (TapJumpCalls)
|
||||
|
|
|
|||
|
|
@ -212,6 +212,7 @@ internal static class Program
|
|||
InventoryAttributeFilterTests.Register(runner);
|
||||
StuckCastTests.Register(runner);
|
||||
KillNoticeTests.Register(runner);
|
||||
PredictedKillReclaimTests.Register(runner);
|
||||
PacerEdgeTests.Register(runner);
|
||||
RecoveryRetryTests.Register(runner);
|
||||
HpFailsafeTests.Register(runner);
|
||||
|
|
@ -237,6 +238,7 @@ internal static class Program
|
|||
CallStateRepairTests.Register(runner);
|
||||
ProfileButtonTests.Register(runner);
|
||||
MonsterProfileTests.Register(runner);
|
||||
ProfileStartTests.Register(runner);
|
||||
GiveProfileTests.Register(runner);
|
||||
TinkerTests.Register(runner);
|
||||
KitRunnerTests.Register(runner);
|
||||
|
|
|
|||
|
|
@ -10,9 +10,11 @@ namespace RynthCore.RynthAiHostTests.Tests;
|
|||
// The back-away combat does on a server plugin's request (CombatManager.BackAwayFrom, RynthAi.Hub
|
||||
// BackAwayFrom). It was the Empyrean Handler lethal-ring evade (Silentkelpie's PR 12) until 2026-10-20,
|
||||
// when the Handler's detection and its setting went to RynthILT (Infinite Leaftide content); RynthAi
|
||||
// keeps the generic part: face the object, back-jump, hold attacks until it settles. Gated: only while
|
||||
// the macro is running with combat on, and only inside the radius (at least Ring Range). RynthAi alone
|
||||
// never reacts to the Handler's line any more.
|
||||
// keeps the generic part: stop attacking, run away (face directly away, autorun until outside the radius
|
||||
// plus a margin, re-aiming as it goes), hold attacks until clear, then re-engage. A single back-jump until
|
||||
// 2026-11-27 (it covers a yard or two); it stays only for an engine without heading snap / autorun
|
||||
// (spotted by SilentKelpie, Forgejo rynth PR #12). Gated: only while the macro is running with combat on,
|
||||
// and only inside the radius (at least Ring Range). RynthAi alone never reacts to the Handler's line.
|
||||
internal static class BackAwayTests
|
||||
{
|
||||
private const uint Player = 0x50000D11;
|
||||
|
|
@ -22,7 +24,10 @@ internal static class BackAwayTests
|
|||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("back away: inside the radius with the macro running and combat on, one back-jump (and none while it runs)", Jumps);
|
||||
r.Add("back away: inside the radius with the macro running and combat on, runs away (faces away, autorun on, no back-jump); not now while it runs", Runs);
|
||||
r.Add("back away: the run re-aims away, holds attacks, stops outside the radius plus the margin (autorun off) and re-engages", RunEnds);
|
||||
r.Add("back away: the run ends with autorun off when the macro stops, combat goes off, the danger is gone or it times out", RunStops);
|
||||
r.Add("back away: an engine without heading snap or autorun gets the old back-jump", JumpFallback);
|
||||
r.Add("back away: not with the macro stopped or combat off", Gated);
|
||||
r.Add("back away: outside the radius (Ring Range widens it), or an object without a position: no jump", NotThese);
|
||||
r.Add("back away: RynthAi alone ignores the Empyrean Handler's ring line (RynthILT's now)", HandlerLineIgnored);
|
||||
|
|
@ -36,7 +41,7 @@ internal static class BackAwayTests
|
|||
public float Heading = -1;
|
||||
public bool Busy;
|
||||
|
||||
public Rig(float dangerYards, bool place = true)
|
||||
public Rig(float dangerYards, bool place = true, Action? beforeCreate = null)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Names[Player] = "Evader";
|
||||
|
|
@ -45,6 +50,7 @@ internal static class BackAwayTests
|
|||
FakeHost.Names[Danger] = "Empyrean Handler";
|
||||
if (place) FakeHost.Positions[Danger] = (Lb | 0x1C, 96f, 96f + dangerYards, 0f);
|
||||
FakeHost.ItemTypes[Danger] = 0x10;
|
||||
beforeCreate?.Invoke();
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Danger });
|
||||
S.IsMacroRunning = true;
|
||||
|
|
@ -58,20 +64,120 @@ internal static class BackAwayTests
|
|||
public int Ask(double radius = 12, int holdMs = 750) => Combat.BackAwayFrom(unchecked((int)Danger), radius, holdMs, "test");
|
||||
}
|
||||
|
||||
private static void Jumps()
|
||||
private static readonly System.Reflection.BindingFlags Any = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
||||
private static DateTime _now = new(2026, 11, 27, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
/// <summary>Runs <paramref name="body"/> on a test clock (RynthClock.TestNow), restored after.</summary>
|
||||
private static void OnClock(Action body)
|
||||
{
|
||||
RynthClock.TestNow = () => _now;
|
||||
try { body(); }
|
||||
finally { RynthClock.TestNow = null; }
|
||||
}
|
||||
|
||||
private static bool Think(Rig rig) => (bool)typeof(CombatManager).GetMethod("TickBackAway", Any)!.Invoke(rig.Combat, null)!;
|
||||
|
||||
/// <summary>Puts the character <paramref name="south"/> yards south of where it started.</summary>
|
||||
private static void MoveSouth(float south)
|
||||
{
|
||||
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f - south, 0f);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f - south, 0f);
|
||||
}
|
||||
|
||||
private static void Runs() => OnClock(() =>
|
||||
{
|
||||
var rig = new Rig(dangerYards: 5);
|
||||
Check.Eq(rig.Ask(), RynthAiHub.BackAwayStarted, "5 yards inside 12: started");
|
||||
Check.Eq(rig.Jumps, 1, "one back-jump");
|
||||
Check.Eq(rig.Jumps, 0, "no back-jump (a jump covers a yard or two)");
|
||||
Check.True(FakeHost.AutoRun, "autorun on");
|
||||
Check.True(Math.Abs(FakeHost.HeadingDeg - 180.0) < 1.0, $"faces directly away (the danger is north; heading {FakeHost.HeadingDeg:0})");
|
||||
Check.True(rig.Combat.BackAwayActive, "combat holds while it runs");
|
||||
Check.Eq(rig.Ask(), RynthAiHub.BackAwayNotNow, "a second request while running: not now");
|
||||
Check.True(FakeHost.Logs.Exists(l => l.Contains("[CombatEvade]") && l.Contains("running away")), "logged as a run");
|
||||
});
|
||||
|
||||
private static void RunEnds() => OnClock(() =>
|
||||
{
|
||||
var rig = new Rig(dangerYards: 5);
|
||||
rig.Ask(radius: 12);
|
||||
_now = _now.AddMilliseconds(100);
|
||||
Check.True(Think(rig), "Think holds attacks while it runs");
|
||||
Check.Eq(rig.Combat.LastCombatSkipReason, "back-away-run", "and says why");
|
||||
|
||||
// Halfway, a little to the east: it re-aims away from the danger.
|
||||
FakeHost.Positions[Player] = (Lb | 0x1C, 100f, 90f, 0f);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 100f, 90f, 0f);
|
||||
FakeHost.HeadingDeg = 0;
|
||||
_now = _now.AddMilliseconds(300);
|
||||
Check.True(Think(rig), "still inside 12 + 4: holding");
|
||||
Check.True(FakeHost.HeadingDeg > 150 && FakeHost.HeadingDeg < 180, $"re-aimed away from the danger (heading {FakeHost.HeadingDeg:0})");
|
||||
Check.True(FakeHost.AutoRun, "still running");
|
||||
|
||||
MoveSouth(12f); // 17 yards from it: outside 12 + 4
|
||||
_now = _now.AddMilliseconds(300);
|
||||
Check.False(Think(rig), "clear: Think re-engages");
|
||||
Check.False(FakeHost.AutoRun, "autorun off");
|
||||
Check.False(rig.Combat.BackAwayActive, "no longer held");
|
||||
Check.True(FakeHost.Logs.Exists(l => l.Contains("Back away done") && l.Contains("clear at")), "logged as clear");
|
||||
Check.Eq(rig.Ask(), RynthAiHub.BackAwayOutside, "a new request out here: outside");
|
||||
});
|
||||
|
||||
private static void RunStops() => OnClock(() =>
|
||||
{
|
||||
var macro = new Rig(5);
|
||||
macro.Ask();
|
||||
macro.S.IsMacroRunning = false;
|
||||
macro.Combat.PollBackAway();
|
||||
Check.False(FakeHost.AutoRun, "macro stopped: autorun off");
|
||||
Check.False(macro.Combat.BackAwayActive, "macro stopped: over");
|
||||
|
||||
var combat = new Rig(5);
|
||||
combat.Ask();
|
||||
combat.S.EnableCombat = false;
|
||||
combat.Combat.PollBackAway();
|
||||
Check.False(FakeHost.AutoRun, "combat off: autorun off");
|
||||
Check.False(combat.Combat.BackAwayActive, "combat off: over");
|
||||
|
||||
var gone = new Rig(5);
|
||||
gone.Ask();
|
||||
FakeHost.Positions.Remove(Danger);
|
||||
_now = _now.AddMilliseconds(100);
|
||||
Check.False(Think(gone), "the danger is gone: re-engage");
|
||||
Check.False(FakeHost.AutoRun, "gone: autorun off");
|
||||
|
||||
var stuck = new Rig(5);
|
||||
stuck.Ask();
|
||||
_now = _now.AddMilliseconds(CombatManager.BackAwayRunMaxMs + 100);
|
||||
Check.False(Think(stuck), "blocked (no progress): it times out");
|
||||
Check.False(FakeHost.AutoRun, "timed out: autorun off");
|
||||
Check.True(FakeHost.Logs.Exists(l => l.Contains("run timed out")), "logged");
|
||||
|
||||
// Think not driving it (another activity has the tick): the poll steps it, so it still ends when clear.
|
||||
var orphan = new Rig(5);
|
||||
orphan.Ask();
|
||||
MoveSouth(12f);
|
||||
_now = _now.AddMilliseconds(500);
|
||||
orphan.Combat.PollBackAway();
|
||||
Check.False(orphan.Combat.BackAwayActive, "the poll ended it once clear");
|
||||
Check.False(FakeHost.AutoRun, "autorun off");
|
||||
});
|
||||
|
||||
private static void JumpFallback() => OnClock(() =>
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var rig = new Rig(5, beforeCreate: () => FakeHost.NoTurnOrAutoRun = true);
|
||||
Check.Eq(rig.Ask(), RynthAiHub.BackAwayStarted, "started");
|
||||
Check.Eq(rig.Jumps, 1, "one back-jump");
|
||||
Check.False(FakeHost.AutoRun, "no autorun");
|
||||
Check.True(rig.Combat.BackAwayActive, "combat holds while it jumps");
|
||||
Check.Eq(rig.Ask(), RynthAiHub.BackAwayNotNow, "a second request while backing away: not now");
|
||||
Check.Eq(rig.Jumps, 1, "still one jump");
|
||||
|
||||
var refused = new Rig(5);
|
||||
var refused = new Rig(5, beforeCreate: () => FakeHost.NoTurnOrAutoRun = true);
|
||||
refused.Combat.RequestBackJump = (_, _) => false;
|
||||
Check.Eq(refused.Ask(), RynthAiHub.BackAwayJumpRefused, "the jumper refused: said so");
|
||||
Check.False(refused.Combat.BackAwayActive, "and combat isn't held");
|
||||
}
|
||||
});
|
||||
|
||||
private static void Gated()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -101,6 +101,13 @@ internal static class BuffTests
|
|||
r.Add("buff upgrade: a confirmed upgrade resets the no-show count", UpgradeConfirmedResetsNoShows);
|
||||
r.Add("buff upgrade: Cancel Buffing ends the pending upgrade", UpgradeCancelEndsPending);
|
||||
r.Add("buff upgrade: an upgrade that would leave mana under the reserve waits for Stamina to Mana, then goes", UpgradeWaitsForManaReserve);
|
||||
|
||||
// Spotted by SilentKelpie (rynth PR #12); re-implemented here.
|
||||
r.Add("no components: a buff refused for components drops a level, not the buff; none left leaves it out", NoComponentsBuffDropsALevel);
|
||||
r.Add("no components: more scarabs or tapers lift the list; the first reading only sets the base", NoComponentsLiftedByRestock);
|
||||
r.Add("no components: a refusal after a later cast (combat's) leaves the pending buff alone", NoComponentsRefusalForTheLastCast);
|
||||
r.Add("no components: the warning shows once per spell per 2 min, closes on OK or after 30 s, and not with the setting off", NoComponentsWarningHud);
|
||||
r.Add("no components: Show No Components Warning defaults on, copies with the profile, is in the settings map", NoComponentsWarningSetting);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
|
@ -2162,4 +2169,158 @@ internal static class BuffTests
|
|||
entry.Set("0");
|
||||
Check.False(live.SkipUnusableBuffs, "and sets off");
|
||||
}
|
||||
|
||||
// ── Missing components (Spotted by SilentKelpie, rynth PR #12; re-implemented here) ──
|
||||
|
||||
private const string NoComps = "You don't have all the components for this spell.";
|
||||
|
||||
/// <summary>Tier 6 Creature Enchantment in Magic stance, knowing Strength Self IV to VI and nothing else.</summary>
|
||||
private static BuffRig StrengthRig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
Know("Strength Self IV", "Strength Self V", "Strength Self VI");
|
||||
FakeHost.Skills[(Player, STypeCreature)] = (300, 2);
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
var rig = new BuffRig();
|
||||
rig.S.SpellCastIntervalMs = 0;
|
||||
rig.Live(("Fire Protection Self I", 3000)); // a registry read, with none of ours on
|
||||
return rig;
|
||||
}
|
||||
|
||||
/// <summary>One pass of the buff loop (a few tries); the spell it cast, or null.</summary>
|
||||
private static string? CastOnce(BuffRig rig)
|
||||
{
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
int before = FakeHost.Casts.Count;
|
||||
CastSelfBuffs.Invoke(rig.B, null);
|
||||
if (FakeHost.Casts.Count > before) return NameOf(FakeHost.Casts[^1].SpellId);
|
||||
System.Threading.Thread.Sleep(20);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void NoComponentsBuffDropsALevel()
|
||||
{
|
||||
var rig = StrengthRig();
|
||||
Check.Eq(CastOnce(rig), "Strength Self VI", "the top level the skill allows");
|
||||
rig.B.OnChatWindowText(NoComps, 0);
|
||||
Check.True(rig.Sm.LacksComponents(Id("Strength Self VI")), "that level is passed over");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("No components for Strength Self VI: buffing with a lower level")), "chat says so");
|
||||
Check.False(FakeHost.Chat.Any(c => c.Contains("Skipping Strength Self VI")), "the buff is not parked");
|
||||
Check.Eq(NameOf(rig.B.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment)), "Strength Self V", "the picker drops a level");
|
||||
Check.Eq(CastOnce(rig), "Strength Self V", "and the next pass casts it");
|
||||
|
||||
rig.B.OnChatWindowText(NoComps, 0);
|
||||
Check.Eq(NameOf(rig.B.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment)), "Strength Self IV", "refused again: one more level down");
|
||||
rig.Sm.MarkNoComponents(Id("Strength Self IV"));
|
||||
Check.Eq(rig.B.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment), 0, "no castable level left: the buff is left out");
|
||||
|
||||
// The other refusals still park the buff as before.
|
||||
var other = StrengthRig();
|
||||
Check.Eq(CastOnce(other), "Strength Self VI", "control: cast");
|
||||
other.B.OnChatWindowText("You must specify a target for this spell.", 0);
|
||||
Check.False(other.Sm.LacksComponents(Id("Strength Self VI")), "not a components refusal: no level is passed over");
|
||||
Check.True(FakeHost.Chat.Any(c => c.Contains("Skipping Strength Self VI") && c.Contains("the server refused it")), "it is parked, as before");
|
||||
}
|
||||
|
||||
private static void NoComponentsLiftedByRestock()
|
||||
{
|
||||
var rig = StrengthRig();
|
||||
int vi = Id("Strength Self VI");
|
||||
rig.Sm.NoteComponentCounts(20, 10); // the base
|
||||
rig.Sm.MarkNoComponents(vi);
|
||||
rig.Sm.NoteComponentCounts(20, 10);
|
||||
Check.True(rig.Sm.LacksComponents(vi), "the same counts: still passed over");
|
||||
rig.Sm.NoteComponentCounts(19, 9);
|
||||
Check.True(rig.Sm.LacksComponents(vi), "fewer (spent): still passed over");
|
||||
rig.Sm.NoteComponentCounts(19, 10);
|
||||
Check.False(rig.Sm.LacksComponents(vi), "a taper more: lifted");
|
||||
rig.Sm.MarkNoComponents(vi);
|
||||
rig.Sm.NoteComponentCounts(25, 10);
|
||||
Check.False(rig.Sm.LacksComponents(vi), "scarabs more: lifted");
|
||||
Check.Eq(NameOf(rig.B.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment)), "Strength Self VI", "the top level again");
|
||||
|
||||
var fresh = StrengthRig();
|
||||
fresh.Sm.MarkNoComponents(vi);
|
||||
fresh.Sm.NoteComponentCounts(50, 50);
|
||||
Check.True(fresh.Sm.LacksComponents(vi), "the first reading is only the base");
|
||||
Check.Eq(SpellManager.NoComponentsSec, 600.0, "ten minutes");
|
||||
}
|
||||
|
||||
private static void NoComponentsRefusalForTheLastCast()
|
||||
{
|
||||
var rig = StrengthRig();
|
||||
Check.Eq(CastOnce(rig), "Strength Self VI", "the buff goes out");
|
||||
int vi = Id("Strength Self VI");
|
||||
Check.Eq(rig.B.PendingSpellId, vi, "and is pending");
|
||||
// Combat sends an attack after it; the refusal that follows answers the attack.
|
||||
Check.True(RynthCore.Plugin.Shared.ActionPacer.CastSpellFor(rig.Host, 0x50000F00, Id("Flame Bolt VI"), "Combat", "Flame Bolt VI"), "an attack goes out after it");
|
||||
rig.B.OnChatWindowText(NoComps, 0);
|
||||
Check.Eq(rig.B.PendingSpellId, vi, "the buff is still pending");
|
||||
Check.False(rig.Sm.LacksComponents(vi), "the buff's level is not passed over");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("refusal is for the last cast sent (Flame Bolt VI)")), "logged whose it is");
|
||||
}
|
||||
|
||||
private static void NoComponentsWarningHud()
|
||||
{
|
||||
long now = 1_000_000;
|
||||
bool on = true;
|
||||
var hud = new RynthCore.Plugin.RynthAi.Huds.CastWarningHud(() => on, () => now);
|
||||
Check.True(hud.Current() == null, "nothing up at first");
|
||||
hud.Post("Strength Self VI", "RynthAi buffs with a lower level of it instead.");
|
||||
Check.Eq(hud.Current()?.Spell, "Strength Self VI", "up, naming the spell");
|
||||
now += 10_000;
|
||||
hud.Post("Strength Self VI", "again");
|
||||
Check.Eq(hud.Current()?.Body, "RynthAi buffs with a lower level of it instead.", "the same spell within 2 min changes nothing");
|
||||
hud.Dismiss();
|
||||
Check.True(hud.Current() == null, "OK closes it");
|
||||
hud.Post("Strength Self VI", "again");
|
||||
Check.True(hud.Current() == null, "and the same spell doesn't bring it back within 2 min");
|
||||
hud.Post("Flame Bolt VI", "RynthAi attacks with a lower level of it instead.");
|
||||
Check.Eq(hud.Current()?.Spell, "Flame Bolt VI", "another spell shows");
|
||||
now += RynthCore.Plugin.RynthAi.Huds.CastWarningHud.ShownForMs + 1;
|
||||
Check.True(hud.Current() == null, "it closes by itself after 30 s");
|
||||
now += RynthCore.Plugin.RynthAi.Huds.CastWarningHud.RepeatSameMs;
|
||||
hud.Post("Strength Self VI", "later");
|
||||
Check.Eq(hud.Current()?.Body, "later", "after 2 min the same spell shows again");
|
||||
on = false;
|
||||
Check.True(hud.Current() == null, "turning the setting off closes it");
|
||||
hud.Post("Focus Self VI", "x");
|
||||
Check.True(hud.Current() == null, "and nothing shows while off");
|
||||
}
|
||||
|
||||
private static void NoComponentsWarningSetting()
|
||||
{
|
||||
Check.True(new LegacyUiSettings().ShowNoComponentsWarning, "a new profile: on");
|
||||
var old = JsonSerializer.Deserialize("{\"EnableBuffing\":true}", RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(old != null && old.ShowNoComponentsWarning, "a profile saved before the setting: on");
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", BindingFlags.NonPublic | BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { ShowNoComponentsWarning = false }, dst });
|
||||
Check.False(dst.ShowNoComponentsWarning, "a profile with it off loads off");
|
||||
|
||||
var payload = JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.ShowNoComponentsWarning == null, "an older engine's payload has no value");
|
||||
var s = new LegacyUiSettings { ShowNoComponentsWarning = false };
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", BindingFlags.NonPublic | BindingFlags.Instance)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", BindingFlags.NonPublic | BindingFlags.Instance)!
|
||||
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
var sent = JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent != null && sent.ShowNoComponentsWarning == false, "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.False(s.ShowNoComponentsWarning, "a save without the field leaves it off");
|
||||
dash.ApplySettingsJson("{\"ShowNoComponentsWarning\":true}");
|
||||
Check.True(s.ShowNoComponentsWarning, "a save with it on turns it on");
|
||||
|
||||
var live = new LegacyUiSettings();
|
||||
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
|
||||
Check.True(map.TryGetValue("ShowNoComponentsWarning", out var entry), "in the settings map");
|
||||
Check.Eq(entry.Get(), "1", "reads on");
|
||||
entry.Set("0");
|
||||
Check.False(live.ShowNoComponentsWarning, "and sets off");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,6 +59,8 @@ internal static class ChestLootTests
|
|||
r.Add("chest loot: no jump-loot from a chest (a hop can take the character out of its use radius)", NoJumpLootFromChest);
|
||||
r.Add("chest loot: a chest gets 2 minutes (not the 12 s corpse timeout), restarted by each pickup", ChestTimeoutLongAndRestarted);
|
||||
r.Add("chest loot: an item the server would refuse for burden (past 300%) is left unsent, with a chat line; one that fits still goes", OverBurdenLeft);
|
||||
r.Add("chest loot (2026-11-28): a matched item the client no longer has (the cache still lists it in the chest) is skipped, not sent, not counted as wanted; the rest still goes", GoneFromClientSkipped);
|
||||
r.Add("chest loot (2026-11-28): a non-stack item that vanishes from the client after its send without showing in a pack is 'not looted', never 'merged into a stack'", VanishedNonStackNotLooted);
|
||||
r.Add("loot burden: ACE's carrying capacity and 300% limit", OverBurdenMath);
|
||||
}
|
||||
|
||||
|
|
@ -264,6 +266,54 @@ internal static class ChestLootTests
|
|||
}
|
||||
}
|
||||
|
||||
// 2026-11-28, Item Tool on a DreamWeave Legendary Chest: the server cleared a leftover 'Platemail
|
||||
// Gauntlets' out of the chest; the cache still listed it there, it matched a Keep rule, the pickup
|
||||
// went out for an object that no longer existed and its absence was read as "merged into a stack".
|
||||
private static void GoneFromClientSkipped()
|
||||
{
|
||||
BaseWorld();
|
||||
AddItem(Gem2, "Fire Opal", ItemTypeGem, Chest);
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.Create(Chest, Gem, Gem2, Spoon);
|
||||
// The client drops the gem (no name, no position); RynthAi's cache still has it in the chest.
|
||||
FakeHost.Names.Remove(Gem);
|
||||
FakeHost.Positions.Remove(Gem);
|
||||
bot.ServerOpens(Chest);
|
||||
LootGemAndFinish(bot, Gem2);
|
||||
bot.TickUntil(() => FakeHost.Closes.Count > 0);
|
||||
Check.False(FakeHost.ExternalMoves.Any(m => m.Item1 == Gem), $"no move for the gone gem (moves: {Moves()})");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("gone from the client") && l.Contains($"{Gem:X8}")), "the skip is logged");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains($"pickup confirmed for 0x{Gem:X8}")), "never 'confirmed'");
|
||||
Check.Eq(bot.Get<int>("_chestKeyTallyWanted"), 1, "the chest looter's tally: one wanted (the gone gem is not)");
|
||||
Check.Eq(bot.Get<int>("_chestKeyTallyTaken"), 1, "and one taken");
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "the chest is finished and closed");
|
||||
}
|
||||
|
||||
// 2026-11-28: a Legendary Chest's 'Helmet' the client was letting go of was picked up and the
|
||||
// pickup "confirmed; merged into a stack in the pack" - a helmet is no stack, and it never landed.
|
||||
private static void VanishedNonStackNotLooted()
|
||||
{
|
||||
BaseWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.Create(Chest, Gem, Spoon);
|
||||
bot.ServerOpens(Chest);
|
||||
bot.TickUntil(() => bot.Moved(Gem));
|
||||
Check.True(bot.Moved(Gem), $"the gem's pickup is sent (moves: {Moves()})");
|
||||
// The client lets the gem go: no name, no position, and the cache is told it was deleted.
|
||||
FakeHost.Names.Remove(Gem);
|
||||
FakeHost.Positions.Remove(Gem);
|
||||
FakeHost.Containers.Remove(Gem);
|
||||
bot.P.OnDeleteObject(Gem);
|
||||
bot.TickUntil(() => FakeHost.Closes.Count > 0, max: 400);
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains($"pickup confirmed for 0x{Gem:X8}")), "not 'confirmed' (" + string.Join(" | ", FakeHost.Logs.Where(l => l.Contains($"{Gem:X8}"))) + ")");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains($"{Gem:X8}") && l.Contains("not looted")), "logged as not looted");
|
||||
Check.Eq(bot.Get<int>("_chestKeyTallyTaken"), 0, "the chest looter's tally: nothing taken");
|
||||
Check.Eq(bot.Get<int>("_chestKeyTallyWanted"), 1, "and one wanted (the Item Tool's nothing-taken stop counts it)");
|
||||
Check.Eq(FakeHost.Closes.Count, 1, "the chest is finished and closed");
|
||||
}
|
||||
|
||||
private static void OverBurdenMath()
|
||||
{
|
||||
Check.Eq(RynthAiPlugin.CarryCapacity(100, 0), 15_000L, "150 per Strength");
|
||||
|
|
|
|||
|
|
@ -69,6 +69,8 @@ internal static class CombatHookTests
|
|||
r.Add("combat hook: a script cast at the fight target is tagged for the Damage tab (element and tier from its spell)", ScriptCastAttribution);
|
||||
r.Add("combat hook: a heal request names the fight target and its health; a nil answer target still heals the player", HealRequestNamesFightTarget);
|
||||
r.Add("combat hook: a refusal after another cast (a heal) or after the script spell landed does not park the script spell", RefusalNotMisattributed);
|
||||
// Spotted by SilentKelpie (rynth PR #12); re-implemented here.
|
||||
r.Add("no components: an attack spell refused for components drops a level (not cast again); a refusal after a later cast is not the attack's", AttackNoComponentsDropsALevel);
|
||||
r.Add("combat hook: a script bolt predicted to kill swaps to the next target like RynthAi's own (not without an alternate, not NOJUDGE)", ScriptKillShotSwaps);
|
||||
r.Add("combat hook: with War and Void untrained, a held attack kind makes the listed wand the weapon: Magic stance, not unarmed Melee", HookMakesWandTheWeapon);
|
||||
}
|
||||
|
|
@ -1654,7 +1656,7 @@ internal static class CombatHookTests
|
|||
MethodInfo issue = typeof(CombatManager).GetMethod("IssueScriptCast", BindingFlags.NonPublic | BindingFlags.Instance)!;
|
||||
void ScriptAttack(HealRig rig) =>
|
||||
Check.True((bool)issue.Invoke(rig.C, new object[] { drain, (uint)Target, RynthAiCombat.FlagArea, "Fire" })!, "the script's attack cast went out");
|
||||
bool HealParked(HealRig rig, int id) => Field<System.Collections.Generic.Dictionary<int, DateTime>>(rig.B, "_noComponentsUntil").ContainsKey(id);
|
||||
bool HealParked(HealRig rig, int id) => Field<SpellManager>(rig.B, "_spellManager").LacksComponents(id);
|
||||
|
||||
// Control: the refusal right after the script's cast is the script spell's.
|
||||
var ctl = new HealRig();
|
||||
|
|
@ -1684,6 +1686,32 @@ internal static class CombatHookTests
|
|||
Check.False(landed.C.ScriptSpellParked(drain), "landed: not parked");
|
||||
});
|
||||
|
||||
private static void AttackNoComponentsDropsALevel() => Guard(() =>
|
||||
{
|
||||
int vi = Id("Flame Bolt VI"), v = Id("Flame Bolt V");
|
||||
void KnowV() { foreach (var row in SpellTable.Named("Flame Bolt V")) FakeHost.Spellbook.Add((uint)row.Id); }
|
||||
|
||||
var rig = new AttackRig(setup: KnowV);
|
||||
rig.Attack();
|
||||
Check.Eq(rig.LastCast, "Flame Bolt VI", "the top level first");
|
||||
rig.C.HandleChatForDebuffs(NoComponents);
|
||||
Check.True(rig.Sm.LacksComponents(vi), "refused for components: that level is passed over");
|
||||
Check.Eq(rig.PendingOffensive, 0, "and the pending cast is cleared");
|
||||
Check.True(FakeHost.Chat.Count(c => c.Contains("No components for Flame Bolt VI: attacking with a lower level")) == 1, "chat says so once");
|
||||
rig.Attack();
|
||||
Check.Eq(rig.LastCast, "Flame Bolt V", "the next attack is a level lower, not the refused level again");
|
||||
Check.Eq(FakeHost.Casts.Count(c => c.SpellId == vi), 1, "the refused level went out once");
|
||||
|
||||
// A heal sent after the attack: the refusal is the heal's, and the attack stays pending.
|
||||
var mixed = new AttackRig(setup: KnowV);
|
||||
mixed.Attack();
|
||||
Check.Eq(mixed.LastCast, "Flame Bolt VI", "mixed: the attack went out");
|
||||
Check.True(ActionPacer.CastSpellFor(mixed.Host, Player, Id("Heal Self V"), "Buff", "Heal Self V"), "mixed: then a heal");
|
||||
mixed.C.HandleChatForDebuffs(NoComponents);
|
||||
Check.False(mixed.Sm.LacksComponents(vi), "mixed: the attack level is not passed over");
|
||||
Check.Eq(mixed.PendingOffensive, vi, "mixed: the attack is still pending");
|
||||
});
|
||||
|
||||
private static void ScriptKillShotSwaps() => Guard(() =>
|
||||
{
|
||||
int bolt = Id("Flame Bolt VI");
|
||||
|
|
|
|||
|
|
@ -36,6 +36,9 @@ internal static class DoorTests
|
|||
r.Add("door: still closed after an answered use, no 'locked' from the server: used again, never picked", NotLockedWithoutServer);
|
||||
r.Add("door: the server says locked: a lockpick goes on it, then the door is opened again", LockedUsesLockpick);
|
||||
r.Add("door: locked and no lockpick: cooldown, and the door is skipped a while", LockedNoPick);
|
||||
r.Add("door: the server says locked: carried keys go first, one at a time (a key that doesn't fit, 0x4B2, goes straight to the next), then the lockpick", LockedKeysThenLockpick);
|
||||
r.Add("door: the server says locked: a key that fits is followed by an open, no lockpick; a lockpick is never tried as a key", LockedKeyFits);
|
||||
r.Add("door: Auto-Unlock Doors off: no key and no lockpick on a locked door", LockedKeysNeedAutoUnlock);
|
||||
r.Add("door: nothing in portal space, nor just after it", NothingInPortalSpace);
|
||||
r.Add("door: a door that opens is released at once (no fixed waits)", OpensFast);
|
||||
r.Add("door: 'locked' from chat counts only as the server's line, not a player's", LockedChatLine);
|
||||
|
|
@ -83,7 +86,7 @@ internal static class DoorTests
|
|||
public long Now = 50_000_000;
|
||||
public readonly RynthCoreHost Host;
|
||||
|
||||
public Bot(bool lockpick = true)
|
||||
public Bot(bool lockpick = true, Action? beforeCreate = null)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true; // UseObject
|
||||
|
|
@ -100,6 +103,7 @@ internal static class DoorTests
|
|||
FakeHost.ObjectStates[Door] = Closed;
|
||||
FakeHost.Names[Pick] = "Plain Lockpick";
|
||||
FakeHost.Names[Kit] = "Treated Healing Kit";
|
||||
beforeCreate?.Invoke();
|
||||
Host = FakeHost.Create(Player);
|
||||
|
||||
ActionPacer.Reset();
|
||||
|
|
@ -127,6 +131,8 @@ internal static class DoorTests
|
|||
Cache.OnCreateObject(Door);
|
||||
_ = Cache[unchecked((int)Pick)];
|
||||
_ = Cache[unchecked((int)Kit)];
|
||||
foreach (uint k in new[] { KeyA, KeyB, KeyC, PackPick })
|
||||
if (FakeHost.Names.ContainsKey(k)) _ = Cache[unchecked((int)k)];
|
||||
Cache.Tick();
|
||||
if (lockpick)
|
||||
S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Pick), Name = "Plain Lockpick", Type = "Lockpick" });
|
||||
|
|
@ -280,6 +286,98 @@ internal static class DoorTests
|
|||
Check.Eq(b.State, "None", "done");
|
||||
});
|
||||
|
||||
// ── Carried keys before lockpicks (2026-11-27; spotted by SilentKelpie, Forgejo rynth PR #12) ──
|
||||
|
||||
private const uint KeyA = 0x80000D13, KeyB = 0x80000D14, KeyC = 0x80000D15, PackPick = 0x80000D16;
|
||||
private const uint TypeKey = 0x4000; // AC ItemType.Key (lockpicks have it too)
|
||||
|
||||
/// <summary>Puts a key (or a key-typed lockpick) in the pack before the rig is made.</summary>
|
||||
private static void Carry(uint id, string name, bool lockpickBit = false)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.ItemTypes[id] = TypeKey;
|
||||
FakeHost.Containers[id] = Player;
|
||||
if (lockpickBit) FakeHost.Bitfields[id] = 0x20000; // BF_LOCKPICK
|
||||
}
|
||||
|
||||
private static int KeyUses(uint key) => FakeHost.UsesOn.Count(u => u.Source == key && u.Target == Door);
|
||||
|
||||
/// <summary>Uses the door, and the server says it is locked.</summary>
|
||||
private static void LockedAnswer(Bot b)
|
||||
{
|
||||
b.Run(1500, 100);
|
||||
b.Say("The door is locked!");
|
||||
b.Answer(open: false);
|
||||
b.Run(300);
|
||||
}
|
||||
|
||||
private static void LockedKeysThenLockpick() => With(() =>
|
||||
{
|
||||
var b = new Bot(lockpick: true, beforeCreate: () =>
|
||||
{
|
||||
Carry(KeyA, "Rusty Key");
|
||||
Carry(KeyB, "Cave Door Key");
|
||||
});
|
||||
b.Tick();
|
||||
b.Run(300);
|
||||
Check.Eq(DoorUses(), 1, "first use");
|
||||
LockedAnswer(b);
|
||||
int first = KeyUses(KeyA) + KeyUses(KeyB);
|
||||
Check.Eq(first, 1, "locked: one carried key goes on the door first");
|
||||
Check.Eq(Picks(), 0, "...not the lockpick");
|
||||
Check.Eq(DoorUses(), 1, "...and no open over it");
|
||||
|
||||
FakeHost.UseDone(0x4B2); // KeyDoesntFitThisLock: nothing spent
|
||||
b.Run(300);
|
||||
Check.Eq(KeyUses(KeyA) + KeyUses(KeyB), 2, "didn't fit: the other key goes at once");
|
||||
Check.True(KeyUses(KeyA) == 1 && KeyUses(KeyB) == 1, "each key once");
|
||||
Check.Eq(DoorUses(), 1, "no open between keys that don't fit");
|
||||
|
||||
FakeHost.UseDone(0x4B2);
|
||||
b.Run(300);
|
||||
Check.Eq(Picks(), 1, "no key left: the lockpick");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("doesn't fit")), "the keys that didn't fit are logged");
|
||||
FakeHost.UseDone(0);
|
||||
b.Run(300);
|
||||
Check.Eq(DoorUses(), 2, "opened again after the lockpick");
|
||||
Check.Eq(KeyUses(KeyA) + KeyUses(KeyB), 2, "no key tried twice");
|
||||
});
|
||||
|
||||
private static void LockedKeyFits() => With(() =>
|
||||
{
|
||||
var b = new Bot(lockpick: true, beforeCreate: () =>
|
||||
{
|
||||
Carry(PackPick, "Reliable Lockpick", lockpickBit: true); // key-typed, but a lockpick
|
||||
Carry(KeyC, "Black Gate Key");
|
||||
});
|
||||
b.Tick();
|
||||
b.Run(300);
|
||||
LockedAnswer(b);
|
||||
Check.Eq(KeyUses(KeyC), 1, "the key goes on the door");
|
||||
Check.Eq(KeyUses(PackPick), 0, "a lockpick is never tried as a key");
|
||||
FakeHost.UseDone(0); // it fit
|
||||
b.Run(300);
|
||||
Check.Eq(DoorUses(), 2, "opened again after the key");
|
||||
Check.Eq(Picks(), 0, "no lockpick");
|
||||
b.Run(800);
|
||||
b.Answer(open: true);
|
||||
b.Now += 50;
|
||||
Check.False(b.Tick(), "opened: nav released");
|
||||
Check.Eq(b.State, "None", "done");
|
||||
});
|
||||
|
||||
private static void LockedKeysNeedAutoUnlock() => With(() =>
|
||||
{
|
||||
var b = new Bot(lockpick: true, beforeCreate: () => Carry(KeyA, "Rusty Key"));
|
||||
b.S.AutoUnlockDoors = false;
|
||||
b.Tick();
|
||||
b.Run(300);
|
||||
LockedAnswer(b);
|
||||
Check.Eq(KeyUses(KeyA), 0, "no key");
|
||||
Check.Eq(Picks(), 0, "no lockpick");
|
||||
Check.Eq(b.State, "Cooldown", "cooldown");
|
||||
});
|
||||
|
||||
private static void LockedNoPick() => With(() =>
|
||||
{
|
||||
var b = new Bot(lockpick: false);
|
||||
|
|
|
|||
|
|
@ -16,6 +16,147 @@ internal static class DunNavToTests
|
|||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("dunnav-to: walks to an object's cell on the dungeon map, the macro on; refuses an unknown one or one outside the dungeon", WalksToObject);
|
||||
r.Add("dunnav-to cell: walks to a cell of the dungeon by its number (a person the client hasn't been sent yet), labelled; refuses another dungeon's or a bad cell", WalksToCell);
|
||||
r.Add("dunnav-to walkonly: fighting, looting, buffing and the meta off for the walk, put back exactly as they were when it ends, stops or fails", WalkOnlyTrip);
|
||||
}
|
||||
|
||||
// RynthNav's go to someone inside a dungeon hands the walk on as "/ra dunnav-to cell <cell> walkonly <name>"
|
||||
// by default (2026-11-27): a run to the target with no fighting, looting or buffing on the way.
|
||||
private static void WalkOnlyTrip()
|
||||
{
|
||||
var rig = new DunRouteTests.Rig("NavProfiles-dunnav-to-walkonly");
|
||||
string cell = rig.D.West.ToString("X8");
|
||||
void Switches(bool combat, bool loot, bool buff, bool meta)
|
||||
{
|
||||
rig.S.EnableCombat = combat; rig.S.EnableLooting = loot; rig.S.EnableBuffing = buff; rig.S.EnableMeta = meta;
|
||||
}
|
||||
string Now() => $"combat {rig.S.EnableCombat} loot {rig.S.EnableLooting} buff {rig.S.EnableBuffing} meta {rig.S.EnableMeta} macro {rig.S.IsMacroRunning}";
|
||||
List<string> Tick()
|
||||
{
|
||||
int before = FakeHost.Chat.Count;
|
||||
rig.Call("TickWalkTrip");
|
||||
return FakeHost.Chat.Skip(before).ToList();
|
||||
}
|
||||
|
||||
// 1. Arrives: everything back, and the macro off again (it was off).
|
||||
rig.S.IsMacroRunning = false;
|
||||
Switches(true, true, true, true);
|
||||
var said = rig.Typed($"/ra dunnav-to cell {cell} walkonly Hall Keeper");
|
||||
Check.True(said.Count == 1 && said[0].StartsWith("[RynthAi] DunNav-To: 'Hall Keeper' in " + cell) && said[0].Contains("walk only"),
|
||||
"it answers, the label without the word walkonly: " + string.Join(" | ", said));
|
||||
Check.True(rig.S.IsMacroRunning && rig.S.EnableNavigation, "macro and navigation on for the walk");
|
||||
Check.False(rig.S.EnableCombat || rig.S.EnableLooting || rig.S.EnableBuffing || rig.S.EnableMeta, "no fighting, looting, buffing or meta on the way: " + Now());
|
||||
Check.True(Tick().Count == 0, "walking: nothing said");
|
||||
Check.False(rig.S.EnableCombat, "still walking: combat stays off");
|
||||
rig.S.ActiveNavIndex = rig.S.CurrentRoute.Points.Count; // the nav engine walked off the last point
|
||||
rig.S.EnableNavigation = false;
|
||||
said = Tick();
|
||||
Check.True(said.Count == 1 && said[0].Contains("ended (arrived)") && said[0].Contains("macro off again"), "arrived: said: " + string.Join(" | ", said));
|
||||
Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.EnableMeta && !rig.S.IsMacroRunning, "all back as before: " + Now());
|
||||
Check.True(Tick().Count == 0, "over: nothing more");
|
||||
|
||||
// 2. The player stops the macro mid-walk: a mixed set back as it was, the macro stays off.
|
||||
rig.S.IsMacroRunning = true;
|
||||
Switches(false, true, false, true);
|
||||
rig.Typed($"/ra dunnav-to cell {cell} walkonly");
|
||||
Check.False(rig.S.EnableLooting || rig.S.EnableMeta, "off for the walk");
|
||||
rig.S.IsMacroRunning = false;
|
||||
said = Tick();
|
||||
Check.True(said.Count == 1 && said[0].Contains("the macro was stopped"), "stopped: said: " + string.Join(" | ", said));
|
||||
Check.True(!rig.S.EnableCombat && rig.S.EnableLooting && !rig.S.EnableBuffing && rig.S.EnableMeta && !rig.S.IsMacroRunning, "back exactly: " + Now());
|
||||
|
||||
// 3. The macro was on before: it stays on at the end; nav switched off counts as the end.
|
||||
rig.S.IsMacroRunning = true;
|
||||
Switches(true, false, true, false);
|
||||
rig.Typed($"/ra dunnav-to cell {cell} walkonly");
|
||||
rig.S.EnableNavigation = false;
|
||||
said = Tick();
|
||||
Check.True(said.Count == 1 && said[0].Contains("navigation was turned off") && !said[0].Contains("macro off"), "nav off: " + string.Join(" | ", said));
|
||||
Check.True(rig.S.EnableCombat && !rig.S.EnableLooting && rig.S.EnableBuffing && !rig.S.EnableMeta && rig.S.IsMacroRunning, "back, the macro still on: " + Now());
|
||||
|
||||
// 4. Another route loaded (a meta, a script, the player): the switches back, the macro left to its new owner.
|
||||
rig.S.IsMacroRunning = false;
|
||||
Switches(true, true, true, true);
|
||||
rig.Typed($"/ra dunnav-to cell {cell} walkonly");
|
||||
rig.S.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Circular };
|
||||
said = Tick();
|
||||
Check.True(said.Count == 1 && said[0].Contains("another route was loaded"), "another route: " + string.Join(" | ", said));
|
||||
Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.EnableMeta && rig.S.IsMacroRunning, "switches back, macro left on: " + Now());
|
||||
|
||||
// 5. Out of the dungeon mid-walk (a portal, a recall, a death): back, the macro off again.
|
||||
rig.S.IsMacroRunning = false;
|
||||
Switches(true, true, true, true);
|
||||
rig.Typed($"/ra dunnav-to cell {cell} walkonly");
|
||||
rig.At(10, 10, 0xA9B40020);
|
||||
said = Tick();
|
||||
Check.True(said.Count == 1 && said[0].Contains("you left the dungeon"), "left: " + string.Join(" | ", said));
|
||||
Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.EnableMeta && !rig.S.IsMacroRunning, "back: " + Now());
|
||||
rig.At(15, 15, rig.D.Start);
|
||||
|
||||
// 6. A second walk-only trip over the first: the player's switches are kept, not the first trip's offs.
|
||||
rig.S.IsMacroRunning = false;
|
||||
Switches(true, true, false, true);
|
||||
rig.Typed($"/ra dunnav-to cell {cell} walkonly");
|
||||
rig.Typed($"/ra dunnav-to cell {cell} walkonly");
|
||||
rig.S.IsMacroRunning = false;
|
||||
Tick();
|
||||
Check.True(rig.S.EnableCombat && rig.S.EnableLooting && !rig.S.EnableBuffing && rig.S.EnableMeta, "the player's own, after two trips: " + Now());
|
||||
|
||||
// 7. Unloaded or logged out mid-walk: the switches back before the profile is saved.
|
||||
Switches(true, true, true, true);
|
||||
rig.S.IsMacroRunning = false;
|
||||
rig.Typed($"/ra dunnav-to cell {cell} walkonly");
|
||||
rig.Call("ForgetWalkTrip");
|
||||
Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.EnableMeta, "back for the save: " + Now());
|
||||
Check.True(rig.Get("_walkTrip") == null, "the trip is forgotten");
|
||||
|
||||
// Without walkonly the walk runs the macro as set (fight on the way in), the switches untouched.
|
||||
rig.S.IsMacroRunning = false;
|
||||
Switches(true, true, true, false);
|
||||
rig.Typed($"/ra dunnav-to cell {cell} Hall Keeper");
|
||||
Check.True(rig.S.EnableCombat && rig.S.EnableLooting && rig.S.EnableBuffing && rig.S.IsMacroRunning, "no walkonly: as set: " + Now());
|
||||
Check.True(rig.Get("_walkTrip") == null, "no trip");
|
||||
}
|
||||
|
||||
// RynthNav's go to someone inside a dungeon hands the walk on as "/ra dunnav-to cell <cell> <name>" (2026-11-27).
|
||||
// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here.
|
||||
private static void WalksToCell()
|
||||
{
|
||||
var rig = new DunRouteTests.Rig("NavProfiles-dunnav-to-cell");
|
||||
rig.S.IsMacroRunning = false;
|
||||
string cell = rig.D.West.ToString("X8");
|
||||
|
||||
var said = rig.Typed($"/ra dunnav-to cell {cell} Hall Keeper");
|
||||
Check.True(said.Count == 1 && said[0].StartsWith("[RynthAi] DunNav-To: 'Hall Keeper' in " + cell) && said[0].Contains("walking there"),
|
||||
"it answers with the label: " + string.Join(" | ", said));
|
||||
var pts = rig.S.CurrentRoute.Points;
|
||||
Check.True(pts.Count >= 2, $"a walk ({pts.Count} points)");
|
||||
Check.True(rig.S.IsMacroRunning && rig.S.EnableNavigation, "macro and navigation on");
|
||||
var last = pts[^1];
|
||||
double lx = DungeonGeometry.NavToWorld(last.EW) - DunRouteTests.Ox, ly = DungeonGeometry.NavToWorld(last.NS) - DunRouteTests.Oy;
|
||||
Check.True(Math.Abs(lx - -17.5) < 3 && Math.Abs(ly - 25) < 3, $"it ends in the west room's middle ({lx:F1}, {ly:F1})");
|
||||
|
||||
// No label: the cell names itself. Lower case and 0x work.
|
||||
rig.S.IsMacroRunning = false;
|
||||
said = rig.Typed($"/ra dunnav-to cell 0x{cell.ToLowerInvariant()}");
|
||||
Check.True(said.Count == 1 && said[0].Contains($"'cell {cell}'"), "unlabelled: " + string.Join(" | ", said));
|
||||
|
||||
var before = rig.S.CurrentRoute;
|
||||
said = rig.Typed("/ra dunnav-to cell 009C0270 Someone");
|
||||
Check.True(said.Count == 1 && said[0].Contains("isn't in this dungeon"), "another dungeon's cell: " + string.Join(" | ", said));
|
||||
said = rig.Typed($"/ra dunnav-to cell {(DunRouteTests.Lb << 16 | 0x0F00):X8}");
|
||||
Check.True(said.Count == 1 && said[0].Contains("isn't on this dungeon's map"), "a cell the map hasn't: " + string.Join(" | ", said));
|
||||
said = rig.Typed("/ra dunnav-to cell 12");
|
||||
Check.True(said.Count == 1 && said[0].Contains("Usage: /ra dunnav-to"), "a bad cell: the usage");
|
||||
said = rig.Typed($"/ra dunnav-to cell {(DunRouteTests.Lb << 16 | 0x0020):X8}");
|
||||
Check.True(said.Count == 1 && said[0].Contains("Usage: /ra dunnav-to"), "an outdoor cell: the usage");
|
||||
Check.True(ReferenceEquals(rig.S.CurrentRoute, before), "the walk in hand is left alone");
|
||||
|
||||
// Standing in that cell already: said so, nothing laid.
|
||||
rig.At(-17.5, 25, rig.D.West);
|
||||
said = rig.Typed($"/ra dunnav-to cell {cell}");
|
||||
Check.True(said.Count == 1 && said[0].Contains("already in"), "there already: " + string.Join(" | ", said));
|
||||
Check.True(ReferenceEquals(rig.S.CurrentRoute, before), "nothing laid when there");
|
||||
}
|
||||
|
||||
private const uint Rat = 0x7E7E9101, Outside = 0x7E7E9102, Unknown = 0x7E7E9103;
|
||||
|
|
|
|||
|
|
@ -710,10 +710,10 @@ internal static class ExpressionTests
|
|||
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, 0]", "1");
|
||||
Check.Eq(s.ChestRelockWaitSec, 1, "ChestRelockWaitSec clamps to at least 1 (MinRelockWaitSec since the fast re-lock)");
|
||||
Is(e, "vtsetsetting[ChestRelockWaitSec, soon]", "1");
|
||||
Check.Eq(s.ChestRelockWaitSec, 5, "unparsable leaves the value");
|
||||
Check.Eq(s.ChestRelockWaitSec, 1, "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");
|
||||
|
|
@ -920,7 +920,13 @@ internal static class ExpressionTests
|
|||
qt.OnChatLine("blankaug - 1 solves (1609459200)\"Blank Aug\" 1 0");
|
||||
qt.OnChatLine($"killtask - 12 solves ({recent})\"Kill task\" 50 3600");
|
||||
qt.OnChatLine("oldtimer - 3 solves (1609459200)\"Old timer\" 10 3600");
|
||||
// A space after the timestamp and -1 max solves (unlimited): still read, timer and all.
|
||||
qt.OnChatLine($"spacedwait - 42 solves ({recent}) \"Spaced wait\" -1 3600");
|
||||
qt.OnChatLine("You say, \"hello\"");
|
||||
Check.True(qt.TryGetFlag("spacedwait", out var spaced) && spaced.Description == "Spaced wait"
|
||||
&& spaced.MaxSolves == -1 && spaced.RepeatTime == TimeSpan.FromSeconds(3600),
|
||||
"a line with a space after the timestamp keeps its description, max solves and repeat time");
|
||||
Is(e, "getqueststatus[spacedwait]", "0"); // its timer is still running
|
||||
Is(e, "testquestflag[BlankAug]", "1");
|
||||
Is(e, "testquestflag[nothere]", "0");
|
||||
Is(e, "getqueststatus[blankaug]", "0"); // once-only, done: never ready again
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ internal static class GiveTests
|
|||
r.Add("give: busy refusals re-send with no cap", BusyResendsUncapped);
|
||||
r.Add("give: a permanent refusal skips the stack at once and moves on", PermanentSkips);
|
||||
r.Add("give: item not found after a re-send counts as given", ItemNotFoundAfterResendCounts);
|
||||
r.Add("give: 'You allow X to examine your Y' is an answer: no re-send, the next stack goes, counted apart", ExaminedIsAnAnswer);
|
||||
r.Add("give: the summary counts items, not stacks", SummaryCountsItems);
|
||||
r.Add("give: no answer at all re-sends once, then skips", NoAnswerSkips);
|
||||
r.Add("give: an unreadable stack count is no information, not a shrink", UnreadableStackIsNotAShrink);
|
||||
|
|
@ -408,6 +409,27 @@ internal static class GiveTests
|
|||
Check.True(w.ChatHas("1 item(s) given, 1 stack(s) skipped"), "summary: one given, one skipped with its reason");
|
||||
}
|
||||
|
||||
// ACE's Refuse emote (an NPC that only looks at an item, e.g. to stamp a parchment) leaves the item with
|
||||
// the player and says "You allow X to examine your Y." That was no answer: re-sent, then skipped.
|
||||
private static void ExaminedIsAnAnswer()
|
||||
{
|
||||
var w = new World();
|
||||
FakeHost.GiveLands = false;
|
||||
w.Call("EnqueueGive", Mote1, Npc, 1);
|
||||
w.Call("EnqueueGive", Mote2, Npc, 1);
|
||||
w.Tick();
|
||||
Check.Eq(FakeHost.Gives.Count, 1, "first stack out");
|
||||
w.Chat("You allow Town Crier to examine your Mana Mote.");
|
||||
w.Tick();
|
||||
Check.Eq(FakeHost.Gives.Count, 2, "answered: the next stack goes on that same tick");
|
||||
Check.Eq(FakeHost.Gives[1].Item, Mote2, "the second stack, not a re-send of the first");
|
||||
w.Chat("You allow Town Crier to examine your Mana Mote.");
|
||||
w.Tick();
|
||||
w.Tick(3001);
|
||||
Check.Eq(FakeHost.Gives.Count, 2, "no re-send after the confirm time");
|
||||
Check.True(w.ChatHas("0 item(s) given, 2 examined and handed back, 0 stack(s) skipped"), "summary: examined, not given or skipped");
|
||||
}
|
||||
|
||||
private static void ItemNotFoundAfterResendCounts()
|
||||
{
|
||||
var w = new World();
|
||||
|
|
|
|||
|
|
@ -40,7 +40,10 @@ 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: keys that are spent go past 300 chests until they are gone; the two-line uses-left message is read (2026-11-28 'after 300 keys it stops')", ChestSpentKeysPastMaxCycles);
|
||||
r.Add("chest looter: a chest seen re-locking (unlocked after the key, locked again, shown closed) is keyed again at once, whatever the wait; a stale locked read is not (2026-11-28 'the 5s ... is way too long')", ChestRelockSeenGoesAtOnce);
|
||||
r.Add("chest looter: 3 chests in a row with wanted loot and nothing picked up stop the run with the item and why (2026-11-28)", ChestStopsWhenNothingTaken);
|
||||
r.Add("chest looter: the re-lock wait is the 'Chest re-lock wait (s)' setting, clamped 1..600; after the loot it waits for the close seen (or 2 s); 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);
|
||||
|
|
@ -48,12 +51,18 @@ internal static class ItemToolTests
|
|||
r.Add("quick give: a refused item is left out; three refusals in a row stop it", GiveRefusals);
|
||||
r.Add("quick give: stops when the target vanishes, changes, moves away or a fight starts", GiveStopConditions);
|
||||
r.Add("quick give: refuses to start with the target far, unloaded, no item or in a fight; busy client waits", GiveStartRefusals);
|
||||
r.Add("quick give Amount: a round gives that many units, splitting a bigger stack (the rest stays in the pack)", GiveAmountSplits);
|
||||
r.Add("quick give Amount: with an NPC that takes one per give, the round still stops at the amount", GiveAmountOnePerGive);
|
||||
r.Add("quick give Every: rounds repeat after the interval until Stop; none left, out of range or a fight only hold the next round", GiveEveryRounds);
|
||||
r.Add("quick give Every: a fight or the target leaving mid-round ends the round, not the run; a changed target ends the run", GiveEveryMidRound);
|
||||
// Plugin glue
|
||||
r.Add("item tool: the chest looter picks the selected chest and key, unlocks, opens and loots with the macro off, stops when out of keys", PluginChestRun);
|
||||
r.Add("item tool: chest/key picks refuse the wrong things (a pack item as chest, a world object as key, house storage)", PluginChestPicks);
|
||||
r.Add("item tool: a full main pack holds no key while a side pack has room (the looter makes room); every pack full or under the 2-slot reserve holds it (2026-11-28)", PluginNoRoomOnlyWhenAllFull);
|
||||
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 giveamount / giveevery set, clamp and answer (any source); the panel's data carries them", PluginGiveAmountEvery);
|
||||
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);
|
||||
}
|
||||
|
|
@ -82,6 +91,7 @@ internal static class ItemToolTests
|
|||
/// <summary>> 0: the corpse looter is played: it takes a requested chest and lets go this long after.</summary>
|
||||
public long AutoLootMs;
|
||||
public bool IgnoreStart; // StartLooting does nothing (the looter never takes the chest)
|
||||
public bool RelockOnClose; // the loot's end sets Locked = true (a chest that resets as it closes)
|
||||
private long _lootEnd;
|
||||
|
||||
// The server's script for the next key use / open: filled by the test, run on send.
|
||||
|
|
@ -126,6 +136,18 @@ internal static class ItemToolTests
|
|||
public bool Looting(int chestId) => LootPending || LootingNow;
|
||||
public void AbortLooting(int chestId) { Aborts++; LootPending = LootingNow = false; }
|
||||
public bool? ChestLockedHint(int chestId) => Locked;
|
||||
public bool? ShownOpen;
|
||||
public bool? ChestShownOpen(int chestId) => ShownOpen;
|
||||
// The corpse looter's tally of the last session (null = not known).
|
||||
public Func<(int Wanted, int Taken)>? Tally;
|
||||
public bool LastLootTally(int chestId, out int wanted, out int taken, out string firstWanted)
|
||||
{
|
||||
wanted = taken = 0; firstWanted = "";
|
||||
if (Tally == null) return false;
|
||||
(wanted, taken) = Tally();
|
||||
firstWanted = "Olthoi Breastplate";
|
||||
return true;
|
||||
}
|
||||
public void Say(string text) => Said.Add(text);
|
||||
public void Log(string text) => Logs.Add(text);
|
||||
|
||||
|
|
@ -139,7 +161,11 @@ internal static class ItemToolTests
|
|||
if (AutoLootMs > 0)
|
||||
{
|
||||
if (LootPending) { LootPending = false; LootingNow = true; _lootEnd = T + AutoLootMs; }
|
||||
else if (LootingNow && T >= _lootEnd) LootingNow = false;
|
||||
else if (LootingNow && T >= _lootEnd)
|
||||
{
|
||||
LootingNow = false;
|
||||
if (RelockOnClose) Locked = true; // ChestRegenOnClose: the close resets it (Locked=true)
|
||||
}
|
||||
}
|
||||
Looter.Tick();
|
||||
}
|
||||
|
|
@ -451,15 +477,145 @@ internal static class ItemToolTests
|
|||
ck.Start(out _);
|
||||
env.Run(60_000_000, () => !ck.Running);
|
||||
Check.False(ck.Running, "ended");
|
||||
Check.Eq(ck.Looted, ChestKeyLooter.MaxCycles, "after MaxCycles chests");
|
||||
Check.Eq(ck.Looted, ChestKeyLooter.MaxCycles, "after MaxCycles chests with no key use spent");
|
||||
string said = Said(env);
|
||||
Check.True(said.Contains($"{ChestKeyLooter.MaxCycles} cycles"), "says why: " + said.Substring(Math.Max(0, said.Length - 200)));
|
||||
Check.True(said.Contains($"{ChestKeyLooter.MaxCycles} chests in a row without a key use spent"), "says why: " + said.Substring(Math.Max(0, said.Length - 200)));
|
||||
}
|
||||
|
||||
// "after 300 keys it stops" (2026-11-28): keys that are spent run on until they are gone.
|
||||
private static void ChestSpentKeysPastMaxCycles()
|
||||
{
|
||||
const int uses = ChestKeyLooter.MaxCycles + 50;
|
||||
var env = NewChest(out var ck);
|
||||
env.Keys.Clear(); env.Keys.Add(11);
|
||||
env.AutoLootMs = 300;
|
||||
// ACE's one two-line message per unlock: "The X has been unlocked.\nYour key has N uses left."
|
||||
int left = uses;
|
||||
env.OnKey = key =>
|
||||
{
|
||||
left--;
|
||||
ck.OnChat(left > 0 ? $"The Mana Forge Chest has been unlocked.\nYour key has {left} use{(left == 1 ? "" : "s")} left." : "The Mana Forge Chest has been unlocked.\nYour key is used up.");
|
||||
if (left <= 0) env.Keys.Remove(key);
|
||||
env.Locked = false;
|
||||
return 0u;
|
||||
};
|
||||
env.OnOpen = () => true;
|
||||
ck.RelockWaitSec = 1;
|
||||
ck.Start(out _);
|
||||
env.Run(3000, () => env.LootStarts > 0);
|
||||
Check.Eq(ck.UsesLeft, uses - 1, "the uses-left line inside the two-line message is read (" + ck.UsesLeft + ")");
|
||||
env.Run(60_000_000, () => !ck.Running);
|
||||
Check.False(ck.Running, "ended");
|
||||
Check.Eq(ck.Looted, uses, $"all {uses} uses looted, past {ChestKeyLooter.MaxCycles}");
|
||||
Check.True(Said(env).Contains($"out of keys after {uses} chest(s)"), "ends out of keys: " + Said(env).Substring(Math.Max(0, Said(env).Length - 200)));
|
||||
|
||||
// A key that is used up and replaced by another of the same name counts as spent too, even with no chat line.
|
||||
var e2 = NewChest(out var c2);
|
||||
e2.Keys.Clear();
|
||||
for (int k = 0; k < ChestKeyLooter.MaxCycles + 20; k++) e2.Keys.Add(100 + k);
|
||||
c2.SetKey(100, "Aged Key");
|
||||
e2.AutoLootMs = 300;
|
||||
e2.OnKey = key => { e2.Keys.Remove(key); return 0u; }; // one use per key, no chat
|
||||
c2.RelockWaitSec = 1;
|
||||
c2.Start(out _);
|
||||
e2.Run(60_000_000, () => !c2.Running);
|
||||
Check.Eq(c2.Looted, ChestKeyLooter.MaxCycles + 20, "one-use keys with no chat line: every key used, past the cap");
|
||||
}
|
||||
|
||||
// 2026-11-28: a chest that re-locks as it closes is keyed again as soon as the client sees that,
|
||||
// whatever the wait (the server's Locked=false on the unlock, Locked=true on the reset).
|
||||
private static void ChestRelockSeenGoesAtOnce()
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Unlimited = true;
|
||||
env.AutoLootMs = 1000;
|
||||
env.ShownOpen = false;
|
||||
env.RelockOnClose = true;
|
||||
var keyAt = new List<long>();
|
||||
env.Locked = true;
|
||||
env.OnKey = _ => { keyAt.Add(env.T); env.Locked = false; return 0u; }; // the unlock's Locked=false
|
||||
ck.Start(out _);
|
||||
Check.Eq(ck.RelockWaitSec, ChestKeyLooter.DefaultRelockWaitSec, "the default 125 s wait");
|
||||
env.Run(5000, () => ck.State == ChestKeyLooter.Phase.Waiting);
|
||||
Check.Eq(ck.State, ChestKeyLooter.Phase.Waiting, "looted, waiting");
|
||||
long lootDone = env.T;
|
||||
env.Run(10_000, () => keyAt.Count >= 2);
|
||||
Check.Eq(keyAt.Count, 2, "the next key went");
|
||||
Check.True(env.T - lootDone < 1_000, $"within a second of the re-lock, not 125 s ({env.T - lootDone} ms)");
|
||||
Check.True(env.Logs.Any(l => l.Contains("re-locked")), "the re-lock is logged");
|
||||
Check.True(ck.RelockSeen, "the run knows the chest re-locks as it closes (the panel hides the wait)");
|
||||
Check.Eq(env.Said.Count(s => s.Contains("re-locks as it closes")), 1, "said in chat once");
|
||||
env.Run(5000, () => ck.State == ChestKeyLooter.Phase.Waiting);
|
||||
Check.True(ck.Status.Contains("it re-locks as it closes") && !ck.Status.Contains(" s) -"), "no countdown in the status: " + ck.Status);
|
||||
|
||||
// A whole cycle on such a chest takes ~the loot time plus a little, not the 5 s floor of before.
|
||||
env.Run(60_000, () => keyAt.Count >= 12);
|
||||
long per = (keyAt[11] - keyAt[1]) / 10;
|
||||
Check.True(per < 3_000, $"a cycle takes {per} ms (loot 1 s + open + settle)");
|
||||
|
||||
// The re-lock waits for the close: shown open, the key does not go.
|
||||
var e2 = NewChest(out var c2);
|
||||
e2.Unlimited = true; e2.AutoLootMs = 1000; e2.ShownOpen = true;
|
||||
int keys2 = 0;
|
||||
e2.OnKey = _ => { keys2++; e2.Locked = false; return 0u; };
|
||||
c2.Start(out _);
|
||||
e2.Run(5000, () => c2.State == ChestKeyLooter.Phase.Waiting);
|
||||
e2.Locked = true;
|
||||
e2.Run(1_500);
|
||||
Check.Eq(keys2, 1, "the client still shows the chest open: no key yet");
|
||||
e2.ShownOpen = false;
|
||||
e2.Run(2_000, () => keys2 >= 2);
|
||||
Check.Eq(keys2, 2, "shown closed: it goes");
|
||||
|
||||
// A locked read never preceded by an unlocked one (stale) does not cut the wait short.
|
||||
var e3 = NewChest(out var c3);
|
||||
e3.Unlimited = true; e3.AutoLootMs = 1000; e3.ShownOpen = false; e3.Locked = true;
|
||||
int keys3 = 0;
|
||||
e3.OnKey = _ => { keys3++; return 0u; }; // no Locked=false ever arrives
|
||||
c3.Start(out _);
|
||||
e3.Run(5000, () => c3.State == ChestKeyLooter.Phase.Waiting);
|
||||
e3.Run(ChestKeyLooter.MinRelockMs - 3000);
|
||||
Check.Eq(keys3, 1, "a stale locked read: no key before MinRelockMs");
|
||||
}
|
||||
|
||||
// "after a certain amount of time it stops picking up items, chest opens, but items don't get picked up" (2026-11-28).
|
||||
private static void ChestStopsWhenNothingTaken()
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Unlimited = true;
|
||||
env.AutoLootMs = 300;
|
||||
Serve(env, ck, spendKey: false);
|
||||
int chest = 0;
|
||||
env.Tally = () => chest switch { 1 => (2, 1), 2 => (0, 0), _ => (2, 0) }; // 1: took 1 of 2; 2: nothing wanted; then: wanted, none taken
|
||||
env.OnOpen = () => { chest++; return true; };
|
||||
ck.RelockWaitSec = 1;
|
||||
ck.Start(out _);
|
||||
env.Run(600_000, () => !ck.Running);
|
||||
Check.False(ck.Running, "stopped");
|
||||
Check.Eq(ck.Looted, 2 + ChestKeyLooter.MaxStarvedChests, $"after {ChestKeyLooter.MaxStarvedChests} chests in a row with wanted loot and none taken");
|
||||
string said = Said(env);
|
||||
Check.True(said.Contains("none of it could be picked up") && said.Contains("Olthoi Breastplate") && said.Contains("no more keys spent"), "says why and names the item: " + said);
|
||||
Check.True(said.Contains("took 1 of 2 wanted"), "each chest says what it took: " + said);
|
||||
|
||||
// One chest that gives something resets the count.
|
||||
var e2 = NewChest(out var c2);
|
||||
e2.Unlimited = true; e2.AutoLootMs = 300;
|
||||
Serve(e2, c2, spendKey: false);
|
||||
int n2 = 0;
|
||||
e2.Tally = () => n2 % 2 == 0 ? (1, 1) : (1, 0); // every other chest gives nothing
|
||||
e2.OnOpen = () => { n2++; return true; };
|
||||
c2.RelockWaitSec = 1;
|
||||
c2.Start(out _);
|
||||
e2.Run(200_000, () => c2.Looted >= 20 || !c2.Running);
|
||||
Check.True(c2.Running && c2.Looted >= 20, $"no {ChestKeyLooter.MaxStarvedChests} in a row: it keeps going ({c2.Looted})");
|
||||
c2.Stop();
|
||||
}
|
||||
|
||||
/// <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)
|
||||
private static long NextKeyAfterOpen(int relockSec, Action<ChestEnv, ChestKeyLooter>? duringWait = null, bool? shownOpen = null)
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.ShownOpen = shownOpen;
|
||||
env.Keys.Clear(); env.Keys.Add(11); env.Keys.Add(12);
|
||||
Serve(env, ck);
|
||||
env.AutoLootMs = 1000;
|
||||
|
|
@ -482,10 +638,10 @@ internal static class ItemToolTests
|
|||
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 = 0;
|
||||
Check.Eq(c0.RelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "0 s is raised to the least, 1 s");
|
||||
c0.RelockWaitSec = -40;
|
||||
Check.Eq(c0.RelockWaitSec, 5, "a negative value too");
|
||||
Check.Eq(c0.RelockWaitSec, 1, "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");
|
||||
|
|
@ -497,8 +653,15 @@ internal static class ItemToolTests
|
|||
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)");
|
||||
// 1 s: the loot (1 s here) ends after that; with no close seen the old 2 s after the loot holds.
|
||||
at = NextKeyAfterOpen(1);
|
||||
Check.True(at >= 5_000, $"1 s is used as 5 s ({at} ms)");
|
||||
Check.True(at >= 1_000 + ChestKeyLooter.AfterLootMaxMs && at < 1_000 + ChestKeyLooter.AfterLootMaxMs + 1_500, $"1 s, close not seen: ~2 s after the loot ({at} ms)");
|
||||
// ... and with the close seen (the client shows the chest shut at once), CloseSettleMs after it.
|
||||
at = NextKeyAfterOpen(1, (env, _) => { }, shownOpen: false);
|
||||
Check.True(at >= 1_000 + ChestKeyLooter.CloseSettleMs && at < 1_000 + ChestKeyLooter.CloseSettleMs + 1_000, $"1 s, close seen: ~{ChestKeyLooter.CloseSettleMs} ms after the loot ({at} ms)");
|
||||
// A close that isn't seen in time: AfterLootMaxMs still ends the wait.
|
||||
at = NextKeyAfterOpen(1, (env, _) => { }, shownOpen: true);
|
||||
Check.True(at >= 1_000 + ChestKeyLooter.AfterLootMaxMs && at < 1_000 + ChestKeyLooter.AfterLootMaxMs + 1_500, $"1 s, the client still shows it open: ~2 s after the loot ({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; });
|
||||
|
|
@ -509,7 +672,7 @@ internal static class ItemToolTests
|
|||
|
||||
private static void ChestRelockProbes()
|
||||
{
|
||||
foreach (int sec in new[] { 20, 5, ChestKeyLooter.DefaultRelockWaitSec })
|
||||
foreach (int sec in new[] { 20, 5, 1, ChestKeyLooter.DefaultRelockWaitSec })
|
||||
{
|
||||
var env = NewChest(out var ck);
|
||||
env.Unlimited = true;
|
||||
|
|
@ -529,7 +692,7 @@ internal static class ItemToolTests
|
|||
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.True(keyAt.Skip(1).Zip(keyAt.Skip(2), (a, b) => b - a).All(d => d >= ChestKeyLooter.MinProbeMs), $"{sec} s: never two asks 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));
|
||||
}
|
||||
|
|
@ -582,12 +745,15 @@ internal static class ItemToolTests
|
|||
left = Items.Contains(itemId) ? (Counts.TryGetValue(itemId, out int c) ? c : 1) : 0;
|
||||
return !Items.Contains(itemId) || left < count;
|
||||
}
|
||||
public bool Send(int itemId, int targetId)
|
||||
public readonly List<int> Amounts = new(); // each give's amount (0 = the whole object)
|
||||
public int PendingAmount;
|
||||
public bool Send(int itemId, int targetId, int amount)
|
||||
{
|
||||
Sent.Add((T, itemId));
|
||||
Amounts.Add(amount);
|
||||
if (Silent) return true;
|
||||
if (Refuses.Contains(itemId)) { Refusals++; return true; }
|
||||
PendingLand = itemId; LandAt = T + LandMs;
|
||||
PendingLand = itemId; PendingAmount = amount; LandAt = T + LandMs;
|
||||
return true;
|
||||
}
|
||||
public int RefusalSeq() => Refusals;
|
||||
|
|
@ -602,7 +768,9 @@ internal static class ItemToolTests
|
|||
T += 50;
|
||||
if (PendingLand != 0 && T >= LandAt)
|
||||
{
|
||||
if (TakesOneAtATime && Counts.TryGetValue(PendingLand, out int c) && c > 1) Counts[PendingLand] = c - 1;
|
||||
int have = Counts.TryGetValue(PendingLand, out int c) ? c : 1;
|
||||
int take = TakesOneAtATime ? 1 : PendingAmount > 0 ? PendingAmount : have; // a split give takes its amount
|
||||
if (take < have) Counts[PendingLand] = have - take;
|
||||
else Items.Remove(PendingLand);
|
||||
PendingLand = 0;
|
||||
}
|
||||
|
|
@ -712,6 +880,131 @@ internal static class ItemToolTests
|
|||
Check.False(q2.Running, "Stop always works");
|
||||
}
|
||||
|
||||
// ── Amount and Every (2026-11-27; spotted by SilentKelpie, Forgejo rynth PR #12) ──
|
||||
|
||||
private static void GiveAmountSplits()
|
||||
{
|
||||
var env = NewGive(out var qg);
|
||||
env.Items.Clear(); env.Items.AddRange(new[] { 1, 2 });
|
||||
env.Counts[1] = 3; env.Counts[2] = 50;
|
||||
qg.SetAmount(20);
|
||||
Check.True(qg.Start(out _), "starts");
|
||||
Check.True(env.Said[0].Contains("20 of 'Mana Mote'"), "the start line says the amount: " + env.Said[0]);
|
||||
env.Run(30_000, () => !qg.Running);
|
||||
Check.Eq(string.Join(",", env.Sent.Select(s => s.Item)), "1,2", "the small stack whole, then the big one");
|
||||
Check.Eq(string.Join(",", env.Amounts), "0,17", "the 3-stack goes whole (amount 0); 17 split off the 50");
|
||||
Check.Eq(qg.Units, 20, "20 units in all");
|
||||
Check.Eq(env.Counts[2], 33, "33 stay in the pack");
|
||||
Check.True(env.Said.Last().Contains("gave 20"), "the round ends at the amount: " + env.Said.Last());
|
||||
Check.False(qg.Running, "one round (Every 0): done");
|
||||
|
||||
// Amount 0 is the old behaviour: every unit.
|
||||
var e2 = NewGive(out var q2);
|
||||
e2.Counts[2] = 5;
|
||||
q2.Start(out _);
|
||||
e2.Run(30_000, () => !q2.Running);
|
||||
Check.Eq(q2.Units, 7, "Amount 0: everything (1 + 5 + 1)");
|
||||
Check.True(e2.Amounts.All(a => a == 0), "whole objects only");
|
||||
|
||||
Check.Eq(new QuickGive(new GiveEnv()).Amount, 0, "Amount starts at 0 (all)");
|
||||
q2.SetAmount(-5); Check.Eq(q2.Amount, 0, "clamped at 0");
|
||||
q2.SetAmount(int.MaxValue); Check.Eq(q2.Amount, QuickGive.MaxAmount, "clamped at the most");
|
||||
}
|
||||
|
||||
private static void GiveAmountOnePerGive()
|
||||
{
|
||||
var env = NewGive(out var qg);
|
||||
env.Items.Clear(); env.Items.Add(1);
|
||||
env.Counts[1] = 10;
|
||||
env.TakesOneAtATime = true;
|
||||
qg.SetAmount(3);
|
||||
qg.Start(out _);
|
||||
env.Run(60_000, () => !qg.Running);
|
||||
Check.Eq(qg.Units, 3, "three units, one a give");
|
||||
Check.Eq(env.Counts[1], 7, "seven left in the pack");
|
||||
Check.Eq(env.Sent.Count, 3, "three gives");
|
||||
}
|
||||
|
||||
private static void GiveEveryRounds()
|
||||
{
|
||||
var env = NewGive(out var qg);
|
||||
env.Items.Clear(); env.Items.Add(1);
|
||||
env.Counts[1] = 10;
|
||||
qg.SetAmount(2);
|
||||
qg.SetEvery(30);
|
||||
qg.Start(out _);
|
||||
Check.True(env.Said[0].Contains("every 30 s until you stop it"), "the start line says it repeats: " + env.Said[0]);
|
||||
env.Run(5_000);
|
||||
Check.Eq(qg.Units, 2, "round 1: 2 units");
|
||||
Check.Eq(qg.State, QuickGive.Phase.Waiting, "then waits");
|
||||
Check.True(qg.Status.Contains("next round in"), "the status counts down: " + qg.Status);
|
||||
Check.True(qg.NextRoundInMs > 20_000, "about 30 s to go");
|
||||
env.Run(30_000);
|
||||
Check.Eq(qg.Units, 4, "round 2 after the interval");
|
||||
Check.Eq(qg.Rounds, 2, "two rounds");
|
||||
|
||||
// Between rounds: out of range holds the next one, it goes when the target is back.
|
||||
env.Meters = 12;
|
||||
env.Run(40_000);
|
||||
Check.Eq(qg.Units, 4, "target 12 m away: no round");
|
||||
Check.True(qg.Running, "still running");
|
||||
Check.True(qg.Status.Contains("then waits"), "the status says why: " + qg.Status);
|
||||
env.Meters = 2;
|
||||
env.Run(3_000);
|
||||
Check.Eq(qg.Units, 6, "back in range: the round goes");
|
||||
|
||||
// A fight holds it too.
|
||||
env.Combat = true;
|
||||
env.Run(40_000);
|
||||
Check.Eq(qg.Units, 6, "in a fight: no round");
|
||||
env.Combat = false;
|
||||
env.Run(3_000);
|
||||
Check.Eq(qg.Units, 8, "after the fight: the round goes");
|
||||
|
||||
// None left: the run waits for more.
|
||||
env.Items.Clear();
|
||||
env.Run(40_000);
|
||||
Check.True(qg.Running, "none left: still running, waiting for more");
|
||||
Check.True(qg.Status.Contains("no 'Mana Mote' in your packs"), "says so: " + qg.Status);
|
||||
env.Items.Add(5); env.Counts[5] = 4;
|
||||
env.Run(3_000);
|
||||
Check.Eq(qg.Units, 10, "new ones go in the next round");
|
||||
|
||||
qg.Stop("stopped by you");
|
||||
Check.False(qg.Running, "Stop ends it");
|
||||
Check.True(env.Said.Last().Contains("rounds"), "the result counts the rounds: " + env.Said.Last());
|
||||
|
||||
// Every with nothing carried still starts (the first round waits).
|
||||
var e2 = NewGive(out var q2);
|
||||
e2.Items.Clear();
|
||||
q2.SetEvery(10);
|
||||
Check.True(q2.Start(out _), "Every set: starts with none carried");
|
||||
q2.SetEvery(0);
|
||||
var e3 = NewGive(out var q3);
|
||||
e3.Items.Clear();
|
||||
Check.False(q3.Start(out _), "Every 0: refused with none carried, as before");
|
||||
}
|
||||
|
||||
private static void GiveEveryMidRound()
|
||||
{
|
||||
void Case(string name, Action<GiveEnv> change, bool runEnds)
|
||||
{
|
||||
var env = NewGive(out var qg);
|
||||
env.Items.Clear(); env.Items.AddRange(Enumerable.Range(1, 30));
|
||||
qg.SetEvery(20);
|
||||
qg.Start(out _);
|
||||
env.Run(600);
|
||||
change(env);
|
||||
env.Run(5000);
|
||||
Check.Eq(qg.Running, !runEnds, $"{name}: {(runEnds ? "the run ends" : "the run goes on")}");
|
||||
if (!runEnds) Check.Eq(qg.State, QuickGive.Phase.Waiting, $"{name}: the round ended, the next is due");
|
||||
}
|
||||
Case("fight", e => e.Combat = true, runEnds: false);
|
||||
Case("vanishes", e => e.Loaded = false, runEnds: false);
|
||||
Case("moves away", e => e.Meters = 30, runEnds: false);
|
||||
Case("renamed", e => e.TargetName = "Somebody Else", runEnds: true);
|
||||
}
|
||||
|
||||
private static void GiveStartRefusals()
|
||||
{
|
||||
var env = NewGive(out var qg);
|
||||
|
|
@ -819,7 +1112,7 @@ internal static class ItemToolTests
|
|||
}
|
||||
|
||||
/// <summary>The player types / presses: a trusted command.</summary>
|
||||
public void Cmd(string args) => P.QueueItemToolCommand(args, trusted: true);
|
||||
public void Cmd(string args, bool trusted = true) => P.QueueItemToolCommand(args, trusted);
|
||||
}
|
||||
|
||||
private static string ProfilePath(string name)
|
||||
|
|
@ -882,6 +1175,49 @@ internal static class ItemToolTests
|
|||
|
||||
private static string Chat() => string.Join(" | ", FakeHost.Chat);
|
||||
|
||||
private const uint SidePack = 0x80290200, JunkBase = 0x80291000, SideJunkBase = 0x80292000;
|
||||
|
||||
/// <summary>The chest looter's room check with the main pack full and <paramref name="sideUsed"/> of a 24-slot side pack's slots used.</summary>
|
||||
private static string? NoRoomWithFullMain(int sideUsed, bool mainFull = true)
|
||||
{
|
||||
BaseWorld();
|
||||
FakeHost.Names[SidePack] = "Backpack";
|
||||
FakeHost.ItemTypes[SidePack] = 0x200;
|
||||
FakeHost.Ints[(SidePack, 6u)] = 24; // ItemsCapacity
|
||||
FakeHost.Containers[SidePack] = Player;
|
||||
var ids = new List<uint> { Chest, Key, Key2, Gem, SidePack };
|
||||
for (uint i = 0; i < (mainFull ? 102u : 50u); i++)
|
||||
{
|
||||
uint j = JunkBase + i;
|
||||
FakeHost.Names[j] = $"Junk {i}"; FakeHost.ItemTypes[j] = 0x80; FakeHost.Containers[j] = Player;
|
||||
ids.Add(j);
|
||||
}
|
||||
for (uint i = 0; i < sideUsed; i++)
|
||||
{
|
||||
uint j = SideJunkBase + i;
|
||||
FakeHost.Names[j] = $"Side junk {i}"; FakeHost.ItemTypes[j] = 0x80; FakeHost.Containers[j] = SidePack;
|
||||
ids.Add(j);
|
||||
}
|
||||
var bot = new Bot(FakeHost.Create(Player), ProfilePath("itemtool-chest.json"), ids.ToArray());
|
||||
bot.Cache.GetDirectInventory(forceRefresh: true);
|
||||
bot.Call("EnsureItemTool");
|
||||
var env = (IChestKeyEnv)typeof(ChestKeyLooter).GetField("_env", Any)!.GetValue(bot.Get<ChestKeyLooter>("_chestKey"))!;
|
||||
return env.NoRoomReason();
|
||||
}
|
||||
|
||||
// 2026-11-28: looting stopped with a full main pack although the side packs had room; it should
|
||||
// fill the side packs (the looter makes room since e026c97c).
|
||||
private static void PluginNoRoomOnlyWhenAllFull()
|
||||
{
|
||||
Check.Eq(NoRoomWithFullMain(0, mainFull: false), null, "room in the main pack: keys go");
|
||||
Check.Eq(NoRoomWithFullMain(0), null, "main pack full, an empty side pack: keys go (the looter moves one item to the side pack, then picks up)");
|
||||
Check.Eq(NoRoomWithFullMain(22), null, "2 side slots left: still goes");
|
||||
string? one = NoRoomWithFullMain(23);
|
||||
Check.True(one != null && one.Contains("1 free slot(s) left in all your packs"), "1 slot left in all: held (looting keeps 2 for weapon swaps): " + one);
|
||||
string? none = NoRoomWithFullMain(24);
|
||||
Check.True(none != null && none.Contains("0 free slot(s)"), "every pack full: held: " + none);
|
||||
}
|
||||
|
||||
private static void PluginChestRun()
|
||||
{
|
||||
BaseWorld();
|
||||
|
|
@ -1064,6 +1400,43 @@ internal static class ItemToolTests
|
|||
|
||||
// ── Chest re-lock wait (the setting) ─────────────────────────────────────
|
||||
|
||||
private static void PluginGiveAmountEvery()
|
||||
{
|
||||
BaseWorld();
|
||||
var bot = MakeBot("itemtool-giveamount.json");
|
||||
string Run(string words, bool trusted = true)
|
||||
{
|
||||
FakeHost.Chat.Clear();
|
||||
bot.Cmd(words, trusted);
|
||||
bot.Tick();
|
||||
return Chat();
|
||||
}
|
||||
string said = Run("giveamount 20");
|
||||
var qg = bot.Get<QuickGive>("_quickGive");
|
||||
Check.Eq(qg.Amount, 20, "giveamount 20");
|
||||
Check.True(said.Contains("gives 20 a round"), "answers: " + said);
|
||||
said = Run("giveevery 45");
|
||||
Check.Eq(qg.EverySec, 45, "giveevery 45");
|
||||
Check.True(said.Contains("a round every 45 s"), "answers: " + said);
|
||||
said = Run("giveamount");
|
||||
Check.True(said.Contains("Amount") && said.Contains("is 20"), "no number: says the value: " + said);
|
||||
said = Run("giveevery soon");
|
||||
Check.Eq(qg.EverySec, 45, "not a number: unchanged");
|
||||
Check.True(said.Contains("'soon' isn't a number"), "says why: " + said);
|
||||
said = Run("giveevery 999999");
|
||||
Check.Eq(qg.EverySec, QuickGive.MaxEverySec, "clamped to the most");
|
||||
Check.True(said.Contains("past the most"), "says it was clamped: " + said);
|
||||
said = Run("giveamount 0", trusted: false);
|
||||
Check.Eq(qg.Amount, 0, "a meta may set them (they only shape a give)");
|
||||
Check.True(said.Contains("every matching item"), "answers: " + said);
|
||||
Run("giveevery 0");
|
||||
|
||||
string json = bot.P.BuildItemToolJson();
|
||||
Check.True(json.Contains("\"amount\":0") && json.Contains("\"everySec\":0") && json.Contains("\"amountMax\":" + QuickGive.MaxAmount)
|
||||
&& json.Contains("\"everyMax\":" + QuickGive.MaxEverySec) && json.Contains("\"rounds\":0") && json.Contains("\"nextInSec\":0"),
|
||||
"the Item Tool panel's data carries Amount and Every: " + json);
|
||||
}
|
||||
|
||||
private static void PluginRelockCommand()
|
||||
{
|
||||
BaseWorld();
|
||||
|
|
@ -1083,9 +1456,11 @@ internal static class ItemToolTests
|
|||
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 0");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "0 s is raised to 1 s");
|
||||
Check.True(said.Contains("re-lock wait = 1 s") && said.Contains("the least is 1 s"), "says it was clamped: " + said);
|
||||
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);
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, 2, "2 s is kept (the least was 5 s until 2026-11-28)");
|
||||
|
||||
said = Run("chest relock 9999");
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, ChestKeyLooter.MaxRelockWaitSec, "'chest relock' works too; 9999 is cut to 600");
|
||||
|
|
@ -1099,13 +1474,25 @@ internal static class ItemToolTests
|
|||
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.True(said.Contains("re-lock wait = 45 s") && said.Contains("1-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.
|
||||
// The panel reads it (the engine's slider takes its least from relockMin, never under 1).
|
||||
string json = bot.P.BuildItemToolJson();
|
||||
Check.True(json.Contains("\"relockSec\":45") && json.Contains("\"relockMin\":5") && json.Contains("\"relockMax\":600") && json.Contains("\"relockReady\":true"),
|
||||
Check.True(json.Contains("\"relockSec\":45") && json.Contains("\"relockMin\":1") && json.Contains("\"relockMax\":600") && json.Contains("\"relockReady\":true"),
|
||||
"the Item Tool panel's data carries the setting: " + json);
|
||||
Check.True(json.Contains("\"relockSeen\":false"), "no run has seen a re-lock");
|
||||
|
||||
// A running looter that saw the chest re-lock as it closes: the panel's wait control goes
|
||||
// (relockSec 0 hides it), the setting itself is kept.
|
||||
var ck = bot.Get<ChestKeyLooter>("_chestKey");
|
||||
typeof(ChestKeyLooter).GetField("<State>k__BackingField", Any)!.SetValue(ck, ChestKeyLooter.Phase.Waiting);
|
||||
typeof(ChestKeyLooter).GetField("<RelockSeen>k__BackingField", Any)!.SetValue(ck, true);
|
||||
json = bot.P.BuildItemToolJson();
|
||||
Check.True(json.Contains("\"relockSec\":0,") && json.Contains("\"relockSeen\":true"), "re-lock seen while running: the control is hidden: " + json);
|
||||
Check.Eq(bot.S.ChestRelockWaitSec, 45, "the setting is unchanged");
|
||||
typeof(ChestKeyLooter).GetField("<State>k__BackingField", Any)!.SetValue(ck, ChestKeyLooter.Phase.Idle);
|
||||
Check.True(bot.P.BuildItemToolJson().Contains("\"relockSec\":45"), "stopped: the control is back");
|
||||
|
||||
// The wait the running looter uses is the setting's (the tick hands it over).
|
||||
bot.S.ChestRelockWaitSec = 77;
|
||||
|
|
@ -1141,7 +1528,7 @@ internal static class ItemToolTests
|
|||
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");
|
||||
Check.Eq(dst.ChestRelockWaitSec, ChestKeyLooter.MinRelockWaitSec, "a hand-edited 0 loads as 1 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);
|
||||
|
|
|
|||
|
|
@ -47,6 +47,8 @@ internal static class LootCorpseTests
|
|||
r.Add("loot chain: 'My Kills Only' loots your kill and skips another player's", OwnershipModes);
|
||||
r.Add("loot chain: an item the cache never saw created is found in the corpse's contents and looted", UnseenItemRescued);
|
||||
r.Add("loot chain: without GetContainerContents an unseen item stays unseen (no crash)", UnseenItemOldEngine);
|
||||
r.Add("loot chain: an item the client lists but can't read yet holds the finish, and is looted once it reads", UnreadItemHoldsFinish);
|
||||
r.Add("loot chain: an item that never reads holds the finish only UnreadContentsWaitMs", UnreadItemHoldIsCapped);
|
||||
r.Add("loot starvation: a corpse waiting behind far-off combat gets a turn, a close monster keeps combat", LootStarvation);
|
||||
r.Add("loot starvation (R-20261115-165857-1de7): a starved open waits for combat's first attack at a fresh lock, at most 3 s", StarvedOpenWaitsForFirstAttack);
|
||||
r.Add("loot logging: a corpse held by combat is logged once, with the reason", HeldByCombatLoggedOnce);
|
||||
|
|
@ -295,6 +297,63 @@ internal static class LootCorpseTests
|
|||
Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the unseen gem is looted");
|
||||
}
|
||||
|
||||
// A corpse finished 130 ms after it opened, from the items the cache already had: the second item the
|
||||
// client listed in it couldn't be read yet, so it was never judged and was left behind.
|
||||
private static Bot CorpseWithUnreadItem()
|
||||
{
|
||||
BaseWorld(corpsePositioned: true);
|
||||
FakeHost.ContentsCalls = true;
|
||||
FakeHost.Ints[(Gem, 11)] = 100; FakeHost.Ints[(Gem, 12)] = 1;
|
||||
FakeHost.Containers[Gem2] = Corpse; // listed in the corpse, no name or position yet
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bot.S.LootCorpseTimeoutMs = 60_000;
|
||||
bot.Cache.OnCreateObject(Corpse);
|
||||
bot.Cache.Tick();
|
||||
bot.Tick(BotActivity.Looting);
|
||||
bot.Cache.OnCreateObject(Gem); // the cache has the first gem only
|
||||
bot.Cache.Tick();
|
||||
FakeHost.GroundContainer = Corpse;
|
||||
bot.P.OnViewObjectContents(Corpse);
|
||||
return bot;
|
||||
}
|
||||
|
||||
private static bool CorpseFinished(Bot bot) =>
|
||||
bot.Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
|
||||
|
||||
private static void UnreadItemHoldsFinish()
|
||||
{
|
||||
var bot = CorpseWithUnreadItem();
|
||||
LootWithMerges(bot, 2000, wantMoves: 99); // past the empty-corpse wait, short of the hold's cap
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem), "the gem the cache had is looted");
|
||||
Check.False(CorpseFinished(bot), "not finished while the client lists an item that can't be read");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("can't be read yet")), "the hold is logged");
|
||||
|
||||
FakeHost.Names[Gem2] = "Black Opal";
|
||||
FakeHost.ItemTypes[Gem2] = ItemTypeGem;
|
||||
FakeHost.Appraised.Add(Gem2);
|
||||
FakeHost.Ints[(Gem2, 11)] = 100; FakeHost.Ints[(Gem2, 12)] = 1;
|
||||
LootWithMerges(bot, 3000, wantMoves: 2);
|
||||
Check.True(FakeHost.ExternalMoves.Any(m => m.Id == Gem2), "once it reads, it is found and looted");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("the object cache had missed") && l.Contains($"0x{Gem2:X8}")), "the rescue names it");
|
||||
}
|
||||
|
||||
private static void UnreadItemHoldIsCapped()
|
||||
{
|
||||
var bot = CorpseWithUnreadItem();
|
||||
long start = Environment.TickCount64;
|
||||
while (!CorpseFinished(bot) && Environment.TickCount64 - start < 6000)
|
||||
{
|
||||
foreach (var m in FakeHost.ExternalMoves) FakeHost.Containers[m.Id] = 0;
|
||||
bot.Tick(BotActivity.Looting);
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
long took = Environment.TickCount64 - start;
|
||||
long cap = RynthAiPlugin.UnreadContentsWaitMs;
|
||||
Check.True(CorpseFinished(bot), "the corpse is finished in the end");
|
||||
Check.True(took >= cap - 200 && took < cap + 2000, $"after about {cap} ms (took {took} ms)");
|
||||
}
|
||||
|
||||
private static void UnseenItemOldEngine()
|
||||
{
|
||||
BaseWorld(corpsePositioned: true);
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ internal static class LootRetryTimingTests
|
|||
r.Add("loot retry (R-20261029-122319-321f): a full main pack's refusals after the pickup count as tries (no free resends); a second item refused there keeps it marked full; nothing goes to a side pack", FullMainPackRefusals);
|
||||
r.Add("loot retry (R-20261029-122319-321f): unanswered moves are retried only after the answer wait, three tries, then given up (no side-pack round); their pack marks end with the item, the next item starts fresh", UnansweredMovesDontPoison);
|
||||
r.Add("loot pickup, main pack full (2026-11-12 'You must first pick up the Silver Pea'): a pea joins the stack you carry, a gem is left at once with one chat line, nothing is aimed at a side pack, the corpse completes", FullMainPackPeaJoinsGemLeft);
|
||||
r.Add("loot pickup, main pack full, a side pack with room (2026-11-28): one main-pack item moves to the side pack per pickup (loot it brought in first), the pickup waits for that move's answer, every gem lands in the main pack, nothing is left", FullMainPackMakesRoom);
|
||||
r.Add("loot retry (R-20261029-122319-321f): an item that lands late, after its pack was given up on, un-marks that pack", LateLandingUnmarks);
|
||||
r.Add("loot retry (R-20261029-122319-321f): a refusal on arrival is 'too busy' (free resend), one after the pickup is the pack's answer", RefusalTiming);
|
||||
r.Add("loot retry (R-20261029-122319-321f): the answer wait grows with the server's measured answers, within 4-8 s", AnswerWaitAdapts);
|
||||
|
|
@ -114,6 +115,7 @@ internal static class LootRetryTimingTests
|
|||
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
public readonly RynthCoreHost Host;
|
||||
public SlowAce? Sim;
|
||||
public BotActivity Activity = BotActivity.Looting; // what the arbiter gave the tick
|
||||
|
||||
|
|
@ -124,6 +126,7 @@ internal static class LootRetryTimingTests
|
|||
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);
|
||||
Host = host;
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
|
|
@ -200,6 +203,9 @@ internal static class LootRetryTimingTests
|
|||
public long ClientPendingTimeoutMs = 10_000;
|
||||
public int TooBusy, LocalRefused, Queued, RoomRefusals;
|
||||
public readonly List<(uint Id, uint Pack, long At)> Landed = new();
|
||||
/// <summary>Pack-to-pack moves (MoveItemInternal) the server carried out: they take the client's one pending request too.</summary>
|
||||
public readonly List<(uint Id, uint Pack, long At)> PackMoves = new();
|
||||
private int _seenPackMoves;
|
||||
|
||||
private enum St { Idle, Pickup, Return }
|
||||
private St _st;
|
||||
|
|
@ -231,6 +237,24 @@ internal static class LootRetryTimingTests
|
|||
if (Lag.Remove(m.Id, out long lag)) arrive += lag;
|
||||
At(arrive, () => Receive(m.Id, m.Target, arrive));
|
||||
}
|
||||
while (_seenPackMoves < FakeHost.Moves.Count)
|
||||
{
|
||||
var m = FakeHost.Moves[_seenPackMoves++];
|
||||
if (_clientPending != 0 && now - _clientPendingAt >= ClientPendingTimeoutMs) _clientPending = 0;
|
||||
if (_clientPending != 0) { LocalRefused++; continue; }
|
||||
_clientPending = m.Id;
|
||||
_clientPendingAt = now;
|
||||
long done = now - TickMs + Rtt;
|
||||
At(done, () =>
|
||||
{
|
||||
uint from = FakeHost.Containers.TryGetValue(m.Id, out uint c) ? c : 0;
|
||||
FakeHost.Containers[m.Id] = m.Pack;
|
||||
if (Room.TryGetValue(from, out int freeFrom)) Room[from] = freeFrom + 1;
|
||||
if (Room.TryGetValue(m.Pack, out int freeTo)) Room[m.Pack] = freeTo - 1;
|
||||
PackMoves.Add((m.Id, m.Pack, done));
|
||||
Answered(m.Id);
|
||||
});
|
||||
}
|
||||
while (true)
|
||||
{
|
||||
var due = _events.Where(e => e.At <= now).OrderBy(e => e.At).ThenBy(e => e.Seq).ToList();
|
||||
|
|
@ -483,6 +507,59 @@ internal static class LootRetryTimingTests
|
|||
Check.True(_now - started < 10_000, $"quickly ({_now - started} ms), not after 3 + 3 tries per item");
|
||||
});
|
||||
|
||||
// ── 3c. A full main pack, room in a side pack (2026-11-28) ────────────────
|
||||
// "Why does Rynth stop looting when the main pack is full? It should continue looting and fill the
|
||||
// side packs." Since 3b every item that joined no stack was left once the main pack was full, side
|
||||
// packs empty or not. Now the looter first moves one loose item from the main pack to the side pack
|
||||
// (a pack-to-pack move, which the client sends), waits for its answer (the client refuses a pickup
|
||||
// while it is out), then picks the item up into the freed slot. 3b runs with no inventory manager,
|
||||
// so it still shows what happens when no room move can be made.
|
||||
|
||||
private static void FullMainPackMakesRoom() => Clocked(() =>
|
||||
{
|
||||
const uint G1 = 0x80263181, G2 = 0x80263182, G3 = 0x80263183, JunkBase = 0x80264100;
|
||||
World(sidePack: true, G1, G2, G3);
|
||||
var ids = new List<uint> { G1, G2, G3 };
|
||||
for (uint i = 0; i < 102; i++) // a full main pack
|
||||
{
|
||||
uint j = JunkBase + i;
|
||||
FakeHost.Names[j] = $"Junk {i}";
|
||||
FakeHost.ItemTypes[j] = 0x80;
|
||||
FakeHost.Containers[j] = Player;
|
||||
ids.Add(j);
|
||||
}
|
||||
var oldClock = RynthClock.TestNow;
|
||||
var t0 = new DateTime(2026, 11, 28, 12, 0, 0);
|
||||
RynthClock.TestNow = () => t0.AddMilliseconds(_now);
|
||||
try
|
||||
{
|
||||
var sim = new SlowAce();
|
||||
sim.Room[Player] = 0; // the server's main pack is full too
|
||||
var bot = Open(sim, sidePack: true, ids.ToArray());
|
||||
bot.Set("_inventoryManager", new RynthCore.Plugin.RynthAi.Loot.InventoryManager(bot.Host, bot.S, bot.Cache));
|
||||
|
||||
long started = _now;
|
||||
Run(bot, () => bot.Completed, 60_000);
|
||||
|
||||
foreach (uint g in new[] { G1, G2, G3 })
|
||||
Check.True(sim.Landed.Any(l => l.Id == g && l.Pack == Player), $"0x{g:X8} is looted into the main pack");
|
||||
Check.True(FakeHost.ExternalMoves.All(m => m.Target == Player), "every pickup is aimed at the main pack");
|
||||
Check.Eq(FakeHost.Moves.Count, 3, "one room move per gem");
|
||||
Check.True(FakeHost.Moves.All(m => m.Pack == SidePack), "each into the side pack");
|
||||
Check.Eq(sim.PackMoves.Count, 3, "and the server carries each out");
|
||||
Check.Eq(FakeHost.Moves[0].Id, JunkBase + 101, "the first room move takes the newest loose item (nothing looted yet)");
|
||||
Check.Eq(FakeHost.Moves[1].Id, sim.Landed[0].Id, "the next takes the loot just brought in");
|
||||
Check.Eq(sim.LocalRefused, 0, "no pickup goes out while a room move has no answer");
|
||||
Check.Eq(sim.RoomRefusals, 0, "and the server refuses none for room");
|
||||
Check.False(Logged("leaving 'Gem"), "nothing is left on the corpse");
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("Main pack full")), 0, "no main-pack-full chat line");
|
||||
Check.True(Logged("the main pack is full: moving"), "the log says why each room move went");
|
||||
Check.True(bot.Completed, "the corpse completes");
|
||||
Check.True(_now - started < 20_000, $"in good time ({_now - started} ms)");
|
||||
}
|
||||
finally { RynthClock.TestNow = oldClock; }
|
||||
});
|
||||
|
||||
// ── 4. A late landing ─────────────────────────────────────────────────────
|
||||
|
||||
private static void LateLandingUnmarks() => Clocked(() =>
|
||||
|
|
|
|||
|
|
@ -34,10 +34,36 @@ internal static class LootRuleMatchTests
|
|||
r.Add("loot rule match: double keys compare as floats (1.20 + 0.09 >= 1.29)", FloatCompare);
|
||||
r.Add("loot rule match: tinked damage and tinked target melee (VTank's worked examples)", TinkedNodes);
|
||||
r.Add("loot rule match: which conditions need the ID", ConditionsNeedingId);
|
||||
r.Add("loot rule match: ImbuedEffect tests see ImbuedEffect2-5 (303-306) too", ImbuesInLaterSlots);
|
||||
r.Add("loot rule match: Decide passes over a rule a known condition fails, in any order", DecideOrder);
|
||||
r.Add("loot rule match (R-20261101-133624-7eeb): a name rule 'Trade Note' first keeps none of a corpse's plain items, ID or not", TradeNoteRuleFirst);
|
||||
r.Add("loot rule match: /ra loot why lists the rules above that came close, with the value read", LootWhyExplains);
|
||||
r.Add("loot rule match: /ra loot why's words, in chat and in the 'Why this loot rule?' window", LootWhyReportWords);
|
||||
r.Add("loot rule match: Slayer damage bonus (float 138) reads the weapon's text when the server sent none; a sent value wins", SlayerBonusFromText);
|
||||
}
|
||||
|
||||
// 2026-11-27 (spotted by SilentKelpie, Forgejo rynth PR #12): ACE never sends float 138; servers built on
|
||||
// ACECustom write "- Shadow Slayer: 1.5x Damage" in the weapon's text.
|
||||
private static void SlayerBonusFromText()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
var rule = new VTankLootRule { Name = "Slayer weapons", Action = VTankLootAction.Keep, CustomExpression = string.Empty };
|
||||
rule.Conditions.Add(new VTankLootCondition(N.ObjectClass, "0", new[] { ((int)AcObjectClass.MeleeWeapon).ToString() }));
|
||||
rule.Conditions.Add(new VTankLootCondition(N.DoubleValKeyGE, "0", new[] { "1.01", "138" }));
|
||||
var profile = new VTankLootProfile { FileVersion = 1, Rules = { rule } };
|
||||
var ctx = Ctx();
|
||||
bool Keeps(Item i) => VTankLootEvaluator.FirstMatch(profile, i, ctx, out _) != null;
|
||||
|
||||
var desc = new Item("Shadow Slayer Sword", AcObjectClass.MeleeWeapon).Int(166, 22).Str(16, "Property Details:\n- Shadow Slayer: 1.5x Damage");
|
||||
Check.True(Keeps(desc), "the bonus from the description: kept");
|
||||
Check.Near(desc.Wo.Values((DoubleValueKey)138, 0.0), 1.5, 1e-9, "the item reader gives 1.5");
|
||||
var use = new Item("Olthoi Slayer Axe", AcObjectClass.MeleeWeapon).Int(166, 1).Str(14, "Olthoi Slayer: 2x Damage");
|
||||
Check.True(Keeps(use), "the bonus from the use text: kept");
|
||||
var sent = new Item("Sent Bonus Mace", AcObjectClass.MeleeWeapon).Dbl(138, 1.0).Str(16, "- Shadow Slayer: 1.5x Damage");
|
||||
Check.False(Keeps(sent), "a sent 1.0 wins over the text's 1.5: left");
|
||||
var none = new Item("Plain Sword", AcObjectClass.MeleeWeapon).Str(16, "A fine blade.");
|
||||
Check.False(Keeps(none), "no bonus anywhere: left");
|
||||
Check.Near(none.Wo.Values((DoubleValueKey)138, -1.0), -1.0, 1e-9, "no bonus: the caller's default");
|
||||
}
|
||||
|
||||
private static VTankLootProfile Excerpt()
|
||||
|
|
@ -204,6 +230,23 @@ internal static class LootRuleMatchTests
|
|||
Check.True(VTankLootEvaluator.Match(new VTankLootRule { Conditions = { C(N.CalcedBuffedTinkedTargetMeleeGE, "109", "1.17", "1.17") } }, mace), "an 80 mace at 1.17/1.17 reaches 109");
|
||||
}
|
||||
|
||||
// ACE keeps an item's second and later imbues in 303-306; a rule on 179 reads them all, ORed.
|
||||
private static void ImbuesInLaterSlots()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
|
||||
static VTankLootRule R(VTankLootCondition c) => new() { Conditions = { c } };
|
||||
var knife = new Item("Knife", AcObjectClass.MeleeWeapon).Int(179, 4).Int(303, 128);
|
||||
Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyFlagExists, "128", "179")), knife), "has Cold Rending: the rend in ImbuedEffect2 counts");
|
||||
Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyFlagExists, "4", "179")), knife), "has Armor Rending: the first slot still counts");
|
||||
Check.False(VTankLootEvaluator.Match(R(C(N.LongValKeyFlagExists, "512", "179")), knife), "no Fire Rending on it");
|
||||
Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyE, "132", "179")), knife), "179 = both imbues ORed");
|
||||
Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyE, "128", "303")), knife), "303 on its own reads as itself");
|
||||
var plain = new Item("Knife", AcObjectClass.MeleeWeapon).Int(353, 6);
|
||||
Check.False(VTankLootEvaluator.Match(R(C(N.LongValKeyGE, "1", "179")), plain), "an unimbued dagger has no imbue");
|
||||
Check.True(VTankLootEvaluator.Match(R(C(N.LongValKeyE, "6", "353")), plain), "353 is the weapon type (dagger)");
|
||||
}
|
||||
|
||||
private static void ConditionsNeedingId()
|
||||
{
|
||||
static VTankLootCondition C(int node, params string[] data) => new(node, "0", data);
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@ internal static class MeleeStallTests
|
|||
r.Add("ghost: a swing, a move, a server message or another target means it is alive", GhostAlive);
|
||||
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("ghost pack (R-20261127 bc02): silent monsters next to a ghost are skipped too, never removed; a heard-from or far one isn't", GhostPackSkipped);
|
||||
r.Add("ghost pack (R-20261127 bc02): a suspect is real again on an update or a move, tried again after 3 min", GhostSuspectClears);
|
||||
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);
|
||||
|
|
@ -236,6 +238,73 @@ internal static class MeleeStallTests
|
|||
Check.True(c.ScannedTargets.Any(t => (uint)t.Id == ghost), "scanned again");
|
||||
}
|
||||
|
||||
// ── Ghosts come in packs (R-20261127-183401-bc02) ─────────────────────────────────────────
|
||||
// Five Butcherous Eaters 11 m down behind a hill, all ghosts: each cost 10-30 s of arrows into
|
||||
// the hillside before it was caught. Now the silent ones next to a caught ghost go with it.
|
||||
private static void GhostPackSkipped()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
Place(Player, "Me", 96, 96, creature: false);
|
||||
FakeHost.PlayerPose = (Lb | 0x0329, 96f, 96f, 0f);
|
||||
uint ghost = 0xF08416EA, mate = 0xF043353B, mate2 = 0xF0841273, heard = 0xF0845E91, far = 0xF083C6E9;
|
||||
Place(ghost, "Butcherous Eater", 96, 130f);
|
||||
Place(mate, "Butcherous Eater", 99, 131f); // 3.2 m from it, silent 80 s
|
||||
Place(mate2, "Butcherous Eater", 90, 128f); // 6.3 m, silent 65 s
|
||||
Place(heard, "Butcherous Eater", 97, 133f); // 3.2 m, but the server spoke of it 5 s ago
|
||||
Place(far, "Butcherous Eater", 96, 150f); // 20 m off, silent
|
||||
var s = new LegacyUiSettings { MonsterRange = 60 };
|
||||
var host = FakeHost.Create();
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { ghost, mate, mate2, heard, far });
|
||||
var c = new CombatManager(host, s, cache);
|
||||
c.SetPlayerId(Player);
|
||||
c.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
|
||||
DateTime now = RynthCore.Plugin.RynthAi.RynthClock.Now;
|
||||
c.Ghosts.NoteServerUpdate((int)mate, now.AddSeconds(-80));
|
||||
c.Ghosts.NoteServerUpdate((int)mate2, now.AddSeconds(-65));
|
||||
c.Ghosts.NoteServerUpdate((int)heard, now.AddSeconds(-5));
|
||||
c.Ghosts.NoteServerUpdate((int)far, now.AddSeconds(-90));
|
||||
|
||||
c.MarkGhost((int)ghost, "Butcherous Eater", 65_000, "test");
|
||||
Check.True(c.Ghosts.IsGhost((int)mate) && c.Ghosts.IsSuspect((int)mate), "the silent one 3 m away: skipped as a suspect");
|
||||
Check.True(c.Ghosts.IsSuspect((int)mate2), "and the one 6 m away");
|
||||
Check.False(c.Ghosts.IsGhost((int)heard), "the server spoke of this one 5 s ago: not a suspect");
|
||||
Check.False(c.Ghosts.IsGhost((int)far), "20 m off: not part of the pack");
|
||||
Check.False(c.Ghosts.IsSuspect((int)ghost), "the caught one is a ghost, not a suspect");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("[Ghost] 2 more next to it") && l.Contains("0xF043353B") && l.Contains("not removed from the client")),
|
||||
"one line names the two");
|
||||
|
||||
Thread.Sleep(80);
|
||||
c.ScanNearbyTargets();
|
||||
Check.False(c.ScannedTargets.Any(t => (uint)t.Id == mate || (uint)t.Id == mate2), "suspects aren't scanned");
|
||||
Check.True(c.ScannedTargets.Any(t => (uint)t.Id == heard), "the heard-from one is");
|
||||
}
|
||||
|
||||
private static void GhostSuspectClears()
|
||||
{
|
||||
var g = new GhostTracker();
|
||||
const uint Lb = 0xF864;
|
||||
Check.True(g.MarkSuspect(5, "Butcherous Eater", Mob, Lb, T0), "marked");
|
||||
Check.False(g.MarkSuspect(5, "Butcherous Eater", Mob, Lb, T0), "once");
|
||||
g.NoteServerUpdate(5, T0.AddSeconds(10));
|
||||
Check.False(g.IsGhost(5), "a server update: real");
|
||||
|
||||
g.MarkSuspect(6, "Butcherous Eater", Mob, Lb, T0);
|
||||
g.CheckMoved(id => new GhostSpot(Mob.X + 1, Mob.Y, Mob.Z));
|
||||
Check.False(g.IsGhost(6), "it moved: real");
|
||||
|
||||
g.MarkSuspect(7, "Butcherous Eater", Mob, Lb, T0);
|
||||
g.Mark(8, "Butcherous Eater", Mob, Lb, T0);
|
||||
g.ExpireSuspects(T0.AddMinutes(2));
|
||||
Check.True(g.IsGhost(7), "2 min: still skipped");
|
||||
g.ExpireSuspects(T0.AddMinutes(3).AddSeconds(1));
|
||||
Check.False(g.IsGhost(7), "3 min with no word: tried again");
|
||||
Check.True(g.IsGhost(8), "a caught ghost doesn't expire");
|
||||
|
||||
g.MarkSuspect(9, "Butcherous Eater", Mob, Lb, T0);
|
||||
g.Mark(9, "Butcherous Eater", Mob, Lb, T0);
|
||||
Check.False(g.IsSuspect(9), "caught after all: a ghost now");
|
||||
}
|
||||
|
||||
private static void Place(uint id, string name, float x, float y, bool creature = true)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
|
|
|
|||
|
|
@ -105,6 +105,12 @@ internal static class MetaSchedulerTests
|
|||
MyQuestsLineKind.Quest, "underscores in the name");
|
||||
Check.Eq(e.Name, "stipendtimer_monthly", "underscored name");
|
||||
|
||||
// A space between the timestamp and the message (some servers send it so).
|
||||
Check.Eq(MyQuestsParser.Parse("stipendtimer_monthly - 12 solves (1759276800) \"Monthly Stipend\" -1 2592000", out e),
|
||||
MyQuestsLineKind.Quest, "a space after the timestamp");
|
||||
Check.Eq(e.Message, "Monthly Stipend", "message after the space");
|
||||
Check.Eq(e.MinDeltaSeconds, 2592000L, "delta after the space");
|
||||
|
||||
// The message may hold quotes and the line may carry the client's trailing newline.
|
||||
Check.Eq(MyQuestsParser.Parse("taskmoarsmenartifactswait - 1 solves (1759000000)\"Bring \"artifacts\" to Kanji\" -1 72000\n", out e),
|
||||
MyQuestsLineKind.Quest, "quotes in the message, trailing newline");
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType;
|
||||
|
|
@ -39,10 +41,17 @@ internal static class NavEngineTests
|
|||
r.Add("nav engine: a recall that never fires, next waypoint close: moves on after 60 s", RecallTimeoutNear);
|
||||
r.Add("nav engine: macro start picks the nearest plain waypoint", ResumeNearest);
|
||||
r.Add("nav engine: indoors, macro start picks the nearest waypoint on foot, not through a wall", ResumeNearestByWalk);
|
||||
r.Add("nav engine (11-27): indoors, macro start keeps the waypoint in your own room (no plan, a clear walk) over one a floor below", ResumeNearestOwnRoom);
|
||||
r.Add("nav engine: macro start skips a nearest waypoint already walked past, not one still ahead", ResumeNearestPassed);
|
||||
r.Add("nav engine: back from a pause that moved 10+ yd, nav heads for the closest waypoint", ResumeAfterPauseMoved);
|
||||
r.Add("nav engine: back from a pause that moved under 10 yd, nav keeps its waypoint", ResumeAfterPauseStill);
|
||||
r.Add("nav engine: the dungeon patrol keeps its waypoint after a pause that moved it (no closest-waypoint pick)", ResumeAfterPausePatrol);
|
||||
r.Add("nav engine (11-28): back from a fight in a side room, the patrol's waypoint behind a wall: walks to the route in sight first, then on to it", InSightSideRoom);
|
||||
r.Add("nav engine (11-28): back from a fight, a clear walk to the waypoint (or a map that can't say): nothing changes", InSightClearOrUnknown);
|
||||
r.Add("nav engine (11-28): back from a fight, only the leg out of the waypoint in sight: goes on from there, passing over it", InSightAhead);
|
||||
r.Add("nav engine (11-28): back from a fight, nothing of the route near in sight: the map's way to the waypoint", InSightNoneFallsBack);
|
||||
r.Add("nav engine (11-28): a fight during the walk to the route in sight: looked at again from where it ends", InSightInterrupted);
|
||||
r.Add("nav engine (11-28): Lugian Excavations 0x02E7 on the real dats: the patrol's legs are clear walks, the 18:56 wall stuck isn't, and the route in sight is found from there and from the rooms off the route (if the dats are here)", InSightLugianRealDats);
|
||||
r.Add("nav engine: Go To Closest Waypoint off keeps the last waypoint (hazard/corpse still rejoin)", ResumeNearestOff);
|
||||
r.Add("nav engine: a loaded route starts at [0] for Once/Follow, or for any route with the option off", StartsAtFirstPoint);
|
||||
r.Add("nav engine: nearest waypoint lookup", FindNearest);
|
||||
|
|
@ -98,7 +107,7 @@ internal static class NavEngineTests
|
|||
public readonly FakePlanner? P;
|
||||
|
||||
/// <summary>Call FakeHost.Reset() and At(...) first.</summary>
|
||||
public Nav(NavRouteParser route, int idx = 0, FakePlanner? planner = null)
|
||||
public Nav(NavRouteParser route, int idx = 0, FakePlanner? planner = null, INavRecoveryPlanner? other = null)
|
||||
{
|
||||
_now = 1_000_000;
|
||||
NavigationEngine.Clock = static () => _now;
|
||||
|
|
@ -107,6 +116,7 @@ internal static class NavEngineTests
|
|||
E = new NavigationEngine(host, S);
|
||||
P = planner;
|
||||
if (planner != null) E.SetRecoveryPlanner(planner);
|
||||
else if (other != null) E.SetRecoveryPlanner(other);
|
||||
}
|
||||
|
||||
public void Tick(int ms = 40) { _now += ms; E.Tick(); }
|
||||
|
|
@ -133,6 +143,24 @@ internal static class NavEngineTests
|
|||
/// <summary>Per-target walk length (yd); null = no path. Used instead of GivePlan when set.</summary>
|
||||
public Func<NavPoint, double?>? WalkYd;
|
||||
public readonly List<NavPoint> PlanTargets = new();
|
||||
/// <summary>
|
||||
/// Per-target walk for a waypoint in your own room with a clear walk (TryPlan has no plan for it): what the real
|
||||
/// planner's WalkLengthYd answers there. Null = not in your room.
|
||||
/// </summary>
|
||||
public Func<NavPoint, double?>? InRoomYd;
|
||||
/// <summary>The dungeon map's straight walk from where the fake character stands (null: the map can't say).</summary>
|
||||
public Func<NavPoint, bool?>? InSight;
|
||||
/// <summary>Every StraightWalkInSight asked, with its answer.</summary>
|
||||
public readonly List<(NavPoint Target, bool? Answer)> SightAsks = new();
|
||||
|
||||
public double? WalkLengthYd(NavPoint target) => TryPlan(target, out _)?.LengthYd ?? InRoomYd?.Invoke(target);
|
||||
|
||||
public bool? StraightWalkInSight(NavPoint target)
|
||||
{
|
||||
bool? a = InSight?.Invoke(target);
|
||||
SightAsks.Add((target, a));
|
||||
return a;
|
||||
}
|
||||
|
||||
public NavRecoveryPlan? TryPlan(NavPoint target, out string why)
|
||||
{
|
||||
|
|
@ -559,6 +587,36 @@ internal static class NavEngineTests
|
|||
Check.Eq(blind.Idx, 1, "no position: untouched");
|
||||
}
|
||||
|
||||
private static void ResumeNearestOwnRoom()
|
||||
{
|
||||
// Desert Mine 0x0182, 2026-11-27: [0] is beside you in your own room, where the planner has no plan (nothing
|
||||
// to walk round); [2] is nearer on the map but a floor below, a 99 yd walk. The walk pick left [0] out and took
|
||||
// [2] (reached at once from above, the bot then ran at the wall toward [3]).
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
var pose = FakeHost.PlayerPose;
|
||||
FakeHost.PlayerPose = ((pose.Cell & 0xFFFF0000) | 0x017B, pose.X, pose.Y, pose.Z);
|
||||
var route = Route(RT.Circular, Pt(3, 0), Pt(200, 0), Pt(1, 0), Pt(8, 0), Pt(300, 0));
|
||||
Func<NavPoint, double?> walk = t => t.NS == route.Points[2].NS ? 99 : t.NS == route.Points[3].NS ? 110 : null;
|
||||
Func<NavPoint, double?> room = t => t.NS == route.Points[0].NS ? 3 : null;
|
||||
var nav = new Nav(route, idx: 0, planner: new FakePlanner { WalkYd = walk, InRoomYd = room });
|
||||
nav.E.ResumeFromNearestWaypoint();
|
||||
Check.Eq(nav.Idx, 0, "loaded at [0]: the waypoint in your own room (3 yd) stays over [2] a floor below (99 yd walk)");
|
||||
|
||||
// Old Mine 0x0190, 2026-11-26: the load's map pick put it a floor below ([2]); the macro start takes [0].
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
FakeHost.PlayerPose = ((pose.Cell & 0xFFFF0000) | 0x017B, pose.X, pose.Y, pose.Z);
|
||||
var nav2 = new Nav(route, idx: 2, planner: new FakePlanner { WalkYd = walk, InRoomYd = room });
|
||||
nav2.E.ResumeFromNearestWaypoint();
|
||||
Check.Eq(nav2.Idx, 0, "loaded at [2] a floor below: the macro start moves it to [0] in your room");
|
||||
|
||||
// With nothing in your room the walks decide, as before.
|
||||
FakeHost.Reset(); At(0, 0);
|
||||
FakeHost.PlayerPose = ((pose.Cell & 0xFFFF0000) | 0x017B, pose.X, pose.Y, pose.Z);
|
||||
var nav3 = new Nav(route, idx: 0, planner: new FakePlanner { WalkYd = walk });
|
||||
nav3.E.ResumeFromNearestWaypoint();
|
||||
Check.Eq(nav3.Idx, 2, "no waypoint in your room: the shortest walk ([2], 99 yd)");
|
||||
}
|
||||
|
||||
private static void ResumeNearestByWalk()
|
||||
{
|
||||
// In a dungeon cell: [2] is 5 yd away through a wall (a 300 yd walk), [1] (current) is
|
||||
|
|
@ -649,6 +707,321 @@ internal static class NavEngineTests
|
|||
Check.Eq(LogCount("back from a pause"), 0, "nothing re-picked");
|
||||
}
|
||||
|
||||
// ── Back to the route in sight (11-28) ───────────────────────────────────
|
||||
// Lugian Excavations, a melee patrol with Monster Range 20 m: after the fights nav steered straight at the patrol's
|
||||
// waypoint behind a wall and ran into it. The dungeon map's straight-walk answer is faked here by walls on the plan.
|
||||
|
||||
/// <summary>A fake dungeon map: the straight walk from the fake character to a point is clear unless it crosses one of
|
||||
/// these walls ((north, east) yd, end to end).</summary>
|
||||
private static Func<NavPoint, bool?> Walls(params (double N0, double E0, double N1, double E1)[] walls)
|
||||
=> t =>
|
||||
{
|
||||
var (tn, te) = NE(t);
|
||||
foreach (var w in walls)
|
||||
if (Crosses(_n, _e, tn, te, w.N0, w.E0, w.N1, w.E1)) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
private static bool Crosses(double ax, double ay, double bx, double by, double cx, double cy, double dx, double dy)
|
||||
{
|
||||
static double O(double ax, double ay, double bx, double by, double px, double py) => (bx - ax) * (py - ay) - (by - ay) * (px - ax);
|
||||
return O(cx, cy, dx, dy, ax, ay) * O(cx, cy, dx, dy, bx, by) < 0 && O(ax, ay, bx, by, cx, cy) * O(ax, ay, bx, by, dx, dy) < 0;
|
||||
}
|
||||
|
||||
private static (double N, double E) NE(NavPoint p) => ((p.NS - NS0) * 240.0, (p.EW - EW0) * 240.0);
|
||||
|
||||
/// <summary>A side room east of the Square's leg [1]→[2] (east 40, north 0..40): its west wall at east 44 with an
|
||||
/// opening from north 18 to 22, its other walls at north 10, north 30 and east 60.</summary>
|
||||
private static readonly (double, double, double, double)[] SideRoom =
|
||||
{ (10, 44, 18, 44), (22, 44, 30, 44), (30, 44, 30, 60), (10, 44, 10, 60), (10, 60, 30, 60) };
|
||||
|
||||
private static void InSightSideRoom()
|
||||
{
|
||||
FakeHost.Reset(); At(14, 40); // on the leg [1]->[2], heading for [2]
|
||||
var p = new FakePlanner { InSight = Walls(SideRoom) };
|
||||
var nav = new Nav(Square(), idx: 2, planner: p);
|
||||
nav.E.KeepWaypointAfterPause = () => true; // the dungeon patrol
|
||||
nav.Tick();
|
||||
nav.E.Stop(); // a rock thrower in the side room
|
||||
At(14, 52); // the fight ends in there: [2] is behind its north wall
|
||||
nav.Run(1.0);
|
||||
Check.Eq(LogCount("walking to the route in sight first"), 1, "one walk to the route in sight, said once");
|
||||
Check.True(nav.Recovery.Contains("via the route in sight") && nav.Recovery.Contains("-> [2]"), $"walking it, then [2] ({nav.Recovery})");
|
||||
Check.Eq(nav.Idx, 2, "the patrol's waypoint is kept meanwhile");
|
||||
Check.False(nav.S.NavIsStuck, "not shown as stuck");
|
||||
var spot = p.SightAsks.Last(a => a.Answer == true).Target;
|
||||
var (sn, se) = NE(spot);
|
||||
Check.True(Math.Abs(se - 40) < 0.01 && sn > 20 && sn < 26, $"the spot is on the leg into [2], seen through the opening ({sn:F1}, {se:F1})");
|
||||
Check.True(p.SightAsks.Count <= 41, $"at most 40 spots tried after the waypoint ({p.SightAsks.Count - 1})");
|
||||
|
||||
At(sn, se); // walked out through the opening
|
||||
nav.Tick();
|
||||
Check.Eq(LogCount("rejoined the route at [2]"), 1, "back on the route, going on to [2]");
|
||||
Check.Eq(nav.Idx, 2, "on to [2]");
|
||||
Check.Eq(nav.Recovery, "none", "no recovery counted against [2]");
|
||||
}
|
||||
|
||||
private static void InSightClearOrUnknown()
|
||||
{
|
||||
foreach (bool? answer in new bool?[] { true, null })
|
||||
{
|
||||
FakeHost.Reset(); At(14, 40);
|
||||
var p = new FakePlanner { InSight = _ => answer };
|
||||
var nav = new Nav(Square(), idx: 2, planner: p);
|
||||
nav.E.KeepWaypointAfterPause = () => true;
|
||||
nav.Tick();
|
||||
nav.E.Stop();
|
||||
At(14, 52);
|
||||
nav.Run(1.0);
|
||||
string what = answer == true ? "a clear walk" : "the map can't say";
|
||||
Check.Eq(p.SightAsks.Count, 1, $"{what}: only the waypoint asked about");
|
||||
Check.Eq(LogCount("back from a pause"), 0, $"{what}: nothing said");
|
||||
Check.Eq(nav.Recovery, "none", $"{what}: no walk");
|
||||
Check.Eq(nav.Idx, 2, $"{what}: on to [2] as before");
|
||||
}
|
||||
|
||||
// A pause that hardly moved the character (half a yard): nothing between, nothing asked.
|
||||
FakeHost.Reset(); At(14, 40);
|
||||
var q = new FakePlanner { InSight = _ => false };
|
||||
var still = new Nav(Square(), idx: 2, planner: q);
|
||||
still.Tick();
|
||||
still.E.Stop();
|
||||
At(14.5, 40);
|
||||
still.Run(1.0);
|
||||
Check.Eq(q.SightAsks.Count, 0, "a pause that moved under 1 yd: not asked");
|
||||
}
|
||||
|
||||
private static void InSightAhead()
|
||||
{
|
||||
// The chase went on past [2] to the north-west: only the leg [2]->[3] (north 40, east 40 down to 0) is in sight.
|
||||
FakeHost.Reset(); At(30, 40);
|
||||
var p = new FakePlanner { InSight = t => { var (n, e) = NE(t); return Math.Abs(n - 40) < 0.01 && e < 39.99; } };
|
||||
var nav = new Nav(Square(), idx: 2, planner: p);
|
||||
nav.E.KeepWaypointAfterPause = () => true;
|
||||
nav.Tick();
|
||||
nav.E.Stop();
|
||||
At(46, 20);
|
||||
nav.Run(1.0);
|
||||
Check.Eq(LogCount("passing over [2]"), 1, "said: it passes over [2]");
|
||||
Check.True(nav.Recovery.Contains("-> [3]"), $"then [3] ({nav.Recovery})");
|
||||
var (sn, se) = NE(p.SightAsks.Last(a => a.Answer == true).Target);
|
||||
// Nearest is (40, 20), 6 yd; (40, 25) is 7.8 yd but passes over 5 yd less of the route (half of it counts).
|
||||
Check.True(Math.Abs(sn - 40) < 0.01 && se >= 20 && se <= 30, $"a spot on that leg near the character, passing over little ({sn:F1}, {se:F1})");
|
||||
At(sn, se);
|
||||
nav.Tick();
|
||||
Check.Eq(nav.Idx, 3, "goes on from [3]");
|
||||
}
|
||||
|
||||
private static void InSightNoneFallsBack()
|
||||
{
|
||||
FakeHost.Reset(); At(14, 40);
|
||||
var p = new FakePlanner { InSight = _ => false, GivePlan = true };
|
||||
var nav = new Nav(Square(), idx: 2, planner: p);
|
||||
nav.E.KeepWaypointAfterPause = () => true;
|
||||
nav.Tick();
|
||||
nav.E.Stop();
|
||||
At(14, 52);
|
||||
nav.Run(1.0);
|
||||
Check.Eq(LogCount("no spot of the route near it in sight"), 1, "said: nothing in sight");
|
||||
Check.Eq(LogCount("started (back from a pause, [2] is behind a wall"), 1, "the map's way to [2] instead");
|
||||
Check.True(nav.Recovery.Contains("via fake planner"), $"walking it ({nav.Recovery})");
|
||||
|
||||
// And no way on the map either: as before (straight on, the stuck escapes if it sticks).
|
||||
FakeHost.Reset(); At(14, 40);
|
||||
var q = new FakePlanner { InSight = _ => false };
|
||||
var nav2 = new Nav(Square(), idx: 2, planner: q);
|
||||
nav2.E.KeepWaypointAfterPause = () => true;
|
||||
nav2.Tick();
|
||||
nav2.E.Stop();
|
||||
At(14, 52);
|
||||
nav2.Run(1.0);
|
||||
Check.Eq(LogCount("result: no plan"), 1, "no plan: said so");
|
||||
Check.Eq(nav2.Idx, 2, "still on to [2]");
|
||||
}
|
||||
|
||||
private static void InSightInterrupted()
|
||||
{
|
||||
FakeHost.Reset(); At(14, 40);
|
||||
var p = new FakePlanner { InSight = Walls(SideRoom) };
|
||||
var nav = new Nav(Square(), idx: 2, planner: p);
|
||||
nav.E.KeepWaypointAfterPause = () => true;
|
||||
nav.Tick();
|
||||
nav.E.Stop();
|
||||
At(14, 52);
|
||||
nav.Run(1.0);
|
||||
Check.Eq(LogCount("walking to the route in sight first"), 1, "the walk started");
|
||||
|
||||
// Another rock thrower before it gets out, fought where it stands: looked at again (still in the side room).
|
||||
nav.E.Stop();
|
||||
nav.Run(1.0);
|
||||
Check.Eq(LogCount("cancelled, another pause"), 1, "the walk was dropped for the fight");
|
||||
Check.Eq(LogCount("walking to the route in sight first"), 2, "and laid again from where the fight ended");
|
||||
|
||||
// A third fight that ends out on the leg: [2] is in sight from there, so no walk at all.
|
||||
nav.E.Stop();
|
||||
At(30, 40);
|
||||
nav.Run(1.0);
|
||||
Check.Eq(LogCount("cancelled, another pause"), 2, "dropped again");
|
||||
Check.Eq(LogCount("walking to the route in sight first"), 2, "nothing new laid: [2] is in sight");
|
||||
Check.Eq(nav.Recovery, "none", "straight on to [2]");
|
||||
Check.Eq(nav.Idx, 2, "on to [2]");
|
||||
}
|
||||
|
||||
// ── The same on the real map: Lugian Excavations (0x02E7) ───────────────
|
||||
|
||||
/// <summary>The dungeon patrol laid 2026-11-28 18:50:47 from cell 02E70285 (71 points; world x, y, z).</summary>
|
||||
private static readonly (double X, double Y, double Z)[] LugianPatrol =
|
||||
{
|
||||
(401.5, 43802.0, 18.0), (404.0, 43804.5, 18.0), (404.0, 43849.5, 18.0), (406.5, 43852.0, 18.0), (513.0, 43852.0, 18.0), (524.0, 43863.0, 18.0),
|
||||
(524.0, 43899.5, 18.0), (526.5, 43902.0, 18.0), (631.5, 43902.0, 12.0), (634.0, 43904.5, 12.0), (634.0, 43922.0, 12.0), (634.0, 43904.5, 12.0),
|
||||
(636.5, 43902.0, 12.0), (703.0, 43902.0, 0.0), (724.0, 43907.0, 0.0), (744.0, 43927.0, 0.0), (734.0, 43957.0, 0.0), (739.0, 44012.0, 0.0),
|
||||
(754.0, 44017.0, 0.0), (774.0, 44047.0, 0.0), (784.0, 44057.0, 0.0), (774.0, 44087.0, 0.0), (784.0, 44117.0, 0.0), (774.0, 44147.0, 0.0),
|
||||
(784.0, 44177.0, 0.0), (814.0, 44187.0, 0.0), (824.0, 44197.0, 0.0), (824.0, 44217.0, 0.0), (844.0, 44237.0, 0.0), (834.0, 44267.0, 0.0),
|
||||
(845.0, 44312.0, 0.0), (854.0, 44312.0, 0.0), (845.0, 44312.0, 0.0), (834.0, 44267.0, 0.0), (844.0, 44237.0, 0.0), (824.0, 44217.0, 0.0),
|
||||
(824.0, 44197.0, 0.0), (784.0, 44167.0, 0.0), (774.0, 44157.0, 0.0), (774.0, 44137.0, 0.0), (784.0, 44127.0, 0.0), (784.0, 44107.0, 0.0),
|
||||
(774.0, 44097.0, 0.0), (774.0, 44077.0, 0.0), (784.0, 44067.0, 0.0), (779.0, 44052.0, 0.0), (749.0, 44012.0, 0.0), (734.0, 43997.0, 0.0),
|
||||
(734.0, 43947.0, 0.0), (744.0, 43937.0, 0.0), (739.0, 43922.0, 0.0), (719.0, 43902.0, 0.0), (656.5, 43902.0, 12.0), (654.0, 43899.5, 12.0),
|
||||
(654.0, 43872.0, 12.0), (654.0, 43899.5, 12.0), (651.5, 43902.0, 12.0), (616.5, 43902.0, 12.0), (614.0, 43899.5, 12.0), (614.0, 43872.0, 12.0),
|
||||
(614.0, 43899.5, 12.0), (611.5, 43902.0, 12.0), (526.5, 43902.0, 18.0), (524.0, 43899.5, 18.0), (524.0, 43863.0, 18.0), (513.0, 43852.0, 18.0),
|
||||
(406.5, 43852.0, 18.0), (404.0, 43849.5, 18.0), (404.0, 43804.5, 18.0), (401.5, 43802.0, 18.0), (394.0, 43802.0, 18.0),
|
||||
};
|
||||
|
||||
private static NavPoint World(double x, double y, double z)
|
||||
=> new() { Type = T.Point, NS = DungeonGeometry.WorldToNav(y), EW = DungeonGeometry.WorldToNav(x), Z = z / 240.0 };
|
||||
|
||||
/// <summary>Puts the fake character at a route point's nav coordinates.</summary>
|
||||
private static void AtNav(NavPoint p)
|
||||
{
|
||||
_n = (p.NS - NS0) * 240.0; _e = (p.EW - EW0) * 240.0;
|
||||
FakeHost.SetNavPosition(p.NS, p.EW);
|
||||
}
|
||||
|
||||
/// <summary>The real planner's straight-walk answer (NavRecoveryPlanner.WalkInSightOn) on a real dungeon map, from the
|
||||
/// fake character at height Z. No plans: a fallback shows as "no plan".</summary>
|
||||
private sealed class GeoPlanner : INavRecoveryPlanner
|
||||
{
|
||||
public DungeonGeometry Geo = null!;
|
||||
public double Z;
|
||||
public NavPoint? LastClear;
|
||||
public NavRecoveryPlan? TryPlan(NavPoint target, out string why) { why = "test planner: no plans"; return null; }
|
||||
public NavAreaCheck CheckArea(uint playerCell, double tNs, double tEw, out string routeArea, out string playerArea)
|
||||
{ routeArea = playerArea = string.Empty; return NavAreaCheck.Match; }
|
||||
public bool? StraightWalkInSight(NavPoint target)
|
||||
{
|
||||
bool? a = NavRecoveryPlanner.WalkInSightOn(Geo, NS0 + _n / 240.0, EW0 + _e / 240.0, Z, target);
|
||||
if (a == true) LastClear = target;
|
||||
return a;
|
||||
}
|
||||
}
|
||||
|
||||
private static void InSightLugianRealDats()
|
||||
{
|
||||
string acDir = DunRouteTests.AcDir;
|
||||
if (!Directory.Exists(acDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; }
|
||||
var loader = new GeometryLoader();
|
||||
if (!loader.Initialize(acDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; }
|
||||
try
|
||||
{
|
||||
const uint lb = 0x02E7;
|
||||
var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
|
||||
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
|
||||
Check.True(geo != null && graph.Count > 250, $"Lugian Excavations loaded ({graph.Count} cells)");
|
||||
if (geo == null) return;
|
||||
var pts = LugianPatrol.Select(p => World(p.X, p.Y, p.Z)).ToList();
|
||||
int n = pts.Count;
|
||||
|
||||
// The patrol's own legs: walked straight, so the map should call (nearly) all of them clear.
|
||||
int clear = 0;
|
||||
var notClear = new List<string>();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var a = pts[i];
|
||||
bool? w = NavRecoveryPlanner.WalkInSightOn(geo, a.NS, a.EW, a.Z * 240.0, pts[(i + 1) % n]);
|
||||
if (w == true) clear++; else notClear.Add($"[{i}]->[{(i + 1) % n}]={(w == null ? "?" : "no")}");
|
||||
}
|
||||
Console.WriteLine($" patrol legs: {clear}/{n} clear walks{(notClear.Count > 0 ? "; not: " + string.Join(" ", notClear) : "")}");
|
||||
Check.True(clear >= n - 3, $"the patrol's legs are clear walks on the map ({clear}/{n})");
|
||||
|
||||
// The 18:56:31 stuck: cell 02E70125 at local (332.13, -397.02, 0), heading for [15] 39.5 m off, standing at a wall.
|
||||
var stuck = World(2 * 192 + 332.13, 0xE7 * 192 - 397.02, 0);
|
||||
Check.Eq(NavRecoveryPlanner.WalkInSightOn(geo, stuck.NS, stuck.EW, 0, pts[15]), (bool?)false, "from where it stuck, no clear walk to [15]");
|
||||
|
||||
var route = new NavRouteParser { RouteType = RT.Circular };
|
||||
route.Points.AddRange(pts);
|
||||
FakeHost.Reset();
|
||||
AtNav(World(734, 43917, 0)); // on the leg [14]->[15] when the fight began
|
||||
var gp = new GeoPlanner { Geo = geo, Z = 0 };
|
||||
var nav = new Nav(route, idx: 15, other: gp);
|
||||
nav.E.KeepWaypointAfterPause = () => true;
|
||||
nav.Tick();
|
||||
nav.E.Stop();
|
||||
AtNav(stuck);
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
nav.Run(0.3);
|
||||
sw.Stop();
|
||||
string line = FakeHost.Logs.FirstOrDefault(l => l.Contains("walking to the route in sight first")) ?? "(none)";
|
||||
if (line == "(none)") foreach (var l in FakeHost.Logs.Where(l => l.Contains("Nav:"))) Console.WriteLine(" " + l);
|
||||
Check.True(line.Contains("[16]->[17]"), "from there the route is in sight on [16]->[17] (also on the loop's way back, [47]->[48], out of reach)");
|
||||
Console.WriteLine($" from the 18:56 stuck: {line.Replace("Nav: ", "")} [{sw.ElapsedMilliseconds} ms for the ticks]");
|
||||
Check.True(line != "(none)" && gp.LastClear != null, "from there it walks to the route in sight");
|
||||
if (gp.LastClear is { } spot)
|
||||
Check.Eq(NavRecoveryPlanner.WalkInSightOn(geo, stuck.NS, stuck.EW, 0, spot), (bool?)true, "a spot it can walk to straight");
|
||||
|
||||
// Every room off the route on the patrol's levels: the patrol heading for the waypoint nearest it, but no clear walk
|
||||
// there. How often is a route spot in sight found (the rest go to the map's way, through the doorways)?
|
||||
int rooms = 0, blocked = 0, found = 0, none = 0;
|
||||
long worstMs = 0;
|
||||
foreach (uint cell in graph.Keys)
|
||||
{
|
||||
if (!geo.TryCellFloorCentre(cell, out double cx, out double cy, out double cz)) continue;
|
||||
var c = World(cx, cy, cz);
|
||||
int best = -1;
|
||||
double bestD = double.MaxValue, onRoute = double.MaxValue;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var p = pts[i];
|
||||
if (Math.Abs(p.Z * 240.0 - cz) > 3.0) continue;
|
||||
double d = Math.Sqrt(Math.Pow(DungeonGeometry.NavToWorld(p.EW) - cx, 2) + Math.Pow(DungeonGeometry.NavToWorld(p.NS) - cy, 2));
|
||||
if (d < bestD) { bestD = d; best = i; }
|
||||
var q = pts[(i + 1) % n];
|
||||
onRoute = Math.Min(onRoute, SegmentDistance(DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS),
|
||||
DungeonGeometry.NavToWorld(q.EW), DungeonGeometry.NavToWorld(q.NS), cx, cy));
|
||||
}
|
||||
if (best < 0 || bestD > 50 || onRoute < 3.0) continue;
|
||||
rooms++;
|
||||
if (NavRecoveryPlanner.WalkInSightOn(geo, c.NS, c.EW, cz, pts[best]) != false) continue;
|
||||
blocked++;
|
||||
|
||||
FakeHost.Reset();
|
||||
AtNav(World(cx + 2, cy, cz));
|
||||
var g = new GeoPlanner { Geo = geo, Z = cz };
|
||||
var nv = new Nav(route, idx: best, other: g);
|
||||
nv.E.KeepWaypointAfterPause = () => true;
|
||||
nv.Tick();
|
||||
nv.E.Stop();
|
||||
AtNav(c);
|
||||
var t0 = System.Diagnostics.Stopwatch.StartNew();
|
||||
nv.Tick();
|
||||
worstMs = Math.Max(worstMs, t0.ElapsedMilliseconds);
|
||||
if (FakeHost.Logs.Any(l => l.Contains("walking to the route in sight first"))) found++;
|
||||
else if (FakeHost.Logs.Any(l => l.Contains("no spot of the route near it in sight"))) none++;
|
||||
}
|
||||
Console.WriteLine($" rooms off the route: {rooms}; no clear walk to the nearest waypoint from {blocked}; the route in sight found from {found}, "
|
||||
+ $"nothing in sight (the map's way) from {none}; slowest resume {worstMs} ms");
|
||||
Check.Eq(found + none, blocked, "every blocked case ends in a walk to the route in sight or the map's way");
|
||||
Check.True(blocked == 0 || found * 2 >= blocked, $"the route in sight is found from most of them ({found}/{blocked})");
|
||||
Check.True(worstMs < 100, $"a resume's search takes under 100 ms ({worstMs} ms)");
|
||||
}
|
||||
finally { DungeonPathfinder.InvalidateCache(); }
|
||||
}
|
||||
|
||||
private static double SegmentDistance(double ax, double ay, double bx, double by, double x, double y)
|
||||
{
|
||||
double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
|
||||
double t = l2 < 1e-12 ? 0 : Math.Clamp(((x - ax) * dx + (y - ay) * dy) / l2, 0, 1);
|
||||
return Math.Sqrt(Math.Pow(ax + dx * t - x, 2) + Math.Pow(ay + dy * t - y, 2));
|
||||
}
|
||||
|
||||
private static void ResumeNearestOff()
|
||||
{
|
||||
FakeHost.Reset(); At(0, 10);
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ internal static class PlannerObjectTests
|
|||
r.Add("planner objects (11-18): a stuck escape burst heading into a wall or an object within 2 m turns to where the dungeon map has room", EscapeRoomTest);
|
||||
r.Add("planner objects (11-18): 0x0190 room 88's table and 0x00C1 room 81's statue on the real dats - an in-room recovery plan, no sample inside (if the dats are here)", InRoomReal);
|
||||
r.Add("planner objects (11-18): Thread patrols with an exit portal at the entry cell on the real dats - no leg through an object, none into the portal (if the dats are here)", PortalPatrolsReal);
|
||||
r.Add("planner objects (11-27): 0x0182's arrival on the real dats - its loop's [0] is in your room with a clear walk (the start pick counts it), [132] is in a room under it (if the dats are here)", OwnRoomStartReal);
|
||||
r.Add("planner objects (review): the room planner never moves a waypoint up on a dais, a ramp or a platform, or in a step, off it (TargetMoved skipped it); a statue's still", OnTopTargets);
|
||||
r.Add("planner objects (review): the walk test from a spot up on a dais is judged from where the leg leaves it, not failed at its first sample", WalkTestFromOnTop);
|
||||
}
|
||||
|
|
@ -497,6 +498,39 @@ internal static class PlannerObjectTests
|
|||
|
||||
// ── Real dats ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Desert Mine 0x0182, 2026-11-27: arrived in cell 0x0182017B at about (41, -25.5, 0); the Thread route's [0] is
|
||||
// (40, -30, 0), its [132] (39.13, -25.97, -11.97) is on the floor under it. The planner's start-pick answer for [0]
|
||||
// comes from these pieces: the same containing cell as yours, and the in-room walk clear (StraightWalkClearWhy).
|
||||
private static void OwnRoomStartReal()
|
||||
{
|
||||
var loader = Loader(out var before);
|
||||
if (loader == null) return;
|
||||
try
|
||||
{
|
||||
const uint lb = 0x0182;
|
||||
DungeonPathfinder.InvalidateCache();
|
||||
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS)!;
|
||||
Check.NotNull(geo, "0x0182: the dungeon map");
|
||||
var floors = new List<(uint, RynthCore.Plugin.RynthAi.Raycasting.Vector3[])>();
|
||||
foreach (var poly in loader.DungeonLOS!.GetDungeonMapFloorPolygons(lb))
|
||||
if (!poly.IsPortal && poly.Vertices != null && DungeonGeometry.IsUpwardFloor(poly.Vertices)) floors.Add((poly.CellId, poly.Vertices));
|
||||
double ox = 0x01 * 192.0, oy = 0x82 * 192.0;
|
||||
(double X, double Y, double Z) me = (ox + 41.15, oy - 25.52, 0.0), first = (ox + 40.0, oy - 30.0, 0.03), under = (ox + 39.13, oy - 25.97, -11.97);
|
||||
uint cMe = NavRecoveryPlanner.PickContainingCell(floors, me.X, me.Y, (float)me.Z);
|
||||
uint cFirst = NavRecoveryPlanner.PickContainingCell(floors, first.X, first.Y, (float)first.Z);
|
||||
uint cUnder = NavRecoveryPlanner.PickContainingCell(floors, under.X, under.Y, (float)under.Z);
|
||||
Console.WriteLine($" cells: you 0x{cMe:X8}, [0] 0x{cFirst:X8}, [132] 0x{cUnder:X8}");
|
||||
Check.Eq(cMe & 0xFFFF, 0x017Bu, "you are in 0x017B (the arrival's cell in the log)");
|
||||
Check.Eq(cFirst, cMe, "[0] is in your room");
|
||||
Check.True(cUnder != 0 && cUnder != cMe, "[132] is in another room");
|
||||
var plan = NavRecoveryPlanner.PlanInRoom(geo, DungeonGeometry.WorldToNav(me.Y), DungeonGeometry.WorldToNav(me.X), me.Z,
|
||||
DungeonGeometry.WorldToNav(first.Y), DungeonGeometry.WorldToNav(first.X), first.Z, out string why);
|
||||
Check.Null(plan, "you to [0]: no in-room plan (nothing to walk round)");
|
||||
Check.Eq(why, NavRecoveryPlanner.StraightWalkClearWhy, "you to [0]: the straight walk is clear, so the start pick counts it");
|
||||
}
|
||||
finally { DungeonPathfinder.StaticMeshSource = before; DungeonPathfinder.InvalidateCache(); loader.Dispose(); }
|
||||
}
|
||||
|
||||
private static GeometryLoader? Loader(out Func<uint, List<(uint, uint, BoundingVolume)>>? before)
|
||||
{
|
||||
before = DungeonPathfinder.StaticMeshSource;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,191 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.CreatureData;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// R-20261127-144058-8cb2: "when a monster is close to death it will switch to another prior to
|
||||
// finishing off its target, then once the next monster is dead it will finish off the one it was
|
||||
// originally targetting". The third Force Bolt at a Guardian Armoredillo was the predicted kill
|
||||
// (hp~1800, dealt~1393): the swap locked a fresh Tamed Armoredillo, the bolt was resisted 640 ms
|
||||
// later, and with Target Lock on the bot fought the fresh one for 13 s before it went back to the
|
||||
// Guardian, at 23%. Now the survivor takes the lock back once it is known to be alive.
|
||||
internal static class PredictedKillReclaimTests
|
||||
{
|
||||
private const uint Player = 0x50000F41;
|
||||
private const uint Lb = 0x88650000;
|
||||
private const uint GuardianWcid = 3101, TamedWcid = 3102;
|
||||
private const string Guardian = "Guardian Armoredillo", Tamed = "Tamed Armoredillo";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("predicted kill (R-20261127 8cb2): resisted after the swap -> the lock goes back to it", ResistedTakesLockBack);
|
||||
r.Add("predicted kill (R-20261127 8cb2): still alive when the swap's window ends -> back to it", AliveAtWindowEndTakesLockBack);
|
||||
r.Add("predicted kill (R-20261127 8cb2): it died after all -> the new target is kept", DiedKeepsNewTarget);
|
||||
r.Add("predicted kill (R-20261127 8cb2): alive only after 10 s -> the new target is kept", LateSurvivalKeepsNewTarget);
|
||||
r.Add("predicted kill (R-20261127 8cb2): the armed cast resisted calls the swap off; a same-named target's miss doesn't reclaim", ArmedResistAndSameName);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { MonsterRange = 10, TargetSelection = 1, TargetLock = true, EnableCombat = true };
|
||||
public CombatManager C = null!;
|
||||
public WorldObjectCache Cache = null!;
|
||||
public DateTime Now = RynthClock.Now;
|
||||
private readonly List<uint> _ids = new();
|
||||
private uint _next = 0x80000601;
|
||||
|
||||
public Rig()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
FakeHost.Names[Player] = "Me";
|
||||
FakeHost.Positions[Player] = (Lb | 0x1E, 96f, 96f, 0f);
|
||||
FakeHost.PlayerPose = (Lb | 0x1E, 96f, 96f, 0f);
|
||||
}
|
||||
|
||||
public uint Mob(string name, uint wcid, float north, float east = 0)
|
||||
{
|
||||
uint id = _next++;
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1E, 96f + east, 96f + north, 0f);
|
||||
FakeHost.ItemTypes[id] = 0x10;
|
||||
FakeHost.Wcids[id] = wcid;
|
||||
_ids.Add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
public void Build(uint fightTarget)
|
||||
{
|
||||
var host = FakeHost.Create();
|
||||
Cache = FakeHost.MakeCache(host, Player, _ids);
|
||||
C = new CombatManager(host, S, Cache);
|
||||
C.SetPlayerId(Player);
|
||||
C.SetDamageStores(null, new MonsterDamageStore());
|
||||
C.TargetClock = () => Now;
|
||||
C.EngageForTest(unchecked((int)fightTarget));
|
||||
}
|
||||
|
||||
public void Rescan()
|
||||
{
|
||||
typeof(CombatManager).GetField("_lastScanTime", Any)!.SetValue(C, DateTime.MinValue);
|
||||
C.ScanNearbyTargets();
|
||||
}
|
||||
|
||||
/// <summary>The predicted kill's cast was accepted: the swap off the target, then the next lock.</summary>
|
||||
public void SwapAndLockNext()
|
||||
{
|
||||
C.ArmPredictedSwapForTest(castAgoMs: 2000);
|
||||
C.PredictedSwapForTest();
|
||||
Rescan();
|
||||
C.HandleCombatTrigger();
|
||||
}
|
||||
|
||||
public void Tick() { Rescan(); C.HandleCombatTrigger(); }
|
||||
public int Target => C.activeTargetId;
|
||||
public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static int Id(uint id) => unchecked((int)id);
|
||||
|
||||
private static void ResistedTakesLockBack()
|
||||
{
|
||||
var r = new Rig();
|
||||
uint guardian = r.Mob(Guardian, GuardianWcid, 3);
|
||||
uint tamed = r.Mob(Tamed, TamedWcid, 3.5f, 0.5f);
|
||||
r.Build(guardian);
|
||||
|
||||
r.SwapAndLockNext();
|
||||
Check.Eq(r.Target, Id(tamed), "the swap locks the Tamed Armoredillo");
|
||||
|
||||
r.Now = r.Now.AddMilliseconds(640);
|
||||
r.C.HandleChatForDamage("Guardian Armoredillo resists your spell", 7);
|
||||
Check.Eq(r.LogCount("Predicted kill of 0x80000601 'Guardian Armoredillo' resisted an attack after the swap"), 1, "the resist says it lives");
|
||||
r.Tick();
|
||||
Check.Eq(r.Target, Id(guardian), "the Guardian takes the lock back (Target Lock on)");
|
||||
Check.Eq(r.LogCount("survived: back to it"), 1, "the switch says why");
|
||||
|
||||
r.Tick();
|
||||
Check.Eq(r.Target, Id(guardian), "and keeps it: no trading back");
|
||||
}
|
||||
|
||||
private static void AliveAtWindowEndTakesLockBack()
|
||||
{
|
||||
var r = new Rig();
|
||||
uint guardian = r.Mob(Guardian, GuardianWcid, 3);
|
||||
uint tamed = r.Mob(Tamed, TamedWcid, 3.5f, 0.5f);
|
||||
r.Build(guardian);
|
||||
r.SwapAndLockNext();
|
||||
Check.Eq(r.Target, Id(tamed), "the swap locks the Tamed Armoredillo");
|
||||
|
||||
r.Now = r.Now.AddMilliseconds(1500);
|
||||
r.Tick();
|
||||
Check.Eq(r.Target, Id(tamed), "inside the swap's window nothing is known yet");
|
||||
|
||||
r.Now = r.Now.AddMilliseconds(600);
|
||||
r.Tick();
|
||||
Check.Eq(r.LogCount("still alive: it is a target again"), 1, "alive when the window ends");
|
||||
Check.Eq(r.Target, Id(guardian), "the Guardian takes the lock back");
|
||||
}
|
||||
|
||||
private static void DiedKeepsNewTarget()
|
||||
{
|
||||
var r = new Rig();
|
||||
uint guardian = r.Mob(Guardian, GuardianWcid, 3);
|
||||
uint tamed = r.Mob(Tamed, TamedWcid, 3.5f, 0.5f);
|
||||
r.Build(guardian);
|
||||
r.SwapAndLockNext();
|
||||
r.Cache.OnUpdateHealth(guardian, 0f); // the server says it died
|
||||
r.Now = r.Now.AddMilliseconds(2100);
|
||||
r.Tick();
|
||||
Check.Eq(r.Target, Id(tamed), "a dead prediction: the Tamed Armoredillo stays the target");
|
||||
Check.Eq(r.LogCount("survived: back to it"), 0, "no switch");
|
||||
}
|
||||
|
||||
private static void LateSurvivalKeepsNewTarget()
|
||||
{
|
||||
var r = new Rig();
|
||||
uint guardian = r.Mob(Guardian, GuardianWcid, 3);
|
||||
uint tamed = r.Mob(Tamed, TamedWcid, 3.5f, 0.5f);
|
||||
r.Build(guardian);
|
||||
r.SwapAndLockNext();
|
||||
r.Now = r.Now.AddMilliseconds(CombatManager.ReclaimWindowMs + 500);
|
||||
r.Tick();
|
||||
Check.Eq(r.Target, Id(tamed), "10 s on, the fight with the Tamed Armoredillo is kept (Target Lock on)");
|
||||
Check.Eq(r.LogCount("survived: back to it"), 0, "no switch");
|
||||
}
|
||||
|
||||
private static void ArmedResistAndSameName()
|
||||
{
|
||||
var r = new Rig();
|
||||
uint guardian = r.Mob(Guardian, GuardianWcid, 3);
|
||||
r.Mob(Tamed, TamedWcid, 3.5f, 0.5f);
|
||||
r.Build(guardian);
|
||||
r.C.ArmPredictedSwapForTest(castAgoMs: 2600);
|
||||
r.C.HandleChatForDamage("Guardian Armoredillo resists your spell", 7);
|
||||
Check.False(r.C.PredictedSwapArmed, "its own cast was resisted: the swap is called off");
|
||||
Check.Eq(r.LogCount("called off: it resisted the cast"), 1, "and logged");
|
||||
Check.Eq(r.Target, Id(guardian), "still on the Guardian");
|
||||
|
||||
// Two of a name: the swap went from one Tamed Armoredillo to the other; a resist naming
|
||||
// "Tamed Armoredillo" may be the new target's, so it proves nothing about the first.
|
||||
var s = new Rig();
|
||||
uint first = s.Mob(Tamed, TamedWcid, 3);
|
||||
uint second = s.Mob(Tamed, TamedWcid, 3.5f, 0.5f);
|
||||
s.Build(first);
|
||||
s.SwapAndLockNext();
|
||||
Check.Eq(s.Target, Id(second), "the swap locks the other one");
|
||||
s.C.HandleChatForDamage("Tamed Armoredillo resists your spell", 7);
|
||||
s.Tick();
|
||||
Check.Eq(s.Target, Id(second), "a same-named miss takes nothing back");
|
||||
Check.Eq(s.LogCount("resisted an attack after the swap"), 0, "and isn't taken as the first one's");
|
||||
}
|
||||
}
|
||||
246
Tools/RynthCore.RynthAiHostTests/Tests/ProfileStartTests.cs
Normal file
246
Tools/RynthCore.RynthAiHostTests/Tests/ProfileStartTests.cs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-11-27 (R-20261127-124531-b5d3): a new settings profile was always a copy of the one in use,
|
||||
// and the Monsters rules belong to the profile (2026-11-18), so a T11 profile made from a T10 one
|
||||
// had every T10 monster rule in it. A new profile now starts from a copy (Save As, which says what
|
||||
// it copied) or fresh (New: the Monsters list down to Default, no items or consumables, weapons
|
||||
// filled from the pack, every other setting kept). The Monsters list also has a Clear list, which
|
||||
// keeps the Default row and saves.
|
||||
internal static class ProfileStartTests
|
||||
{
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const int HandWraps = unchecked((int)0x801A1F0D);
|
||||
private const int Sword = 0x50000101, Kit = 0x50000202;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("new profile: the fresh reset keeps Default (or makes one) and only empties the lists", ResetUnit);
|
||||
r.Add("new profile: Save As says it is a copy and how many monster rules came with it", CopySays);
|
||||
r.Add("new profile: Fresh has only the Default row and no items, keeps the other settings", FreshProfile);
|
||||
r.Add("new profile: Fresh never replaces an existing profile, and the one left keeps its lists", FreshRefusesExisting);
|
||||
r.Add("monsters: Clear list keeps the Default row and saves the profile and the Monsters file", ClearList);
|
||||
r.Add("new profile: /ra settings new is fresh, saveas a copy; the menu's Clear list verb", CommandsAndVerbs);
|
||||
}
|
||||
|
||||
private sealed class Scratch : IDisposable
|
||||
{
|
||||
private readonly string? _buffs = BuffProfileStore.FolderOverride;
|
||||
public readonly string CharDir, MonstersFile;
|
||||
|
||||
public Scratch(string name)
|
||||
{
|
||||
string root = Path.Combine(Program.TempRoot, "profile-start", name);
|
||||
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
|
||||
Directory.CreateDirectory(root);
|
||||
LegacyDashboardRenderer.ProfilesBase = Path.Combine(root, "SettingsProfiles");
|
||||
LegacyDashboardRenderer.MonstersBase = Path.Combine(root, "MonsterProfiles");
|
||||
BuffProfileStore.FolderOverride = Path.Combine(root, "BuffProfiles");
|
||||
CharDir = Path.Combine(LegacyDashboardRenderer.ProfilesBase, "TestWorld", "Tester");
|
||||
MonstersFile = Path.Combine(LegacyDashboardRenderer.MonstersBase, "TestWorld", "Tester.json");
|
||||
}
|
||||
|
||||
public string Tag => File.Exists(MonstersFile + ".profile") ? File.ReadAllText(MonstersFile + ".profile").Trim() : "";
|
||||
public string Profile(string name) => File.ReadAllText(Path.Combine(CharDir, name + ".json"));
|
||||
|
||||
public void Dispose() => BuffProfileStore.FolderOverride = _buffs;
|
||||
}
|
||||
|
||||
private static LegacyDashboardRenderer Login(out LegacyUiSettings s)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
DataWriteGuard.Reset();
|
||||
FakeHost.WorldName = "TestWorld";
|
||||
var dash = new LegacyDashboardRenderer(FakeHost.Create());
|
||||
FakeHost.WorldName = "TestWorld";
|
||||
dash.LoadSettings("Tester");
|
||||
s = (LegacyUiSettings)typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.GetValue(dash)!;
|
||||
return dash;
|
||||
}
|
||||
|
||||
private static MonsterRule DefaultRow(LegacyUiSettings s) =>
|
||||
s.MonsterRules.Single(r => r.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static void Select(LegacyDashboardRenderer dash, string profile) =>
|
||||
dash.SelectProfileAtIndex(3, Array.IndexOf(dash.ReadDashboardFiles().Profiles, profile));
|
||||
|
||||
private static string PackSetup(LegacyDashboardRenderer dash) =>
|
||||
typeof(LegacyDashboardRenderer).GetField("_packSetup", Any)!.GetValue(dash)!.ToString()!;
|
||||
|
||||
/// <summary>A T10 profile in use: Default's off hand set, two named rules, a weapon, a kit, a buff row, Monster Range 33.</summary>
|
||||
private static LegacyDashboardRenderer T10(out LegacyUiSettings s)
|
||||
{
|
||||
var dash = Login(out s);
|
||||
DefaultRow(s).OffhandId = HandWraps;
|
||||
s.MonsterRules.Add(new MonsterRule { Name = "Tusker", Priority = 3 });
|
||||
s.MonsterRules.Add(new MonsterRule { Name = "Olthoi", Priority = 4 });
|
||||
s.ItemRules.Add(new ItemRule { Id = Sword, Name = "T10 Sword", Action = "Weapon" });
|
||||
s.ConsumableRules.Add(new ConsumableRule { Id = Kit, Name = "Healing Kit", Type = "Heal" });
|
||||
s.BuffRules.Add(new BuffRule { SpellName = "Strength Self VII" });
|
||||
s.MonsterRange = 33;
|
||||
s.ProfileItemsChecked = true;
|
||||
dash.SaveMonsterRules();
|
||||
ProfileResult r = dash.SaveProfileAs(ProfileKind.Settings, "T10", replace: false);
|
||||
Check.True(r.Ok, "Save As T10: " + r.Text);
|
||||
Check.Eq(s.SelectedProfile, "T10", "T10 in use");
|
||||
return dash;
|
||||
}
|
||||
|
||||
private static void ResetUnit()
|
||||
{
|
||||
var s = new LegacyUiSettings { MonsterRange = 41 };
|
||||
s.MonsterRules.Add(new MonsterRule { Name = "Tusker" });
|
||||
s.MonsterRules.Add(new MonsterRule { Name = "default", OffhandId = HandWraps });
|
||||
s.ItemRules.Add(new ItemRule { Id = Sword, Name = "T10 Sword" });
|
||||
s.ConsumableRules.Add(new ConsumableRule { Id = Kit, Name = "Healing Kit" });
|
||||
s.BuffRules.Add(new BuffRule { SpellName = "Strength Self VII" });
|
||||
s.ProfileItemsChecked = true;
|
||||
var oldMonsters = s.MonsterRules;
|
||||
|
||||
LegacyDashboardRenderer.ResetForFreshProfile(s);
|
||||
Check.Eq(s.MonsterRules.Count, 1, "one rule left");
|
||||
Check.Eq(s.MonsterRules[0].OffhandId, HandWraps, "the Default row itself is kept, as it was");
|
||||
Check.Eq(oldMonsters.Count, 2, "a new list: the old one isn't emptied under a reader");
|
||||
Check.Eq(s.ItemRules.Count + s.ConsumableRules.Count + s.BuffRules.Count, 0, "items, consumables and the buff rows emptied");
|
||||
Check.False(s.ProfileItemsChecked, "the weapons are filled from the pack again");
|
||||
Check.Eq(s.MonsterRange, 41, "other settings kept");
|
||||
|
||||
var none = LegacyDashboardRenderer.DefaultRuleOnly(new() { new MonsterRule { Name = "Tusker" } });
|
||||
Check.Eq(none.Count, 1, "no Default row: one is made");
|
||||
Check.Eq(none[0].Name, "Default", "named Default");
|
||||
Check.Eq(LegacyDashboardRenderer.NamedMonsterRules(none), 0, "Default isn't counted as a monster rule");
|
||||
}
|
||||
|
||||
private static void CopySays()
|
||||
{
|
||||
using var t = new Scratch("copy");
|
||||
var dash = T10(out var s);
|
||||
ProfileResult r = dash.SaveProfileAs(ProfileKind.Settings, "T11", replace: false);
|
||||
Check.True(r.Ok, "Save As T11");
|
||||
Check.Eq(r.Text, "[RynthAi] New profile 'T11': a copy of 'T10' (2 monster rules).", "the chat line");
|
||||
Check.Eq(s.MonsterRules.Count, 3, "a copy keeps the monster rules");
|
||||
Check.Eq(s.ItemRules.Count, 1, "and the weapons");
|
||||
|
||||
Select(dash, "T10");
|
||||
r = dash.SaveProfileAs(ProfileKind.Settings, "T11", replace: true);
|
||||
Check.Eq(r.Text, "[RynthAi] Profile 'T11' replaced with a copy of 'T10' (2 monster rules).", "a replace says so");
|
||||
}
|
||||
|
||||
private static void FreshProfile()
|
||||
{
|
||||
using var t = new Scratch("fresh");
|
||||
var dash = T10(out var s);
|
||||
ProfileResult r = dash.NewProfile(ProfileKind.Settings, "T11");
|
||||
Check.True(r.Ok, "New T11: " + r.Text);
|
||||
Check.Eq(r.Text, "[RynthAi] New profile 'T11': fresh (no monsters or items; weapons fill from your pack).", "the chat line");
|
||||
Check.Eq(s.SelectedProfile, "T11", "T11 in use");
|
||||
Check.Eq(s.MonsterRules.Count, 1, "only the Default row");
|
||||
Check.Eq(DefaultRow(s).OffhandId, HandWraps, "Default as it was");
|
||||
Check.Eq(s.ItemRules.Count, 0, "no weapons yet");
|
||||
Check.Eq(s.ConsumableRules.Count, 0, "no consumables yet");
|
||||
Check.Eq(s.BuffRules.Count, 0, "no per-profile buff rows");
|
||||
Check.Eq(s.MonsterRange, 33, "Monster Range kept");
|
||||
Check.Eq(PackSetup(dash), "FillNew", "weapons and consumables fill from the pack, as a new profile's do");
|
||||
|
||||
string json = t.Profile("T11");
|
||||
Check.False(json.Contains("Tusker") || json.Contains("T10 Sword"), "T11.json holds no T10 monsters or weapons");
|
||||
Check.Eq(t.Tag, "T11", "the Monsters file is T11's");
|
||||
Check.False(File.ReadAllText(t.MonstersFile).Contains("Tusker"), "and holds only Default");
|
||||
|
||||
Select(dash, "T10");
|
||||
Check.Eq(s.SelectedProfile, "T10", "back on T10");
|
||||
Check.Eq(s.MonsterRules.Count, 3, "T10 kept its monster rules");
|
||||
Check.Eq(s.ItemRules.Count, 1, "and its weapon");
|
||||
Check.Eq(s.ConsumableRules.Count, 1, "and its kit");
|
||||
|
||||
Select(dash, "T11");
|
||||
Check.Eq(s.MonsterRules.Count, 1, "T11 is still fresh after a switch");
|
||||
}
|
||||
|
||||
private static void FreshRefusesExisting()
|
||||
{
|
||||
using var t = new Scratch("fresh-exists");
|
||||
var dash = T10(out var s);
|
||||
Check.True(dash.SaveProfileAs(ProfileKind.Settings, "T11", replace: false).Ok, "a T11 copy");
|
||||
Select(dash, "T10");
|
||||
string before = t.Profile("T11");
|
||||
|
||||
ProfileResult r = dash.NewProfile(ProfileKind.Settings, "T11");
|
||||
Check.False(r.Ok, "New over an existing profile is refused");
|
||||
Check.True(r.Text.Contains("already exists"), r.Text);
|
||||
Check.Eq(t.Profile("T11"), before, "T11 untouched");
|
||||
Check.Eq(s.SelectedProfile, "T10", "T10 still in use");
|
||||
Check.Eq(s.MonsterRules.Count, 3, "with its rules");
|
||||
Check.False(dash.NewProfile(ProfileKind.Settings, "monsters").Ok, "a name RynthAi keeps is refused");
|
||||
Check.False(dash.NewProfile(ProfileKind.Settings, " ").Ok, "a blank name is refused");
|
||||
Check.Eq(s.ItemRules.Count, 1, "nothing was reset");
|
||||
}
|
||||
|
||||
private static void ClearList()
|
||||
{
|
||||
using var t = new Scratch("clear");
|
||||
var dash = T10(out var s);
|
||||
ProfileResult r = dash.ClearMonsterRules();
|
||||
Check.True(r.Ok, "Clear list: " + r.Text);
|
||||
Check.Eq(r.Text, "[RynthAi] Cleared the Monsters list of profile 'T10': removed 2 monster rules; the Default row stays.", "the chat line");
|
||||
Check.Eq(s.MonsterRules.Count, 1, "only Default left");
|
||||
Check.Eq(DefaultRow(s).OffhandId, HandWraps, "the Default row as it was");
|
||||
Check.Eq(s.ItemRules.Count, 1, "the weapons stay");
|
||||
Check.False(t.Profile("T10").Contains("Tusker"), "saved to T10.json at once");
|
||||
Check.False(File.ReadAllText(t.MonstersFile).Contains("Tusker"), "and to the Monsters file");
|
||||
Check.Eq(t.Tag, "T10", "tagged T10");
|
||||
Check.Eq(dash.ProfileInfo(ProfileKind.Settings).MonsterRules, 0, "the PROFILE menu counts no rules");
|
||||
|
||||
Check.True(dash.ClearMonsterRules().Text.Contains("nothing to clear"), "a second clear has nothing to do");
|
||||
|
||||
Login(out s);
|
||||
Check.Eq(s.SelectedProfile, "T10", "relogged on T10");
|
||||
Check.Eq(s.MonsterRules.Count, 1, "still cleared after a relog");
|
||||
Check.Eq(DefaultRow(s).OffhandId, HandWraps, "Default kept after a relog");
|
||||
}
|
||||
|
||||
private static void CommandsAndVerbs()
|
||||
{
|
||||
using var t = new Scratch("commands");
|
||||
var dash = T10(out var s);
|
||||
Check.Eq(dash.ProfileInfo(ProfileKind.Settings).MonsterRules, 2, "the PROFILE menu counts T10's two rules");
|
||||
Check.Eq(dash.ProfileInfo(ProfileKind.Nav).MonsterRules, -1, "other kinds have no Monsters list");
|
||||
var plugin = new RynthAiPlugin();
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
|
||||
typeof(RynthAiPlugin).GetField("_dashboard", Any)!.SetValue(plugin, dash);
|
||||
MethodInfo dispatch = typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!;
|
||||
string Ra(string line)
|
||||
{
|
||||
FakeHost.Chat.Clear();
|
||||
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
dispatch.Invoke(plugin, new object[] { parts[1].ToLowerInvariant(), parts, 0 });
|
||||
return string.Join(" / ", FakeHost.Chat);
|
||||
}
|
||||
|
||||
string chat = Ra("/ra settings saveas T10 Copy");
|
||||
Check.True(chat.Contains("New profile 'T10 Copy': a copy of 'T10' (2 monster rules)."), "/ra settings saveas copies: " + chat);
|
||||
Check.Eq(s.MonsterRules.Count, 3, "the copy has T10's rules");
|
||||
chat = Ra("/ra settings new T11");
|
||||
Check.True(chat.Contains("New profile 'T11': fresh"), "/ra settings new: " + chat);
|
||||
Check.Eq(s.MonsterRules.Count, 1, "fresh");
|
||||
chat = Ra("/ra settings new");
|
||||
Check.True(chat.Contains("needs a name") && chat.Contains("new <name>"), "no name: why + usage: " + chat);
|
||||
|
||||
Select(dash, "T10");
|
||||
var run = typeof(RynthAiPlugin).GetMethod("RunProfileAction", Any)!;
|
||||
var r = (ProfileResult)run.Invoke(plugin, new object?[] { ProfileKind.Settings, ProfileVerb.ClearMonsters, "", false })!;
|
||||
Check.True(r.Ok && r.Text.Contains("removed 2 monster rules"), "the menu's Clear list verb: " + r.Text);
|
||||
r = (ProfileResult)run.Invoke(plugin, new object?[] { ProfileKind.Nav, ProfileVerb.ClearMonsters, "", false })!;
|
||||
Check.False(r.Ok, "only a settings profile has a Monsters list");
|
||||
}
|
||||
}
|
||||
|
|
@ -36,6 +36,10 @@ internal static class SpellCatalogTests
|
|||
r.Add("built-in buffs (R-20261119-195743-1993): Mana Conversion Mastery right after the four that raise casting skill, before the rest", ManaConversionEarly);
|
||||
r.Add("buff profile: a profile spell casts the best level known", ProfileResolvesTier);
|
||||
r.Add("buff profile: a name with no tier ladder falls back to its spell family", ProfileFamilyFallback);
|
||||
// Spotted by SilentKelpie (rynth PR #12); re-implemented here.
|
||||
r.Add("buffing: never a heal for health, stamina or mana, nor a dispel (list or profile); lasting boosts stay", BuffingNeverHealsOrDispels);
|
||||
r.Add("fellowship buffs: only with the setting on and in a fellowship; capped by the skill, never below the self level, refused levels passed over", FellowshipBuffs);
|
||||
r.Add("fellowship buffs: UseFellowshipBuffs defaults off, loads, saves, bridges, is in the settings map", FellowshipBuffsSetting);
|
||||
r.Add("buff profile: Loaded Files lists profiles, picks one by index, and the snapshot reports it", LoadedFilesPicker);
|
||||
}
|
||||
|
||||
|
|
@ -281,4 +285,146 @@ internal static class SpellCatalogTests
|
|||
dash.SelectProfileAtIndex(4, 0);
|
||||
Check.Eq(dash.Settings.CurrentBuffProfilePath, "", "index 0 goes back to the built-in list");
|
||||
});
|
||||
|
||||
private static void BuffingNeverHealsOrDispels()
|
||||
{
|
||||
SpellCatalog.EnsureLoaded();
|
||||
int Named(string n) => SpellCatalog.GetByName(n)?.Id ?? 0;
|
||||
foreach (string n in new[] { "Heal Self VI", "Revitalize Self VI", "Mana Boost Self VI", "Stamina to Mana Self VI",
|
||||
"Incantation of Heal Self", "Evaporate All Magic Other" })
|
||||
{
|
||||
Check.True(Named(n) != 0, $"{n} is in the catalog");
|
||||
Check.False(BuffManager.IsLastingBuff(Named(n)), $"{n} is never cast as a buff");
|
||||
}
|
||||
int dispels = 0;
|
||||
foreach (var c in SpellCatalog.All)
|
||||
if (c.FamilyName.Contains("Dispel", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
dispels++;
|
||||
if (BuffManager.IsLastingBuff(c.Id)) Check.True(false, $"dispel {c.Name} ({c.Id}) counted as a buff");
|
||||
}
|
||||
Check.True(dispels > 10, $"every dispel in the catalog is refused ({dispels})");
|
||||
foreach (string n in new[] { "Strength Self VI", "Regeneration Self VI", "Rejuvenation Self VI", "Mana Renewal Self VI",
|
||||
"Blade Bane VI", "Aura of Blood Drinker Self VI" })
|
||||
Check.True(BuffManager.IsLastingBuff(Named(n)), $"{n} stays a buff");
|
||||
|
||||
// A spell the catalog doesn't know goes by name.
|
||||
foreach (string n in new[] { "Heal Self IX", "Mana to Health Other II", "Extinguish All Magic Self", "Dispel Creature" })
|
||||
Check.True(BuffManager.IsVitalOrDispelName(n), $"by name: {n} is a heal or dispel");
|
||||
foreach (string n in new[] { "Mana Renewal Self IX", "Regeneration Other", "Strength Self", "" })
|
||||
Check.False(BuffManager.IsVitalOrDispelName(n), $"by name: '{n}' is not");
|
||||
|
||||
// The built-in list, every spell known at skill 500: none of these is ever picked.
|
||||
var all = new System.Collections.Generic.List<int>();
|
||||
foreach (var c in SpellCatalog.All) all.Add(c.Id);
|
||||
var buffs = NewBuffs(500, all.ToArray());
|
||||
foreach (string buff in buffs.BuildBuiltInBuffList())
|
||||
{
|
||||
int id = buffs.FindBestSpellId(buff, buffs.SkillFor(buff));
|
||||
if (id != 0 && !BuffManager.IsLastingBuff(id)) Check.True(false, $"built-in {buff} resolved to a heal or dispel ({id})");
|
||||
}
|
||||
|
||||
// A profile that names Mana Boost and Heal Self: left out, and logged once.
|
||||
buffs = NewBuffs(500, all.ToArray());
|
||||
var profile = new BuffProfile { Name = "heals" };
|
||||
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(Named("Mana Boost Self VI"))));
|
||||
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(Named("Heal Self VI"))));
|
||||
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(Named("Regeneration Self VI"))));
|
||||
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthSelfVI)));
|
||||
buffs.ApplyBuffProfile(profile);
|
||||
Check.Eq(buffs.ActiveBuffProfileCount, 2, "only the two buffs are in use");
|
||||
Check.False(buffs.BuildDynamicBuffList().Any(b => b.Contains("Mana Boost") || b.Contains("Heal Self")), "the heals are not in the list");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("left out") && l.Contains("Mana Boost Self VI") && l.Contains("Heal Self VI")), "logged what was left out");
|
||||
Check.Eq(buffs.FindBestSpellId("Mana Boost Self", AcSkillType.LifeMagic), 0, "and the picker never resolves Mana Boost for buffing");
|
||||
}
|
||||
|
||||
private const int GreaterEmpoweringConclave = 3177, SuperiorEmpoweringConclave = 3178;
|
||||
|
||||
private static void FellowshipBuffs()
|
||||
{
|
||||
SpellCatalog.EnsureLoaded();
|
||||
Check.True(BuffManager.IsFellowshipSpell(Spell(SuperiorEmpoweringConclave)), "Superior Empowering the Conclave is a fellowship spell");
|
||||
Check.False(BuffManager.IsFellowshipSpell(Spell(MightOfTheLugians)), "Might of the Lugians is not");
|
||||
Check.Eq(Spell(SuperiorEmpoweringConclave).FamilyId, StrengthFamily, "same family as Strength Self");
|
||||
|
||||
bool inFellow = true;
|
||||
BuffManager Rig(int buffed, bool on, params int[] known)
|
||||
{
|
||||
var b = NewBuffs(buffed, known);
|
||||
Settings(b).UseFellowshipBuffs = on;
|
||||
b.InFellowship = () => inFellow;
|
||||
return b;
|
||||
}
|
||||
int Pick(BuffManager b) => b.FindBestSpellId("Strength Self", AcSkillType.CreatureEnchantment);
|
||||
|
||||
int[] all = { StrengthSelfVI, MightOfTheLugians, GreaterEmpoweringConclave, SuperiorEmpoweringConclave };
|
||||
Check.Eq(Pick(Rig(500, on: false, all)), MightOfTheLugians, "setting off: the self buff");
|
||||
Check.Eq(Pick(Rig(500, on: true, all)), SuperiorEmpoweringConclave, "on, in a fellowship, skill 500: the level-7 fellowship version");
|
||||
inFellow = false;
|
||||
Check.Eq(Pick(Rig(500, on: true, all)), MightOfTheLugians, "solo: never");
|
||||
inFellow = true;
|
||||
Check.Eq(Pick(Rig(300, on: true, all)), GreaterEmpoweringConclave, "skill 300 (tier 6): the level-6 fellowship version, as the self buff is VI");
|
||||
Check.Eq(Pick(Rig(500, on: true, StrengthSelfVI, MightOfTheLugians, GreaterEmpoweringConclave)), MightOfTheLugians,
|
||||
"only a lower fellowship level known: the self buff (never weaker)");
|
||||
Check.Eq(Pick(Rig(500, on: true, StrengthSelfVI, MightOfTheLugians)), MightOfTheLugians, "no fellowship version known: the self buff");
|
||||
|
||||
var refused = Rig(500, on: true, all);
|
||||
Spells(refused).MarkNoComponents(SuperiorEmpoweringConclave);
|
||||
Check.Eq(Pick(refused), MightOfTheLugians, "the fellowship level refused for components: the self buff (the lower fellowship level is weaker)");
|
||||
|
||||
// A buff profile goes through the same picker; its family fallback never picks a fellowship spell itself.
|
||||
var prof = Rig(500, on: false, all);
|
||||
var profile = new BuffProfile { Name = "fellow" };
|
||||
profile.Entries.Add(BuffProfileStore.EntryFor(Spell(StrengthOtherVI)));
|
||||
prof.ApplyBuffProfile(profile);
|
||||
Check.Eq(Pick(prof), MightOfTheLugians, "profile, setting off: the self buff");
|
||||
Settings(prof).UseFellowshipBuffs = true;
|
||||
Check.Eq(Pick(prof), SuperiorEmpoweringConclave, "profile, setting on: the fellowship version");
|
||||
|
||||
// The fellowship version's level is the catalog's, not the name's (no numeral in its name).
|
||||
Check.Eq(BuffManager.GetSpellLevel(SpellTableStub.GetById(SuperiorEmpoweringConclave)!), 7, "Superior Empowering the Conclave is level 7");
|
||||
int volition = SpellCatalog.GetByName("Superior Volition of the Conclave")!.Id;
|
||||
Check.Eq(BuffManager.GetSpellLevel(SpellTableStub.GetById(volition)!), 7, "Superior Volition of the Conclave is 7, not V");
|
||||
}
|
||||
|
||||
private static LegacyUiSettings Settings(BuffManager b) =>
|
||||
(LegacyUiSettings)typeof(BuffManager).GetField("_settings", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(b)!;
|
||||
|
||||
private static SpellManager Spells(BuffManager b) =>
|
||||
(SpellManager)typeof(BuffManager).GetField("_spellManager", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(b)!;
|
||||
|
||||
private static void FellowshipBuffsSetting()
|
||||
{
|
||||
Check.False(new LegacyUiSettings().UseFellowshipBuffs, "a new profile: off");
|
||||
var on = System.Text.Json.JsonSerializer.Deserialize(
|
||||
System.Text.Json.JsonSerializer.Serialize(new LegacyUiSettings { UseFellowshipBuffs = true }, RynthAiJsonContext.Default.LegacyUiSettings),
|
||||
RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(on != null && on.UseFellowshipBuffs, "on is saved and loaded");
|
||||
var copy = typeof(LegacyDashboardRenderer).GetMethod("CopySettings", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)!;
|
||||
var dst = new LegacyUiSettings();
|
||||
copy.Invoke(null, new object[] { new LegacyUiSettings { UseFellowshipBuffs = true }, dst });
|
||||
Check.True(dst.UseFellowshipBuffs, "a profile with it on loads on");
|
||||
|
||||
var payload = System.Text.Json.JsonSerializer.Deserialize("{\"PatrolOnLogin\":false}", RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(payload != null && payload.UseFellowshipBuffs == null, "an older engine's payload has no value");
|
||||
var s = new LegacyUiSettings { UseFellowshipBuffs = true };
|
||||
var dash = (LegacyDashboardRenderer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true);
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.SetValue(dash, s);
|
||||
typeof(LegacyDashboardRenderer).GetField("_advancedSettingsUi", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
|
||||
.SetValue(dash, new LegacyAdvancedSettingsUi(s));
|
||||
var sent = System.Text.Json.JsonSerializer.Deserialize(dash.BuildSettingsJson(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||
Check.True(sent != null && sent.UseFellowshipBuffs == true, "sent to the engine face");
|
||||
dash.ApplySettingsJson("{\"PatrolOnLogin\":false}");
|
||||
Check.True(s.UseFellowshipBuffs, "a save without the field leaves it on");
|
||||
dash.ApplySettingsJson("{\"UseFellowshipBuffs\":false}");
|
||||
Check.False(s.UseFellowshipBuffs, "a save with it off turns it off");
|
||||
|
||||
var live = new LegacyUiSettings();
|
||||
var map = ExpressionTests.Engine(settings: live).BuildSettingsMapPublic();
|
||||
Check.True(map.TryGetValue("UseFellowshipBuffs", out var entry), "in the settings map");
|
||||
Check.Eq(entry.Get(), "0", "reads off");
|
||||
entry.Set("1");
|
||||
Check.True(live.UseFellowshipBuffs, "and sets on");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -401,8 +401,14 @@ internal static class VTankLootTests
|
|||
Check.False(MC(robe, ctx, C(N.SlotExactPalette, "0", "22136")), "wrong palette for the slot");
|
||||
Check.False(MC(robe, ctx, C(N.SlotExactPalette, "2", "4660")), "slot past the end");
|
||||
Check.False(MC(robe, ctx, C(N.SlotExactPalette, "-1", "4660")), "negative slot");
|
||||
// 2026-11-28: with an engine that reads palettes, an item it has none for (the client released
|
||||
// or deleted it) fails: a Legendary Chest's plain 'Helmet' matched "PP Olthoi Helm" that way.
|
||||
var plain = new Item("Plain");
|
||||
Check.True(MC(plain, ctx, C(N.SlotExactPalette, "5", "1")), "an item with no palette data passes");
|
||||
Check.False(MC(plain, ctx, C(N.SlotExactPalette, "5", "1")), "an item with no palette data fails where the engine reads palettes");
|
||||
Check.False(MC(plain, ctx, C(N.SlotExactPalette, "0", "3665")), "whatever the slot and palette");
|
||||
// The palettes come back (the object is created again): judged on them.
|
||||
FakeHost.Palettes[unchecked((uint)plain.Wo.Id)] = new uint[] { 0x04000E51 };
|
||||
Check.True(MC(plain, new VTankLootContext(FakeHost.Create(), Player), C(N.SlotExactPalette, "0", "3665")), "palettes read again: 0xE51 = 3665 matches");
|
||||
}
|
||||
|
||||
private static void MalformedData()
|
||||
|
|
|
|||
164
Tools/RynthDefective.Tests/AppraisalTests.cs
Normal file
164
Tools/RynthDefective.Tests/AppraisalTests.cs
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthDefective.Appraisal;
|
||||
using RynthCore.Plugin.RynthDefective.Model;
|
||||
|
||||
namespace RynthDefective.Tests
|
||||
{
|
||||
// The Appraisal window's words (2026-11-28): retail's examine lines for a weapon, armor, a caster, a
|
||||
// creature and a player, the wield requirements, the flags, and the "All properties" list.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static AppraisalInput Item(uint itemType, params (uint Key, int Value)[] ints)
|
||||
{
|
||||
var o = new AppraisalInput { Id = 0x8000_1234, Name = "Test Item", ItemType = itemType, Identified = true, SpellName = SpellTable.Name };
|
||||
o.Ints[1] = (int)itemType;
|
||||
foreach (var (k, v) in ints) o.Ints[k] = v;
|
||||
return o;
|
||||
}
|
||||
|
||||
private static List<string> Lines(AppraisalDoc d, string section) =>
|
||||
d.Sections.FirstOrDefault(s => s.Title == section)?.Lines.Select(l => l.Text).ToList() ?? new List<string>();
|
||||
|
||||
private static void AppraiseWeapon()
|
||||
{
|
||||
// A heavy sword: 50 max, variance 0.5, slash/pierce, speed 35, +12% attack, +15% melee defense.
|
||||
var o = Item(0x1, (19, 12345), (5, 150), (48, 0x2C), (353, 2), (44, 50), (45, 0x3), (49, 35),
|
||||
(158, 1), (159, 0x2C), (160, 400), (270, 7), (272, 180), (105, 8), (131, 64), (265, 13), (370, 3), (372, 1), (179, 0x4), (166, 1));
|
||||
o.Floats[22] = 0.5; o.Floats[62] = 1.12; o.Floats[29] = 1.15; o.Floats[138] = 2.5;
|
||||
o.Spells.Add(6);
|
||||
AppraisalDoc d = AppraisalText.Build(o);
|
||||
|
||||
Eq(d.Kind, "Heavy Weapons (Sword)", "kind");
|
||||
Check(d.Facts.Contains(("Value", "12,345")) && d.Facts.Contains(("Burden", "150")), "value and burden: " + string.Join("; ", d.Facts));
|
||||
var w = Lines(d, "Weapon");
|
||||
Check(w.Contains("Skill: Heavy Weapons (Sword)"), "skill line: " + string.Join(" | ", w));
|
||||
Check(w.Contains("Damage: 25 - 50, Slashing/Piercing"), "damage line");
|
||||
Check(w.Contains("Speed: Average (35)"), "speed line");
|
||||
Check(w.Contains("Bonus to Attack Skill: +12%."), "attack bonus");
|
||||
Check(w.Contains("Bonus to Melee Defense: +15%."), "melee defense bonus");
|
||||
Check(w.Contains("Slayer: Olthoi (x2.5 damage)"), "slayer");
|
||||
Check(w.Contains("Imbued: Armor Rending"), "imbue");
|
||||
var r = Lines(d, "Requirements");
|
||||
Check(r.Contains("Wield requires Heavy Weapons 400") && r.Contains("Wield requires level 180"), "wield lines: " + string.Join(" | ", r));
|
||||
var p = Lines(d, "Properties");
|
||||
Check(p.Contains("Workmanship: Utterly flawless (8)") && p.Contains("Material: Steel") && p.Contains("Set: Soldier's Set"), "workmanship, material, set: " + string.Join(" | ", p));
|
||||
Check(p.Contains("Ratings: Damage +3, Crit +1"), "ratings");
|
||||
Check(Lines(d, "Magic").Contains("Spells: Heal Self I"), "spells by name");
|
||||
Check(!d.IsCreature && d.Bars.Count == 0, "an item without mana has no bars");
|
||||
}
|
||||
|
||||
private static void AppraiseArmorAndMana()
|
||||
{
|
||||
var o = Item(0x2, (28, 600), (4, 0x0400 | 0x0800 | 0x1000 | 0x2000), (107, 1234), (108, 2000), (106, 400), (109, 300), (33, 1), (114, 1), (36, 9999));
|
||||
o.Floats[13] = 1.2; o.Floats[14] = 0.6; o.Floats[5] = -1.0 / 20.0;
|
||||
o.Bools[91] = true;
|
||||
AppraisalDoc d = AppraisalText.Build(o);
|
||||
|
||||
Eq(d.Kind, "Armor", "kind");
|
||||
var a = Lines(d, "Armor");
|
||||
Check(a.Contains("Armor Level: 600") && a.Contains("Slashing: Above Average (720)") && a.Contains("Piercing: Below Average (360)"), "protections: " + string.Join(" | ", a));
|
||||
Check(a.Contains("Covers: Chest, Abdomen, Upper Arms, Lower Arms"), "coverage");
|
||||
var m = Lines(d, "Magic");
|
||||
Check(m.Contains("Mana: 1,234 / 2,000") && m.Contains("Mana Cost: 1 point per 20 seconds.") && m.Contains("Spellcraft: 400."), "mana lines: " + string.Join(" | ", m));
|
||||
Check(Lines(d, "Requirements").Contains("Activation requires Arcane Lore: 300"), "arcane lore");
|
||||
Check(Lines(d, "Properties").Contains("Properties: Bonded, Attuned (can't be given), Retained, Unenchantable"), "flags: " + string.Join(" | ", Lines(d, "Properties")));
|
||||
Check(d.Bars.Count == 1 && d.Bars[0].Kind == AppraiseBarKind.Mana && d.Bars[0].Current == 1234 && d.Bars[0].Max == 2000, "the mana bar");
|
||||
}
|
||||
|
||||
private static void AppraiseCaster()
|
||||
{
|
||||
var o = Item(0x8000, (45, 0x10));
|
||||
o.Floats[144] = 0.05; o.Floats[152] = 1.15; o.Floats[150] = 1.10;
|
||||
AppraisalDoc d = AppraisalText.Build(o);
|
||||
var c = Lines(d, "Caster");
|
||||
Check(c.Contains("Bonus to Mana Conversion: +5%."), "mana conversion: " + string.Join(" | ", c));
|
||||
Check(c.Contains("Damage bonus for Fire spells: +15% vs. Monsters, +3.75% vs. Players."), "elemental bonus");
|
||||
Check(c.Contains("Bonus to Magic Defense: +10%."), "magic defense");
|
||||
}
|
||||
|
||||
private static void AppraiseCreatureAndPlayer()
|
||||
{
|
||||
var m = Item(0x10, (25, 112), (2, 1));
|
||||
m.Name = "Olthoi Soldier";
|
||||
m.Vitals = (500, 1000, 200, 400, 0, 0);
|
||||
m.HealthRatio = 0.4f;
|
||||
m.Attributes = new uint[] { 200, 180, 190, 210, 100, 90 };
|
||||
m.EnchantBits = (1u << 0) | (1u << 16) | (1u << 3); // Strength up, Coordination down
|
||||
AppraisalDoc d = AppraisalText.Build(m);
|
||||
Check(d.IsCreature, "a creature");
|
||||
Eq(d.Kind, "Level 112 · Olthoi", "creature kind");
|
||||
Check(d.Bars.Count == 2 && d.Bars[0].Label == "Health" && Math.Abs(d.Bars[0].Ratio - 0.4f) < 1e-6 && d.Bars[1].Label == "Stamina", "health (the server's ratio) and stamina; no mana bar without max mana");
|
||||
Check(d.Attributes.Count == 6 && d.Attributes[0] == ("Strength", 200u, true, true) && d.Attributes[3] == ("Coordination", 210u, true, false), "attributes and their buffs");
|
||||
Check(d.Facts.Count == 0, "no value or burden for a creature");
|
||||
|
||||
var p = Item(0x10, (25, 275), (188, 1), (113, 1), (134, 4), (30, 5));
|
||||
p.IsPlayer = true;
|
||||
p.Strings[2] = "the Bold"; p.Strings[47] = "Test Allegiance";
|
||||
AppraisalDoc pd = AppraisalText.Build(p);
|
||||
Eq(pd.Kind, "Level 275 · Aluvian Male", "player kind");
|
||||
var c = Lines(pd, "Character");
|
||||
Check(c.Contains("Title: the Bold") && c.Contains("Player Killer") && c.Contains("Allegiance: Test Allegiance") && c.Contains("Rank: 5"), "character lines: " + string.Join(" | ", c));
|
||||
|
||||
var unknown = Item(0x10);
|
||||
unknown.Identified = false;
|
||||
AppraisalDoc ud = AppraisalText.Build(unknown);
|
||||
Check(ud.Sections.Any(s => s.Lines.Any(l => l.Text.StartsWith("Not assessed yet", StringComparison.Ordinal))), "an unassessed creature says so");
|
||||
}
|
||||
|
||||
private static void AppraiseWordsAndRaw()
|
||||
{
|
||||
Eq(AppraisalText.WieldLine(8, 0x0B, 3), "Wield requires specialized Sword", "training requirement");
|
||||
Eq(AppraisalText.WieldLine(3, 1, 200), "Wield requires Strength 200", "attribute requirement");
|
||||
Eq(AppraisalText.WieldLine(12, 0, 3), "Wield requires Sho race", "heritage requirement");
|
||||
Eq(AppraisalText.SpeedName(10), "Very Fast", "speed 10");
|
||||
Eq(AppraisalText.SpeedName(80), "Very Slow", "speed 80");
|
||||
Eq(AppraisalText.Pct(0.0375), "+3.75%", "a fractional percent");
|
||||
Eq(AppraisalText.Pct(-0.05), "-5%", "a negative percent");
|
||||
Eq(AppraisalText.Coverage(0x4000 | 0x8000 | 0x10000), "Head, Hands, Feet", "coverage order");
|
||||
|
||||
var o = Item(0x8, (19, 10));
|
||||
o.Strings[16] = "A long description.";
|
||||
o.Floats[5] = -0.05;
|
||||
o.DataIds[37] = 0x21; // ItemSkillLimit: Life Magic
|
||||
o.Ints[115] = 250;
|
||||
o.InstanceIds[2] = 0x5000_0001;
|
||||
o.Spells.Add(6);
|
||||
AppraisalDoc d = AppraisalText.Build(o);
|
||||
Eq(d.Description, "A long description.", "the long description");
|
||||
Check(Lines(d, "Requirements").Contains("Activation requires Life Magic: 250"), "activation skill");
|
||||
Check(d.Raw.Any(r => r.Kind == "Int" && r.Key == 19 && r.Name == "Value" && r.Value == "10"), "raw: an int by name");
|
||||
Check(d.Raw.Any(r => r.Kind == "Float" && r.Name == "ManaRate" && r.Value == "-0.05"), "raw: a float");
|
||||
Check(d.Raw.Any(r => r.Kind == "InstanceId" && r.Value == "0x50000001"), "raw: an instance id");
|
||||
Check(d.Raw.Any(r => r.Kind == "Spell" && r.Name == "Heal Self I"), "raw: the spell by name");
|
||||
int ints = d.Raw.Count(r => r.Kind == "Int");
|
||||
Eq(ints, o.Ints.Count, "every int listed once");
|
||||
string text = d.ToText();
|
||||
Check(text.StartsWith("Test Item", StringComparison.Ordinal) && text.Contains("Value: 10") && text.Contains("A long description."), "copy as text");
|
||||
}
|
||||
|
||||
private static void AppraiseCommand()
|
||||
{
|
||||
DefCommand c = DefCommandParser.Parse("appraisal");
|
||||
Check(c.Verb == DefVerb.Appraisal && c.Text == "", "/rdef appraisal");
|
||||
c = DefCommandParser.Parse("appraise pin");
|
||||
Check(c.Verb == DefVerb.Appraisal && c.Text == "pin", "/rdef appraise pin");
|
||||
c = DefCommandParser.Parse("examine 0x80001234");
|
||||
Check(c.Verb == DefVerb.Appraisal && c.Text == "0x80001234", "/rdef examine <id>");
|
||||
c = DefCommandParser.Parse("appraisal popout");
|
||||
Check(c.Verb == DefVerb.Appraisal && c.Text == "popout", "/rdef appraisal popout");
|
||||
|
||||
// Pop out / dock answers.
|
||||
Check(DefReplies.PoppedOut("Appraisal window", 1).Ok && DefReplies.PoppedOut("Appraisal window", 1).Text.Contains("popped out"), "popped out");
|
||||
Check(DefReplies.PoppedOut("Appraisal window", 0).Ok && DefReplies.PoppedOut("Appraisal window", 0).Text.Contains("docked"), "docked");
|
||||
Check(!DefReplies.PoppedOut("Appraisal window", -1).Ok && DefReplies.PoppedOut("Appraisal window", -1).Text.Contains("open it first"), "not open: says to open it");
|
||||
|
||||
// The pin, in the character's file.
|
||||
var d = new DefData();
|
||||
d.Settings.AppraisalPinned = true;
|
||||
Check(DefStore.Parse(System.Text.Json.JsonDocument.Parse(DefStore.ToJson(d)).RootElement).Settings.AppraisalPinned, "pinned: saved and read");
|
||||
Check(!DefStore.Parse(System.Text.Json.JsonDocument.Parse("{\"settings\":{\"quantityBox\":true}}").RootElement).Settings.AppraisalPinned, "a file from before: not pinned");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -130,6 +130,12 @@ namespace RynthDefective.Tests
|
|||
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);
|
||||
Run("appraisal: a weapon's lines (skill, damage, speed, bonuses, slayer, wield, workmanship, set, ratings)", AppraiseWeapon);
|
||||
Run("appraisal: armor's protections and coverage, mana, spellcraft, the flags", AppraiseArmorAndMana);
|
||||
Run("appraisal: a caster's bonuses", AppraiseCaster);
|
||||
Run("appraisal: a creature's bars and attributes, a player's lines", AppraiseCreatureAndPlayer);
|
||||
Run("appraisal: retail words, activation skill, description, every property, copy", AppraiseWordsAndRaw);
|
||||
Run("appraisal: /rdef appraisal parsing and the pin in the file", AppraiseCommand);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
|
|||
|
|
@ -108,6 +108,7 @@ namespace RynthDefective.Tests
|
|||
("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),
|
||||
("appraisal", DefVerb.Appraisal), ("appraisal pin", DefVerb.Appraisal), ("appraisal popout", DefVerb.Appraisal), ("examine 0x80001234", DefVerb.Appraisal),
|
||||
};
|
||||
var seen = new HashSet<DefVerb>();
|
||||
foreach (var (typed, verb) in right)
|
||||
|
|
|
|||
|
|
@ -53,6 +53,9 @@
|
|||
<Compile Include="..\..\Plugins\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
|
||||
<!-- The Appraisal window's name tables (linked into RynthDefective from RynthAi). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Meta\PropertyNames.cs" Link="Shared\PropertyNames.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\ItemInfo\MagItemInfoTables.cs" Link="Shared\MagItemInfoTables.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
|
|
|||
128
Tools/RynthNav.RouteTests/CustomPortalTests.cs
Normal file
128
Tools/RynthNav.RouteTests/CustomPortalTests.cs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthNav.RouteTests;
|
||||
|
||||
// A custom server's own portals (CustomPortals.cs, 2026-11-27): written down by a scan, learned by taking them, per
|
||||
// server, saved, and planned with on our own graph (PortalRoute) next to the world data's portals.
|
||||
// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunCustomPortals()
|
||||
{
|
||||
Run(nameof(CustomScanAndLearn), CustomScanAndLearn);
|
||||
Run(nameof(CustomKnownPortalNotRelearned), CustomKnownPortalNotRelearned);
|
||||
Run(nameof(CustomPerServerForgetClear), CustomPerServerForgetClear);
|
||||
Run(nameof(CustomSaveAndMerge), CustomSaveAndMerge);
|
||||
Run(nameof(CustomPortalsRoute), CustomPortalsRoute);
|
||||
}
|
||||
|
||||
private static readonly List<PortalLink> BuiltIn = new() { new(10.0, 10.0, -30.0, -30.0, "Portal to the World Data") };
|
||||
private static readonly DateTime T0 = new(2026, 11, 27, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static void CustomScanAndLearn()
|
||||
{
|
||||
var s = new CustomPortalStore();
|
||||
int v0 = s.Version;
|
||||
Check(s.Saw("Test Server", "Portal to the Spire", 9001, 0xA9B40021, 12.5, 30.25, 40.0, 20.0, 30.0, BuiltIn, T0) == CustomSeen.Added, "a scan adds a new one");
|
||||
Check(s.Version > v0, "and it's a change to save");
|
||||
Check(s.Saw("Test Server", "Portal to the Spire", 9001, 0xA9B40021, 12.5, 30.25, 40.0, 20.0, 30.0, BuiltIn, T0) == CustomSeen.Refreshed, "seen again: refreshed");
|
||||
Check(s.Saw("Test Server", "Portal to the World Data", 0, 0xA9B40022, 1, 1, 0, 10.02, 10.01, BuiltIn, T0) == CustomSeen.BuiltIn, "the world data has it: left alone");
|
||||
Check(s.Saw("Test Server", "Some Other Portal", 0, 0xA9B40022, 1, 1, 0, 10.01, 10.0, BuiltIn, T0) == CustomSeen.BuiltIn, "any portal right on a world-data one: left alone");
|
||||
var (saved, routable) = s.Counts("Test Server");
|
||||
Check(saved == 1 && routable == 0, $"one saved, not routable until taken ({saved}, {routable})");
|
||||
Check(s.Links("Test Server").Count == 0, "no link yet");
|
||||
|
||||
CustomLearn r = s.Learned("Test Server", "Portal to the Spire", 9001, 0xA9B40021, 12.5, 30.25, 40.0, 20.0, 30.0,
|
||||
true, -5.5, 60.25, 0, BuiltIn, T0.AddMinutes(1), out CustomPortal? p);
|
||||
Check(r == CustomLearn.New && p != null && p.Routable, "taking it learns the landing");
|
||||
List<PortalLink> links = s.Links("Test Server");
|
||||
Check(links.Count == 1 && links[0].Name == "Portal to the Spire" && links[0].DstNs == -5.5 && links[0].DstEw == 60.25, "a route link");
|
||||
Check(links[0].HasSpot && links[0].Cell == 0xA9B40021 && links[0].Z == 40.0, "the link walks to where the object stood");
|
||||
Check(!links[0].HasRules, "open to anyone (a refusal is learned as for any portal)");
|
||||
|
||||
// A portal never scanned: added when taken.
|
||||
r = s.Learned("Test Server", "Hidden Portal", 0, 0xA9B40023, 2, 2, 0, 21.0, 31.0, true, 50, 50, 0, BuiltIn, T0, out p);
|
||||
Check(r == CustomLearn.New && s.Counts("Test Server").Saved == 2, "an unscanned one is added when taken");
|
||||
// Into a dungeon: kept, listed, not routed.
|
||||
r = s.Learned("Test Server", "Pit Portal", 0, 0xA9B40024, 3, 3, 0, 22.0, 32.0, false, 0, 0, 0x01230105, BuiltIn, T0, out p);
|
||||
Check(r == CustomLearn.New && p != null && !p.Routable && p.Where.Contains("0123"), "a dungeon landing: kept, not routed");
|
||||
Check(s.Links("Test Server").Count == 2, "two map-to-map links");
|
||||
// A world-data portal taken: nothing learned.
|
||||
r = s.Learned("Test Server", "Portal to the World Data", 0, 0xA9B40022, 1, 1, 0, 10.0, 10.0, true, -30, -30, 0, BuiltIn, T0, out p);
|
||||
Check(r == CustomLearn.BuiltIn && p == null, "a world-data portal isn't learned");
|
||||
// Landing right beside it: not a teleport through it.
|
||||
r = s.Learned("Test Server", "Fountain Portal", 0, 0xA9B40025, 1, 1, 0, 23.0, 33.0, true, 23.05, 33.05, 0, BuiltIn, T0, out p);
|
||||
Check(r == CustomLearn.NotAPortal && s.Counts("Test Server").Saved == 3, "a landing beside it isn't learned");
|
||||
}
|
||||
|
||||
private static void CustomKnownPortalNotRelearned()
|
||||
{
|
||||
var s = new CustomPortalStore();
|
||||
s.Learned("S", "Portal A", 0, 0xA9B40021, 1, 1, 0, 20.0, 30.0, true, -5.5, 60.25, 0, null, T0, out _);
|
||||
int v = s.Version;
|
||||
CustomLearn r = s.Learned("S", "Portal A", 0, 0xA9B40021, 1, 1, 0, 20.02, 30.01, true, -5.52, 60.3, 0, null, T0.AddHours(1), out _);
|
||||
Check(r == CustomLearn.AlreadyKnown && s.Version == v, "taken again, same landing: already known, nothing to write");
|
||||
r = s.Learned("S", "Portal A", 0, 0xA9B40021, 1, 1, 0, 20.0, 30.0, true, 40.0, -40.0, 0, null, T0.AddHours(2), out CustomPortal? p);
|
||||
Check(r == CustomLearn.LandingChanged && p!.DestNs == 40.0 && s.Version > v, "a new landing: updated");
|
||||
}
|
||||
|
||||
private static void CustomPerServerForgetClear()
|
||||
{
|
||||
var s = new CustomPortalStore();
|
||||
s.Learned("One", "Gate", 0, 0xA9B40021, 1, 1, 0, 20.0, 30.0, true, -5, 60, 0, null, T0, out _);
|
||||
s.Learned("One", "Gate of Ash", 0, 0xA9B40022, 1, 1, 0, 25.0, 35.0, true, -15, 70, 0, null, T0, out _);
|
||||
s.Learned("Two", "Gate", 0, 0xA9B40021, 1, 1, 0, 20.0, 30.0, true, 45, -60, 0, null, T0, out _);
|
||||
Check(s.Links("One").Count == 2 && s.Links("two").Count == 1, "each server has its own (the name in any case)");
|
||||
Check(s.Links("Three").Count == 0, "another server has none");
|
||||
Check(s.Forget("One", "Gate") == 1 && s.Links("One").Count == 1, "forget: the exact name only, when there is one");
|
||||
Check(s.Forget("One", "ash") == 1 && s.Links("One").Count == 0, "forget: else the names containing it");
|
||||
Check(s.Forget("One", "Nothing") == 0, "forget: none");
|
||||
Check(s.Clear("Two") == 1 && s.All.Count == 0, "clear: that server's all");
|
||||
}
|
||||
|
||||
private static void CustomSaveAndMerge()
|
||||
{
|
||||
var s = new CustomPortalStore();
|
||||
s.Saw("Test Server", "Scanned Only", 77, 0xA9B40021, 10.5, 20.25, 30.0, 20.0, 30.0, null, T0);
|
||||
s.Learned("Test Server", "To Town", 78, 0xA9B40022, 1, 2, 3, 21.0, 31.0, true, -5.5, 60.25, 0, null, T0, out _);
|
||||
s.Learned("Other", "Down", 0, 0xA9B40023, 1, 2, 3, 22.0, 32.0, false, 0, 0, 0x01230105, null, T0, out _);
|
||||
string text = s.Serialize();
|
||||
CustomPortalStore back = CustomPortalStore.Parse(text);
|
||||
Check(back.All.Count == 3, $"three read back ({back.All.Count})");
|
||||
CustomPortal? a = back.Find("Test Server", "Scanned Only", 20.0, 30.0), b = back.Find("Test Server", "To Town", 21.0, 31.0), c = back.Find("Other", "Down", 22.0, 32.0);
|
||||
Check(a != null && !a.DestKnown && a.Wcid == 77 && a.Cell == 0xA9B40021 && a.X == 10.5 && a.Y == 20.25 && a.Z == 30.0, "a scanned one, with its spot");
|
||||
Check(b != null && b.Routable && b.DestNs == -5.5 && b.DestEw == 60.25 && b.LearnedUtc == T0, "a learned one, with its landing");
|
||||
Check(c != null && c.DestKnown && !c.DestOnMap && c.DestCell == 0x01230105, "a dungeon landing");
|
||||
Check(CustomPortalStore.Parse("# notes\n\nbad line\nS\tN\tx\n").All.Count == 0, "notes and bad lines are skipped");
|
||||
Check(CustomPortalStore.Clean("A\tB\nC ") == "A B C", "names are one field");
|
||||
|
||||
// Another client's file: its new portal and later landing are taken in, a portal this one forgot isn't.
|
||||
var mine = CustomPortalStore.Parse(text);
|
||||
mine.Forget("Test Server", "Scanned Only");
|
||||
var disk = CustomPortalStore.Parse(text);
|
||||
disk.Learned("Test Server", "To Town", 78, 0xA9B40022, 1, 2, 3, 21.0, 31.0, true, 44.0, 44.0, 0, null, T0.AddDays(1), out _);
|
||||
disk.Learned("Test Server", "New Elsewhere", 0, 0xA9B40024, 1, 2, 3, 26.0, 36.0, true, -40, 40, 0, null, T0, out _);
|
||||
mine.MergeFrom(disk);
|
||||
Check(mine.Find("Test Server", "Scanned Only", 20.0, 30.0) == null, "what this client forgot stays forgotten");
|
||||
Check(mine.Find("Test Server", "New Elsewhere", 26.0, 36.0) != null, "another client's new portal is taken in");
|
||||
Check(mine.Find("Test Server", "To Town", 21.0, 31.0)!.DestNs == 44.0, "a landing learned later wins");
|
||||
}
|
||||
|
||||
private static void CustomPortalsRoute()
|
||||
{
|
||||
// The world data has no way across; the server's own portal does: the plan takes it (our graph, PortalRoute).
|
||||
var s = new CustomPortalStore();
|
||||
s.Learned("S", "Server Portal", 0, 0xA9B40021, 1, 1, 0, 0.5, 0.5, true, 39.5, 39.5, 0, BuiltIn, T0, out _);
|
||||
var portals = new List<PortalLink>(BuiltIn);
|
||||
portals.AddRange(s.Links("S"));
|
||||
var steps = PortalRoute.Plan(portals, null, 0, 0, 40, 40, out _, out int used);
|
||||
Check(used == 1 && steps.Count == 2 && steps[0].UsePortal && steps[0].Label == "Server Portal", "the custom portal is taken");
|
||||
Near(steps[0].LandNs, 39.5, 1e-9, "it lands where it was learned to");
|
||||
// Without it (custom off, or another server): walk.
|
||||
steps = PortalRoute.Plan(BuiltIn, null, 0, 0, 40, 40, out _, out used);
|
||||
Check(used == 0, "without it: no portal");
|
||||
}
|
||||
}
|
||||
84
Tools/RynthNav.RouteTests/FollowTests.cs
Normal file
84
Tools/RynthNav.RouteTests/FollowTests.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
|
||||
namespace RynthNav.RouteTests;
|
||||
|
||||
// Walks keep to the trip's own path (TripFollow.cs, 2026-11-27): each re-plan aims a few yards along the walk the
|
||||
// markers draw; off it, back to it; progress never goes back, so a walk that doubles back isn't cut across.
|
||||
// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunFollow()
|
||||
{
|
||||
Run(nameof(FollowAimsAlongTheWalk), FollowAimsAlongTheWalk);
|
||||
Run(nameof(FollowRejoinsWhenOff), FollowRejoinsWhenOff);
|
||||
Run(nameof(FollowNeverCutsBack), FollowNeverCutsBack);
|
||||
Run(nameof(FollowHeights), FollowHeights);
|
||||
}
|
||||
|
||||
// An L: 100 yd east, then 100 yd north.
|
||||
private static WorldPt[] LWalk() => new[] { new WorldPt(1000, 1000, 0), new WorldPt(1100, 1000, 0), new WorldPt(1100, 1100, 0) };
|
||||
|
||||
private static void FollowAimsAlongTheWalk()
|
||||
{
|
||||
var f = new TripFollow(1, 0, LWalk());
|
||||
Near(f.Length, 200, 1e-6, "the walk's length");
|
||||
WorldPt a = f.Aim(1000, 1000, out double off, out bool atEnd);
|
||||
Near(a.X, 1000 + TripFollow.AheadUnits, 1e-6, "from the start: AheadUnits along");
|
||||
Check(!atEnd && off < 1e-6, "on the walk, not at its end");
|
||||
// At the corner, the aim goes round it (north), not straight on east across the field.
|
||||
a = f.Aim(1090, 1000, out off, out atEnd);
|
||||
Near(a.X, 1100, 1e-6, "past the corner: on the north leg (x)");
|
||||
Near(a.Y, 1000 + (90 + TripFollow.AheadUnits - 100), 1e-6, "past the corner: on the north leg (y)");
|
||||
// A little to the side of the walk still counts as on it.
|
||||
a = f.Aim(1100 - 5, 1050, out off, out atEnd);
|
||||
Near(off, 5, 1e-6, "5 yd to the side");
|
||||
Near(a.Y, 1050 + TripFollow.AheadUnits, 1e-6, "aims along from the nearest point");
|
||||
// Near the end: the step's own point, and planned to it as before.
|
||||
a = f.Aim(1100, 1090, out off, out atEnd);
|
||||
Check(atEnd && a.X == 1100 && a.Y == 1100, "near the end: the end itself");
|
||||
Near(f.Progress, 190, 1e-6, "progress is where you are on it");
|
||||
}
|
||||
|
||||
private static void FollowRejoinsWhenOff()
|
||||
{
|
||||
var f = new TripFollow(1, 0, LWalk());
|
||||
f.Aim(1050, 1000, out _, out _);
|
||||
// Knocked 30 yd off the walk: aim back at it, a little past its nearest point, not 28 yd ahead.
|
||||
WorldPt a = f.Aim(1060, 970, out double off, out bool atEnd);
|
||||
Near(off, 30, 1e-6, "30 yd off");
|
||||
Near(a.X, 1060 + TripFollow.RejoinUnits, 1e-6, "back to the walk, just past its nearest point");
|
||||
Near(a.Y, 1000, 1e-6, "on the walk");
|
||||
Near(f.Progress, 50, 1e-6, "progress doesn't move while off");
|
||||
Check(!atEnd, "not the end");
|
||||
}
|
||||
|
||||
private static void FollowNeverCutsBack()
|
||||
{
|
||||
// A hairpin: 100 east, 10 north, 100 back west. From the start of the way back, the first leg is 10 yd away.
|
||||
var hairpin = new[] { new WorldPt(0, 0, 0), new WorldPt(100, 0, 0), new WorldPt(100, 10, 0), new WorldPt(0, 10, 0) };
|
||||
var f = new TripFollow(1, 0, hairpin);
|
||||
for (double x = 0; x <= 100; x += 10) f.Aim(x, 0, out _, out _);
|
||||
f.Aim(100, 10, out _, out _);
|
||||
f.Aim(80, 10, out _, out _);
|
||||
Near(f.Progress, 130, 1e-6, "on the way back, 130 yd along");
|
||||
// Standing between the legs, nearer the first: the first leg is behind the window, so it isn't picked.
|
||||
WorldPt a = f.Aim(60, 4, out double off, out _);
|
||||
Check(Math.Abs(off - 6) < 1e-6, $"measured from the way back (6 yd), not the first leg (4 yd): {off:F2}");
|
||||
Check(a.Y == 10 && a.X < 60, $"the aim keeps going west on the way back ({a.X:F1}, {a.Y:F1})");
|
||||
Check(f.Progress >= 130, "progress never goes back");
|
||||
// Two points are the least a walk is.
|
||||
bool threw = false;
|
||||
try { _ = new TripFollow(1, 0, new[] { new WorldPt(0, 0, 0) }); } catch (ArgumentException) { threw = true; }
|
||||
Check(threw, "one point isn't a walk");
|
||||
}
|
||||
|
||||
private static void FollowHeights()
|
||||
{
|
||||
var ramp = new[] { new WorldPt(0, 0, 10), new WorldPt(100, 0, 30) };
|
||||
var f = new TripFollow(1, 0, ramp);
|
||||
Near(f.At(50).H, 20, 1e-6, "the height between the points");
|
||||
var flat = new[] { new WorldPt(0, 0, double.NaN), new WorldPt(100, 0, double.NaN) };
|
||||
Check(double.IsNaN(new TripFollow(1, 0, flat).At(50).H), "no heights given: none made up (the walker uses its own)");
|
||||
}
|
||||
}
|
||||
133
Tools/RynthNav.RouteTests/InsideTests.cs
Normal file
133
Tools/RynthNav.RouteTests/InsideTests.cs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
|
||||
namespace RynthNav.RouteTests;
|
||||
|
||||
// A go to someone INSIDE a dungeon (InsidePlaces.cs, Atlas.FindInside, Entrance.PortalInto; 2026-11-27):
|
||||
// which name means someone inside, and the way in: already there, a portal on the map, a recall you know.
|
||||
// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunInside()
|
||||
{
|
||||
Run(nameof(InsideFindsPeopleInDungeons), InsideFindsPeopleInDungeons);
|
||||
Run(nameof(InsideMapWinsWhenItAnswers), InsideMapWinsWhenItAnswers);
|
||||
Run(nameof(InsideWayIn), InsideWayIn);
|
||||
Run(nameof(InsideAlternatives), InsideAlternatives);
|
||||
Run(nameof(InsideLines), InsideLines);
|
||||
}
|
||||
|
||||
// Landblock 0x0A0B: the Deep Vault (two portals in on the map, one needs a quest; a third is destroyed).
|
||||
// Landblock 0x0C0D: reached only by Vault Recall. Holtburg is on the map; "Gate Keeper" is both a map NPC
|
||||
// in Holtburg and a person inside.
|
||||
private const string InsideJson = """
|
||||
{"generated":"test","locations":[
|
||||
{"id":1,"name":"Holtburg","type":"Town","cell":"A9B40001","place":"outdoor","ns":42.1,"ew":33.6},
|
||||
{"id":2,"name":"Quest Portal to the Deep Vault","type":"Portal","cell":"A9B30001","place":"outdoor","ns":41.9,"ew":33.5,"quest":true,
|
||||
"dest":{"cell":"0A0B0110","place":"dungeon","name":"Deep Vault"}},
|
||||
{"id":3,"name":"Deep Vault Portal","type":"Portal","cell":"A8B30001","place":"outdoor","ns":40.0,"ew":32.0,
|
||||
"dest":{"cell":"0A0B0110","place":"dungeon","name":"Deep Vault"}},
|
||||
{"id":4,"name":"Destroyed Deep Vault Portal","type":"Portal","cell":"A9B40002","place":"outdoor","ns":42.0,"ew":33.6,
|
||||
"dest":{"cell":"0A0B0110","place":"dungeon","name":"Deep Vault"}},
|
||||
{"id":5,"name":"Brannoc the Smith","type":"NPC","cell":"0A0B0123","place":"dungeon"},
|
||||
{"id":6,"name":"Brannoc","type":"Vendor","cell":"0C0D0101","place":"dungeon"},
|
||||
{"id":7,"name":"Ulla","type":"NPC","cell":"0C0D0140","place":"dungeon"},
|
||||
{"id":8,"name":"Inner Portal","type":"Portal","cell":"0A0B0130","place":"dungeon"},
|
||||
{"id":9,"name":"Gate Keeper","type":"NPC","cell":"A9B40003","place":"outdoor","ns":42.2,"ew":33.7},
|
||||
{"id":10,"name":"Gate Keeper","type":"NPC","cell":"0A0B0150","place":"dungeon"},
|
||||
{"id":11,"name":"Brannocka","type":"NPC","cell":"0A0B0151","place":"dungeon"},
|
||||
{"id":12,"name":"Holtburg Guard","type":"NPC","cell":"0A0B0152","place":"dungeon"},
|
||||
{"id":13,"name":"Holtburg Guard Tower","type":"Landmark","cell":"A9B40004","place":"outdoor","ns":42.3,"ew":33.8}
|
||||
],"recalls":[
|
||||
{"spell":4084,"name":"Vault Recall","cell":"0C0D0101","place":"dungeon"},
|
||||
{"spell":2020,"name":"Recall Holtburg","cell":"A9B40001","place":"outdoor","ns":42.1,"ew":33.6}
|
||||
]}
|
||||
""";
|
||||
|
||||
private static void InsideFindsPeopleInDungeons()
|
||||
{
|
||||
Atlas atlas = Atlas.Parse(InsideJson);
|
||||
Check(atlas.Recalls[0].Cell == "0C0D0101", "a recall's landing cell is read");
|
||||
AtlasLocation? d = atlas.FindInside("Brannoc the Smith");
|
||||
Check(d?.Id == 5, $"the exact name (got {d?.Id})");
|
||||
d = atlas.FindInside("brannoc");
|
||||
Check(d?.Id == 6, $"exact beats starts-with (got {d?.Id})");
|
||||
d = atlas.FindInside("Brannoc", hereLb: 0x0A0B);
|
||||
Check(d?.Id == 5, $"one in the landblock you're in wins (got {d?.Id})");
|
||||
Check(atlas.FindInside("Bran") == null, "a part of a word isn't a name (Bran, not Brannoc / Brannocka)");
|
||||
Check(atlas.FindInside("Inner Portal") == null, "a portal inside isn't someone to go to");
|
||||
Check(atlas.FindInside("Ul") == null, "two letters are too few");
|
||||
Check(atlas.FindInside("Holtburg")?.Id == 12, "a whole-word start counts inside (Holtburg Guard); Prefer leaves a map place to the map");
|
||||
AtlasLocation? p = Entrance.PortalInto(atlas, 0x0A0B, true, 42.1, 33.6);
|
||||
Check(p?.Id == 3, $"the portal in: no quest first beats nearer, never the destroyed one (got {p?.Id})");
|
||||
Check(Entrance.PortalInto(atlas, 0x0C0D, true, 42, 33) == null, "no portal on the map into the other dungeon");
|
||||
}
|
||||
|
||||
private static void InsideMapWinsWhenItAnswers()
|
||||
{
|
||||
Atlas atlas = Atlas.Parse(InsideJson);
|
||||
// The map's exact name wins: Gate Keeper is in Holtburg as well as inside.
|
||||
Check(InsidePlaces.Prefer(atlas, "Gate Keeper", true, 42, 33, 0, out bool onMap) == null && onMap, "an exact map name wins");
|
||||
// Someone inside by their exact name beats a map place that only half matches ("Holtburg Guard" vs Holtburg).
|
||||
AtlasLocation? g = InsidePlaces.Prefer(atlas, "Holtburg Guard", true, 42, 33, 0, out onMap);
|
||||
Check(g?.Id == 12 && onMap, $"an exact inside name beats a part-match on the map, Holtburg Guard Tower (got {g?.Id})");
|
||||
// Only a starts-with match inside, and a whole-word match on the map: the map.
|
||||
Check(InsidePlaces.Prefer(atlas, "Holtburg Gu", true, 42, 33, 0, out onMap) == null, "a partial name inside loses to the map's match");
|
||||
g = InsidePlaces.Prefer(atlas, "Ulla", true, 42, 33, 0, out onMap);
|
||||
Check(g?.Id == 7 && !onMap, $"nothing on the map: the one inside (got {g?.Id})");
|
||||
Check(InsidePlaces.Prefer(atlas, "Holtburg", true, 42, 33, 0, out onMap) == null && onMap, "a town is the town");
|
||||
Check(InsidePlaces.Prefer(atlas, "Nobody Here", true, 42, 33, 0, out onMap) == null && !onMap, "no one: null, nothing on the map");
|
||||
}
|
||||
|
||||
private static void InsideWayIn()
|
||||
{
|
||||
Atlas atlas = Atlas.Parse(InsideJson);
|
||||
AtlasLocation smith = atlas.ById(5)!, ulla = atlas.ById(7)!;
|
||||
var known = new HashSet<int> { 4084 };
|
||||
const uint outdoors = 0xA9B4001A, inVault = 0x0A0B0105, inOther = 0x0C0D0120;
|
||||
|
||||
InsideWay w = InsidePlaces.WayIn(atlas, smith, outdoors, true, 42.1, 33.6, known, true);
|
||||
Check(w.Kind == InsideWayKind.Portal && w.Portal?.Id == 3 && w.Cell == 0x0A0B0123 && w.Dungeon == "Deep Vault",
|
||||
$"on the map: the portal into the Deep Vault ({w.Kind}, {w.Portal?.Id}, {w.Cell:X8}, {w.Dungeon})");
|
||||
w = InsidePlaces.WayIn(atlas, smith, inVault, false, 0, 0, known, true);
|
||||
Check(w.Kind == InsideWayKind.Here, "in that dungeon already: here");
|
||||
w = InsidePlaces.WayIn(atlas, smith, inOther, false, 0, 0, known, true);
|
||||
Check(w.Kind == InsideWayKind.Portal && w.Portal?.Id == 3, "in another dungeon with no recall in: still the portal (the route out starts with a recall)");
|
||||
|
||||
w = InsidePlaces.WayIn(atlas, ulla, outdoors, true, 42, 33, known, true);
|
||||
Check(w.Kind == InsideWayKind.Recall && w.Recall?.SpellId == 4084 && w.Dungeon == "where Vault Recall lands",
|
||||
$"no portal in: the recall you know ({w.Kind}, {w.Dungeon})");
|
||||
w = InsidePlaces.WayIn(atlas, ulla, outdoors, true, 42, 33, new HashSet<int>(), true);
|
||||
Check(w.Kind == InsideWayKind.None && InsidePlaces.NoWayText(w).Contains("no portal on the map or recall you know"), "a recall you don't know: none");
|
||||
w = InsidePlaces.WayIn(atlas, ulla, outdoors, true, 42, 33, known, recallsOn: false);
|
||||
Check(w.Kind == InsideWayKind.None, "recalls off: none");
|
||||
w = InsidePlaces.WayIn(atlas, ulla, outdoors, true, 42, 33, null, true);
|
||||
Check(w.Kind == InsideWayKind.None, "the spellbook not read yet: none");
|
||||
w = InsidePlaces.WayIn(atlas, ulla, inOther, false, 0, 0, known, true);
|
||||
Check(w.Kind == InsideWayKind.Here && w.Cell == 0x0C0D0140, "Ulla's dungeon, where you are: here");
|
||||
}
|
||||
|
||||
private static void InsideAlternatives()
|
||||
{
|
||||
Atlas atlas = Atlas.Parse(InsideJson);
|
||||
Check(InsidePlaces.FromAlternatives(atlas, "Nobody || Ulla || Holtburg", true, 42, 33, 0)?.Id == 7, "the first inside candidate, before a later map one");
|
||||
Check(InsidePlaces.FromAlternatives(atlas, "Holtburg || Ulla", true, 42, 33, 0) == null, "a map place first: the usual go");
|
||||
Check(InsidePlaces.FromAlternatives(atlas, "10.0N, 20.0E || Ulla", true, 42, 33, 0) == null, "coordinates first: the usual go");
|
||||
Check(InsidePlaces.FromAlternatives(atlas, "Nobody || Nothing", true, 42, 33, 0) == null, "none at all: the usual go says why");
|
||||
}
|
||||
|
||||
private static void InsideLines()
|
||||
{
|
||||
Check(InsidePlaces.Tail("Brannoc", 0x009C0270) == " (Brannoc is in cell 009C0270)", "the arrival line's tail");
|
||||
// A walk only by default (2026-11-27): RynthAi turns fighting, looting, buffing and the meta off for it.
|
||||
Check(InsidePlaces.WalkCommand(0x009C0270, "Brannoc the Smith") == "/ra dunnav-to cell 009C0270 walkonly Brannoc the Smith", "RynthAi's walk to the cell, a walk only");
|
||||
Check(InsidePlaces.WalkCommand(0x009C0270, "") == "/ra dunnav-to cell 009C0270 walkonly", "no name: just the cell, a walk only");
|
||||
// Fight on the way in: the macro as set, as before.
|
||||
Check(InsidePlaces.WalkCommand(0x009C0270, "Brannoc the Smith", fight: true) == "/ra dunnav-to cell 009C0270 Brannoc the Smith", "fight on the way in: no walkonly");
|
||||
Check(InsidePlaces.WalkCommand(0x009C0270, "", fight: true) == "/ra dunnav-to cell 009C0270", "fight, no name: just the cell");
|
||||
Atlas atlas = Atlas.Parse(InsideJson);
|
||||
Check(InsidePlaces.DungeonName(atlas, 0x0A0B) == "Deep Vault", "named by the portals into it");
|
||||
Check(InsidePlaces.DungeonName(atlas, 0x0E0F) == "dungeon 0E0F", "unknown: its landblock");
|
||||
}
|
||||
}
|
||||
|
|
@ -64,11 +64,15 @@ internal static partial class Program
|
|||
RunAutoRunGate();
|
||||
RunRouteMaker();
|
||||
RunSteering();
|
||||
RunStuckWatch();
|
||||
RunWays();
|
||||
RunArrival();
|
||||
RunRealWalks();
|
||||
RunTripTimes();
|
||||
RunTargetSwitch();
|
||||
RunInside(); // someone inside a dungeon (InsideTests.cs)
|
||||
RunFollow(); // walks keep to the trip's path (FollowTests.cs)
|
||||
RunCustomPortals(); // a custom server's own portals (CustomPortalTests.cs)
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(_fails == 0 && _asserts > 0
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripClock.cs" Link="Linked\TripClock.cs" />
|
||||
<!-- The goto's heading servo and path follower (SteeringTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\WalkSteer.cs" Link="Linked\WalkSteer.cs" />
|
||||
<!-- Is the walk blocked (StuckWatchTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\StuckWatch.cs" Link="Linked\StuckWatch.cs" />
|
||||
<!-- The planned trip, its path, the path markers and "save as nav route" (TripExportTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPlan.cs" Link="Linked\TripPlan.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPath.cs" Link="Linked\TripPath.cs" />
|
||||
|
|
@ -52,6 +54,12 @@
|
|||
<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" />
|
||||
<!-- Ported navigation from SilentKelpie's backlog (2026-11-27): someone inside a dungeon (InsideTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\InsidePlaces.cs" Link="Linked\InsidePlaces.cs" />
|
||||
<!-- ...walks keep to the trip's path (FollowTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripFollow.cs" Link="Linked\TripFollow.cs" />
|
||||
<!-- ...and a custom server's own portals (CustomPortalTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\CustomPortals.cs" Link="Linked\CustomPortals.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
90
Tools/RynthNav.RouteTests/StuckWatchTests.cs
Normal file
90
Tools/RynthNav.RouteTests/StuckWatchTests.cs
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
|
||||
namespace RynthNav.RouteTests;
|
||||
|
||||
// Is the walk blocked (StuckWatch)? A walk against a wall that ran a moment and turned a moment,
|
||||
// swinging between headings, never ran 1.2 s in a row, so it was never blocked; it stood until the
|
||||
// 30 s progress watchdog stopped the goto. Turning ticks now count too.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunStuckWatch()
|
||||
{
|
||||
Run(nameof(StuckRunningIntoAWall), StuckRunningIntoAWall);
|
||||
Run(nameof(StuckRunTurnFlipFlop), StuckRunTurnFlipFlop);
|
||||
Run(nameof(StuckTurningOnly), StuckTurningOnly);
|
||||
Run(nameof(StuckNotWhileMoving), StuckNotWhileMoving);
|
||||
Run(nameof(StuckNotWhenNotDriving), StuckNotWhenNotDriving);
|
||||
}
|
||||
|
||||
private const long StuckTickMs = 30;
|
||||
|
||||
/// <summary>Ticks for <paramref name="ms"/>: Check, then drive (running or not) as the walk does. True once blocked.</summary>
|
||||
private static bool StuckTicks(StuckWatch w, ref long now, long ms, Func<long, bool> running, Func<long, (double x, double y)> at,
|
||||
bool drive = true)
|
||||
{
|
||||
long end = now + ms;
|
||||
for (; now < end; now += StuckTickMs)
|
||||
{
|
||||
var (x, y) = at(now);
|
||||
if (w.Check(now, x, y, out _, out _)) return true;
|
||||
if (drive) w.Drove(running(now));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void StuckRunningIntoAWall()
|
||||
{
|
||||
var w = new StuckWatch();
|
||||
long now = 1_000_000;
|
||||
bool stuck = StuckTicks(w, ref now, 1500, _ => true, _ => (10, 10));
|
||||
Check(stuck, "running and not moving for 1.2 s is blocked");
|
||||
}
|
||||
|
||||
private static void StuckRunTurnFlipFlop()
|
||||
{
|
||||
// Run 300 ms, turn 300 ms, over and over, against a wall: it used to start the watch again at
|
||||
// every turn and was never blocked.
|
||||
var w = new StuckWatch();
|
||||
long now = 1_000_000, start = now;
|
||||
bool stuck = StuckTicks(w, ref now, 4000, t => (t - start) / 300 % 2 == 0, _ => (10, 10));
|
||||
Check(stuck, "running and turning by turns against a wall is blocked");
|
||||
Check(now - start <= StuckWatch.RunWindowMs + 2 * StuckTickMs, $"within a run window ({now - start} ms)");
|
||||
}
|
||||
|
||||
private static void StuckTurningOnly()
|
||||
{
|
||||
var w = new StuckWatch();
|
||||
long now = 1_000_000, start = now;
|
||||
bool early = StuckTicks(w, ref now, 1500, _ => false, _ => (10, 10));
|
||||
Check(!early, "turning on the spot for 1.5 s is not blocked (a half turn takes about a second)");
|
||||
bool stuck = StuckTicks(w, ref now, 3000, _ => false, _ => (10, 10));
|
||||
Check(stuck, "turning on the spot for 3 s is blocked");
|
||||
Check(now - start >= StuckWatch.TurnWindowMs, $"only after the turn window ({now - start} ms)");
|
||||
}
|
||||
|
||||
private static void StuckNotWhileMoving()
|
||||
{
|
||||
var w = new StuckWatch();
|
||||
long now = 1_000_000, start = now;
|
||||
// 4 u/s, running and turning by turns: always getting somewhere.
|
||||
bool stuck = StuckTicks(w, ref now, 5000, t => (t - start) / 300 % 2 == 0, t => (10 + (t - start) * 0.004, 10));
|
||||
Check(!stuck, "a walk that moves is never blocked");
|
||||
}
|
||||
|
||||
private static void StuckNotWhenNotDriving()
|
||||
{
|
||||
// Standing (waiting for a plan) between drives starts the watch again each time.
|
||||
var w = new StuckWatch();
|
||||
long now = 1_000_000;
|
||||
bool stuck = false;
|
||||
for (int i = 0; i < 10 && !stuck; i++)
|
||||
{
|
||||
stuck |= StuckTicks(w, ref now, 600, _ => true, _ => (10, 10));
|
||||
stuck |= StuckTicks(w, ref now, 300, _ => true, _ => (10, 10), drive: false);
|
||||
}
|
||||
Check(!stuck, "short drives with standing between them are not blocked");
|
||||
w.Reset();
|
||||
Check(!w.Check(now, 10, 10, out double moved, out long windowMs) && moved == 0 && windowMs == 0, "after a reset: no window");
|
||||
}
|
||||
}
|
||||
155
Tools/RynthOracle.Tests/GuideTabTests.cs
Normal file
155
Tools/RynthOracle.Tests/GuideTabTests.cs
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
using System;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthOracle;
|
||||
using RynthCore.Plugin.RynthOracle.Data;
|
||||
using RynthCore.Plugin.RynthOracle.Ui;
|
||||
using RynthCore.Plugin.RynthOracle.Views;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthOracle.Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// The Guide tab (2026-11-27): the lists (All / Story / Dailies / Weekly, Kill Tasks, Society, Contracts), the four
|
||||
/// states, kill counts from /myquests and chat, "first time / done before", the server plugin's guide over the
|
||||
/// wiki's, and every page through the engine's parser. The guide is the made-up one of QuestGuideTests.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static unsafe void GuideTab()
|
||||
{
|
||||
OracleContext c = Context();
|
||||
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
c.Flags.OnChatLine($"TestErrandStarted - 1 solves ({now - 3600})\"Started\" -1 72000", 1000);
|
||||
c.Flags.OnChatLine($"KillTaskSampleBeasts_0101 - 12 solves ({now - 600})\"Beasts\" 50 0", 1000);
|
||||
c.Flags.OnChatLine($"KillTaskOtherThings_0202 - 3 solves ({now - 600})\"Others\" 10 0", 1000);
|
||||
c.Flags.Tick(6000);
|
||||
c.UtcNow = DateTime.UtcNow;
|
||||
c.Wiki.Use(SampleGuide());
|
||||
GuideProgress p = c.Progress;
|
||||
|
||||
// ── The four states ──
|
||||
QuestGuide g = c.Wiki.Guide;
|
||||
GuideQuest daily = g.Find("Test Daily Errand")!;
|
||||
GuideProgress.Row r = p.RowOf(daily, c.UtcNow);
|
||||
Check(r.State == GuideState.PartWaiting && r.Held == 1 && r.All == 3 && r.Status.StartsWith("1/3 wait ") && r.Tip.Contains("2 still to get"),
|
||||
$"one stamp of three held, its timer running: part done, waiting ({r.Status})");
|
||||
Check(p.StateOf(daily, "TestErrandStarted", c.UtcNow) == StampState.Done && p.StateOf(daily, "TestErrandFang", c.UtcNow) == StampState.Missing,
|
||||
"a held stamp inside its timer counts; a missing one doesn't");
|
||||
Check(p.StateOf(daily, "testerrandstarted", c.UtcNow) == StampState.Done, "a stamp matches its flag by any spelling");
|
||||
Check(p.StateOf(daily, "TestErrandStarted", c.UtcNow.AddDays(1)) == StampState.Earlier, "after its timer it was done on an earlier run");
|
||||
Check(p.RowOf(daily, c.UtcNow.AddDays(1)).State == GuideState.PartReady, "the timer up: part done, ready");
|
||||
Check(c.OnGuideChatLine("You've stamped TestErrandFang!", c.UtcNow) && c.SessionStamps.Contains("testerrandfang"), "a stamp line in chat is held at once");
|
||||
Check(p.RowOf(daily, c.UtcNow).Held == 2, "two of three held now");
|
||||
c.OnGuideChatLine("You've stamped TestErrandDone!", c.UtcNow);
|
||||
GuideProgress.Row full = p.RowOf(daily, c.UtcNow);
|
||||
Check(full.State == GuideState.Done && full.HideWhenDone && full.Status.StartsWith("Done "), "every stamp held, its timer running: done, hidden by Hide done");
|
||||
GuideQuest story = g.Find("Test Story Quest")!;
|
||||
Check(p.RowOf(story, c.UtcNow).Status == "no stamps" && p.RowOf(story, c.UtcNow, flagDone: true).State == GuideState.Done
|
||||
&& p.RowOf(story, c.UtcNow, flagDone: false).State == GuideState.NotDone, "a quest without stamps: the quest list's flag, else unknown");
|
||||
Check(GuideProgress.RepeatText(daily).StartsWith("Daily (every 20h") && GuideProgress.RepeatText(story) == "One-time", "the timer text");
|
||||
|
||||
// ── Kill tasks ──
|
||||
GuideQuest kt = g.Find("Sample Beast Kill Task")!;
|
||||
GuideProgress.Kill k = p.KillOf(kt, c.UtcNow);
|
||||
Check(k.State == KillState.Counting && k.Kills == 12 && k.Goal == 50 && string.Equals(k.Counter?.Key, "KillTaskSampleBeasts_0101", StringComparison.OrdinalIgnoreCase) && !k.DoneBefore,
|
||||
$"a kill task counting from its /myquests counter, the first time ({k.Status})");
|
||||
Check(c.OnGuideChatLine("You have killed 13 Sample Beasts! You must kill 50 to complete your task.", DateTime.UtcNow.AddSeconds(5)), "a kill line is taken");
|
||||
k = p.KillOf(kt, c.UtcNow);
|
||||
Check(k.Kills == 13 && k.FromChat && k.Status == "13 / 50", "the kill line moves the count at once");
|
||||
c.OnGuideChatLine("You have killed 50 Sample Beasts! You must kill 50 to complete your task.", DateTime.UtcNow.AddSeconds(6));
|
||||
Check(p.KillOf(kt, c.UtcNow).State == KillState.TurnIn, "all kills made: turn in");
|
||||
Check(GuideProgress.FlagLabel("KillTaskOtherThings_0202") == "Kill Task Other Things 0202", "a counter flag's label");
|
||||
Check(!c.OnGuideChatLine("You have killed a Sample Beast.", c.UtcNow), "an ordinary kill line isn't a kill task's");
|
||||
|
||||
// ── The page ──
|
||||
var view = new OracleView(c);
|
||||
var host = new UiHost();
|
||||
UiWindow main = host.Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true, DefaultWidth = 760, DefaultHeight = 600 });
|
||||
string Draw(string what)
|
||||
{
|
||||
main.Begin(); view.Draw(main); main.End();
|
||||
ParseAll(host, what, out int ops);
|
||||
Check(ops > 5 && ops < 1400, $"{what}: {ops} ops");
|
||||
string body = Encoding.UTF8.GetString(main.Body);
|
||||
main.MarkSubmitted(true);
|
||||
return body;
|
||||
}
|
||||
Check(Array.IndexOf(view.VisibleTabs(), OracleView.TabGuide) == 1, "the Guide tab is the second tab");
|
||||
view.ShowGuide(GuideList.All);
|
||||
string all = Draw("Guide: All");
|
||||
Check(all.Contains("Test Daily Errand") && all.Contains("Test Story Quest") && all.Contains("AC Community Wiki feed: off"),
|
||||
"All lists the guide's quests and says the feed is off");
|
||||
view.ShowGuide(GuideList.Dailies, "w:Test Daily Errand");
|
||||
string opened = Draw("Guide: a quest opened");
|
||||
Check(opened.Contains("Daily (every 20h") && opened.Contains("Go 12.3N, 45.6E") && opened.Contains("[x] stamped TestErrandStarted")
|
||||
&& opened.Contains("Sample Fang") && opened.Contains("Wiki page") && !opened.Contains("Run this quest"),
|
||||
"the opened quest: timer, Go buttons, ticked stamps, loot; no run controls in this version");
|
||||
view.ShowGuide(GuideList.Story, "");
|
||||
string storyPage = Draw("Guide: Story");
|
||||
Check(storyPage.Contains("Test Story Quest") && !storyPage.Contains("Test Daily Errand"), "Story holds the one-time quests only");
|
||||
|
||||
view.ShowGuide(GuideList.KillTasks);
|
||||
Check(view.KillTasksShowing, "the Kill Tasks list is on screen");
|
||||
string kills = Draw("Guide: Kill Tasks");
|
||||
Check(kills.Contains("Sample Beast Kill Task") && kills.Contains("Turn in") && kills.Contains("1st"), "a wiki kill task: turn in, first time");
|
||||
Check(kills.Contains("Others") && kills.Contains("3 / 10"), "a counter no wiki task names is listed too");
|
||||
Check(kills.Contains("Kill tasks: 0 counting, 1 to turn in"), "the summary line");
|
||||
|
||||
view.ShowGuide(GuideList.Society, "w:Test Story Quest");
|
||||
string society = Draw("Guide: Society");
|
||||
Check(society.Contains("Initiate: Test Story Quest") && society.Contains("Society: Initiate"), "society quests by rank");
|
||||
view.ShowGuide(GuideList.Contracts, "c:Contract for Test Daily Errand");
|
||||
string contracts = Draw("Guide: Contracts");
|
||||
Check(contracts.Contains("Contract for Test Daily Errand") && contracts.Contains("Go to Sample Barkeep") && contracts.Contains("Open"),
|
||||
"a contract: where it comes from (Go) and its quest (Open)");
|
||||
// Open goes to the quest in All.
|
||||
main.Begin(); view.Draw(main); main.End();
|
||||
Apply(host, Event(1, 300, main.Hash, main.KeyOf("g.c.q.0"), new byte[] { 1, 0, 0 }));
|
||||
string afterOpen = Draw("Guide: Open from a contract");
|
||||
Check(afterOpen.Contains("Daily (every 20h") && afterOpen.Contains("[x] stamped"), "Open shows the contract's quest");
|
||||
|
||||
// Hide done leaves the finished daily out (every stamp held, its timer running).
|
||||
c.Settings.GuideHideDone = true;
|
||||
view.ShowGuide(GuideList.All, "");
|
||||
string hidden = Draw("Guide: hide done");
|
||||
Check(!hidden.Contains("Test Daily Errand") && hidden.Contains("Test Story Quest"), "Hide done leaves out the done daily");
|
||||
c.Settings.GuideHideDone = false;
|
||||
|
||||
// ── A server plugin's guide comes first, over the wiki's quest of the same name ──
|
||||
var serverGuide = new QuestGuide();
|
||||
serverGuide.Quests.Add(new GuideQuest { Title = "Test Story Quest", Steps = { new GuideStep { Text = "The server's own way", Stamps = { "ServerStoryStamp" } } } });
|
||||
serverGuide.Quests.Add(new GuideQuest { Title = "Server Only Quest", RepeatSec = 7 * 86400 });
|
||||
ServerQuestGuideHost.ResetForTests();
|
||||
var table = (RynthServerQuestGuideApiV1*)ServerQuestGuideHost.Query(1);
|
||||
ServerQuestGuideHost.Publish("Test Server", "RynthTestServer", serverGuide, "2 quests", running: false, RynthServerQuestGuide.CommandRefresh);
|
||||
c.ServerGuide.Use(table, "RynthTestServer");
|
||||
GuideSet set = view.GuideSources();
|
||||
Check(set.Quests.Count == 4 && set.Find("Test Story Quest")!.Steps.Count == 1 && set.FromServer(set.Find("Server Only Quest")!)
|
||||
&& !set.FromServer(set.Find("Test Daily Errand")!), "merged: the server's quests first and over the wiki's of the same name");
|
||||
Check(set.SocietyRankOf(set.Find("Test Story Quest")!) == "Initiate", "the wiki's society rank still applies");
|
||||
view.ShowGuide(GuideList.Weekly, "w:Server Only Quest");
|
||||
string weekly = Draw("Guide: a server quest");
|
||||
Check(weekly.Contains("Test Server Wiki (RynthTestServer)") && weekly.Contains("Read it again") && weekly.Contains("From Test Server's guide"),
|
||||
"the server guide's line, its command button and the quest's source");
|
||||
ServerQuestGuideHost.Release();
|
||||
c.ServerGuide.Use(table, "RynthTestServer");
|
||||
Check(view.GuideSources().Quests.Count == 3, "the server's guide gone: the wiki's alone");
|
||||
ServerQuestGuideHost.ResetForTests();
|
||||
|
||||
// ── No guide at all: the feed's controls, saying what it reads ──
|
||||
OracleContext empty = Context();
|
||||
var emptyView = new OracleView(empty);
|
||||
UiWindow ew = new UiHost().Add(new UiWindow("RynthOracle/Oracle", "Oracle") { Visible = true });
|
||||
empty.Settings.TabName = OracleView.TabGuide;
|
||||
ew.Begin(); emptyView.Draw(ew); ew.End();
|
||||
string none = Encoding.UTF8.GetString(ew.Body);
|
||||
Check(none.Contains("No quest guide yet") && none.Contains("Turn the feed on and read it") && none.Contains("asheron.fandom.com/api.php"),
|
||||
"no guide: the feed's button, and what it reads and from where");
|
||||
|
||||
// ── /ro guide ──
|
||||
Check(OracleCommand.Parse("guide") is { Verb: OracleVerb.Tab, Tab: OracleView.TabGuide, Word: "" }
|
||||
&& OracleCommand.Parse("killtasks") is { Tab: OracleView.TabGuide, Word: "killtasks" }
|
||||
&& OracleCommand.Parse("guide society").Word == "society" && OracleCommand.Parse("contracts").Word == "contracts", "/ro guide words");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -41,6 +41,8 @@ namespace RynthOracle.Tests
|
|||
{
|
||||
// Tab clicks save the settings: into a scratch file, never the player's %APPDATA% copy.
|
||||
OracleSettings.PathOverride = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-settings.json");
|
||||
// The wiki feed's saved guide: a scratch path too (none there, so the feed starts empty).
|
||||
CommunityWikiFeed.PathOverride = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-guide.json");
|
||||
Lists();
|
||||
QuestLines();
|
||||
Catalog();
|
||||
|
|
@ -68,6 +70,10 @@ namespace RynthOracle.Tests
|
|||
ServerMove();
|
||||
Replies();
|
||||
ReadyEarly();
|
||||
QuestListDaily();
|
||||
QuestGuideInterface();
|
||||
WikiFeed();
|
||||
GuideTab();
|
||||
Console.WriteLine($"{_pass} passed, {_fail} failed");
|
||||
return _fail == 0 ? 0 : 1;
|
||||
}
|
||||
|
|
|
|||
101
Tools/RynthOracle.Tests/QuestGuideTests.cs
Normal file
101
Tools/RynthOracle.Tests/QuestGuideTests.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthOracle.Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// The quest guide (2026-11-27; SilentKelpie's PR 12 idea, re-implemented): the "RynthServer.QuestGuide"
|
||||
/// interface a server plugin serves its guide through, the guide's JSON, and RynthOracle's reader of it.
|
||||
/// The server side runs in-process (ServerQuestGuideHost's table, as a server plugin would hand it out).
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
/// <summary>A small guide in the shared format: two quests (one with steps and stamps), a kill task, a contract.</summary>
|
||||
internal static QuestGuide SampleGuide()
|
||||
{
|
||||
var g = new QuestGuide { Source = "test wiki", UpdatedUtc = new DateTime(2026, 11, 27, 12, 0, 0, DateTimeKind.Utc) };
|
||||
g.Quests.Add(new GuideQuest
|
||||
{
|
||||
Title = "Test Daily Errand", Url = "https://wiki.example/Test_Daily_Errand", Rev = 11, Level = "50+", Repeat = "20 Hours",
|
||||
RepeatSec = 20 * 3600, StartsWith = "Sample Questgiver", StartsAt = "Sampletown",
|
||||
Steps =
|
||||
{
|
||||
new GuideStep { Text = "Talk to Sample Questgiver", Coords = { "12.3N, 45.6E" }, Stamps = { "TestErrandStarted" } },
|
||||
new GuideStep { Text = "Kill the Sample Beast and loot its Sample Fang", Items = { "Sample Fang" }, Stamps = { "TestErrandFang" } },
|
||||
new GuideStep { Text = "Hand the fang in", Stamps = { "TestErrandDone" } },
|
||||
},
|
||||
Loot = { "Sample Fang" }, Rewards = { "Luminance: 1,000" },
|
||||
});
|
||||
g.Quests.Add(new GuideQuest { Title = "Test Story Quest", Overview = "A one-time quest." });
|
||||
g.Quests.Add(new GuideQuest
|
||||
{
|
||||
Title = "Sample Beast Kill Task", KillTask = "Yes", RepeatSec = 20 * 3600, Repeat = "20 hours",
|
||||
Steps = { new GuideStep { Text = "Kill 50 Sample Beasts", Stamps = { "KillTaskSampleBeasts_0101 on first completion" } } },
|
||||
});
|
||||
g.KillTasks.Add("Sample Beast Kill Task");
|
||||
g.Society["Test Story Quest"] = "Initiate";
|
||||
g.Contracts.Add(new GuideContract { Title = "Contract for Test Daily Errand", Name = "Contract for Test Daily Errand", Npc = "Sample Barkeep", Quests = { "Test Daily Errand" } });
|
||||
return g;
|
||||
}
|
||||
|
||||
private static unsafe void QuestGuideInterface()
|
||||
{
|
||||
// The guide's JSON round trip, stamps cut to their flags on the way in.
|
||||
QuestGuide g = SampleGuide();
|
||||
QuestGuide back = QuestGuide.Parse(g.ToJson());
|
||||
Check(back.Quests.Count == 3 && back.Contracts.Count == 1 && back.KillTasks.Count == 1, "the guide reads back: quests, kill tasks, contracts");
|
||||
GuideQuest? daily = back.Find("test daily errand");
|
||||
Check(daily != null && daily.Steps.Count == 3 && daily.Steps[0].Coords[0] == "12.3N, 45.6E" && daily.RepeatSec == 72000 && daily.IsDaily,
|
||||
"a quest's steps, coordinates and timer read back");
|
||||
Check(back.Find("Sample Beast Kill Task")!.Steps[0].Stamps[0] == "KillTaskSampleBeasts_0101", "a stamp with words after it is cut to the flag");
|
||||
Check(back.IsKillTask(back.Find("Sample Beast Kill Task")!) && !back.IsKillTask(daily!), "kill tasks by the summary box and the list");
|
||||
Check(back.SocietyRankOf(back.Find("Test Story Quest")!) == "Initiate", "society rank from the guide's society list");
|
||||
Check(QuestGuide.Parse("not json").IsEmpty && QuestGuide.Parse("{\"schema\":9,\"quests\":[{\"title\":\"x\"}]}").IsEmpty,
|
||||
"junk or another schema is an empty guide");
|
||||
Check(GuideStamp.Clean("You've stamped TestErrandFang!") == "TestErrandFang" && GuideStamp.Clean("Shiny Red Stone") == "Shiny Red Stone",
|
||||
"a chat line's stamp, and a stamp of plain words left whole");
|
||||
Check(GuideStamp.Key("Shiny_Red_Stone") == GuideStamp.Key("shiny red stone"), "stamp names compare alike");
|
||||
|
||||
// A server plugin serves it; the reader takes it through the table.
|
||||
ServerQuestGuideHost.ResetForTests();
|
||||
var table = (RynthServerQuestGuideApiV1*)ServerQuestGuideHost.Query(1);
|
||||
Check(table != null && table->Version == 1 && ServerQuestGuideHost.Query(2) == IntPtr.Zero, "the table answers version 1 only");
|
||||
var client = new ServerQuestGuideClient();
|
||||
client.Use(table, "RynthTestServer");
|
||||
Check(!client.Available && client.Guide.IsEmpty, "nothing published: no guide");
|
||||
|
||||
ServerQuestGuideHost.Publish("Test Server", "RynthTestServer", null, "reading the wiki...", running: true, RynthServerQuestGuide.CommandRefresh);
|
||||
client.Use(table, "RynthTestServer");
|
||||
Check(client.Available && client.Guide.IsEmpty && client.Info!.Running && client.Info.Status == "reading the wiki...",
|
||||
"a guide still being read: its status, no quests");
|
||||
|
||||
ServerQuestGuideHost.Publish("Test Server", "RynthTestServer", g, "3 quests", running: false, RynthServerQuestGuide.CommandRefresh, RynthServerQuestGuide.CommandSettings);
|
||||
int rev = client.Revision;
|
||||
client.Use(table, "RynthTestServer");
|
||||
Check(client.Guide.Quests.Count == 3 && client.Tag == "Test Server" && client.Revision != rev, "the published guide is read");
|
||||
rev = client.Revision;
|
||||
client.Use(table, "RynthTestServer");
|
||||
Check(client.Revision == rev, "unchanged info: nothing read again");
|
||||
|
||||
Check(client.Command("refresh") && ServerQuestGuideHost.TryTakeCommand(out string word) && word == "refresh", "a command goes to the plugin's queue");
|
||||
Check(!client.Command("delete-everything") && !ServerQuestGuideHost.TryTakeCommand(out _), "a word the plugin doesn't list isn't sent");
|
||||
|
||||
// A name outside ASCII survives the info JSON's escaping.
|
||||
ServerQuestGuideHost.Publish("Café \"Q\"", "RynthTestServer", g, "ok", running: false);
|
||||
client.Use(table, "RynthTestServer");
|
||||
Check(client.Tag == "Café \"Q\"" && !client.Info!.Takes("refresh"), "the tag's escaping, and no commands listed");
|
||||
|
||||
ServerQuestGuideHost.Release();
|
||||
Check(table->Version == 0, "shutdown: the table says so");
|
||||
client.Use(table, "RynthTestServer");
|
||||
Check(!client.Available && client.Guide.IsEmpty, "a shut-down plugin's guide goes away");
|
||||
ServerQuestGuideHost.ResetForTests();
|
||||
|
||||
Check(ServerQuestGuideInfo.Parse("{\"schema\":1,\"bytes\":-5,\"commands\":[\"Refresh\",3]}") is { Bytes: 0 } i && i.Takes("refresh"),
|
||||
"the info is read leniently");
|
||||
Check(ServerQuestGuideInfo.Parse("{\"schema\":2}") == null && ServerQuestGuideInfo.Parse("[]") == null, "another schema, or junk, is no info");
|
||||
}
|
||||
}
|
||||
}
|
||||
20
Tools/RynthOracle.Tests/QuestListDailyTests.cs
Normal file
20
Tools/RynthOracle.Tests/QuestListDailyTests.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.RynthOracle.Data;
|
||||
|
||||
namespace RynthOracle.Tests
|
||||
{
|
||||
// "Check once a day for a newer quest list" ran once per login: a client that stayed logged in for
|
||||
// days never checked again. It is due a day after the last check started, however long the session.
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void QuestListDaily()
|
||||
{
|
||||
DateTime last = new DateTime(2026, 11, 20, 9, 0, 0, DateTimeKind.Utc);
|
||||
Check(QuestCatalogUpdater.Due(last.AddDays(1), last), "quest list: due a day after the last check");
|
||||
Check(!QuestCatalogUpdater.Due(last.AddHours(23), last), "quest list: not due within the day");
|
||||
Check(QuestCatalogUpdater.Due(last.AddDays(3), last), "quest list: still due days later in the same session");
|
||||
Check(QuestCatalogUpdater.Due(last, DateTime.MinValue), "quest list: never checked: due");
|
||||
Check(!new QuestCatalogUpdater().Running, "quest list: a new updater isn't running");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -25,6 +25,10 @@ namespace RynthOracle.Tests
|
|||
("progress", OracleVerb.Tab, OracleView.TabProgress), ("progression", OracleVerb.Tab, OracleView.TabProgress),
|
||||
("status", OracleVerb.Status, ""), ("about", OracleVerb.About, OracleView.TabAbout), ("help", OracleVerb.Help, ""), ("?", OracleVerb.Help, ""),
|
||||
("STATUS", OracleVerb.Status, ""), ("questz", OracleVerb.Unknown, ""), ("dynamic", OracleVerb.Unknown, ""),
|
||||
("wiki", OracleVerb.Wiki, ""), ("wiki on", OracleVerb.Wiki, ""), ("wiki off", OracleVerb.Wiki, ""), ("wiki read", OracleVerb.Wiki, ""),
|
||||
("wiki status", OracleVerb.Wiki, ""), ("wiki delete", OracleVerb.Unknown, ""),
|
||||
("guide", OracleVerb.Tab, OracleView.TabGuide), ("killtasks", OracleVerb.Tab, OracleView.TabGuide), ("kill tasks", OracleVerb.Tab, OracleView.TabGuide),
|
||||
("guide society", OracleVerb.Tab, OracleView.TabGuide), ("contracts", OracleVerb.Tab, OracleView.TabGuide),
|
||||
};
|
||||
var seen = new HashSet<OracleVerb>();
|
||||
foreach (var (typed, verb, tab) in words)
|
||||
|
|
|
|||
|
|
@ -38,6 +38,12 @@
|
|||
<!-- "RynthServer.QuestPack": the active server plugin's quest pack (as in the plugin's csproj). -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthServerQuestPackApi.cs" Link="RynthOracle\Shared\RynthServerQuestPackApi.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\ServerQuestPackClient.cs" Link="RynthOracle\Shared\ServerQuestPackClient.cs" />
|
||||
<!-- "RynthServer.QuestGuide": the reader (as in the plugin's csproj) and a server plugin's side (the tests serve a guide). -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthServerQuestGuideApi.cs" Link="RynthOracle\Shared\RynthServerQuestGuideApi.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\QuestGuideData.cs" Link="RynthOracle\Shared\QuestGuideData.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\ServerQuestGuideClient.cs" Link="RynthOracle\Shared\ServerQuestGuideClient.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\ServerQuestGuideHost.cs" Link="RynthOracle\Shared\ServerQuestGuideHost.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\QuestWikiText.cs" Link="RynthOracle\Shared\QuestWikiText.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="RynthOracle\Shared\CommandReply.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ namespace RynthOracle.Tests
|
|||
{
|
||||
c.Server.Force(tag, world);
|
||||
string[] tabs = view.VisibleTabs();
|
||||
Check(Array.IndexOf(tabs, "Pet Breeding") < 0 && tabs.Length == 11, $"ilt: {world}: the same eleven tabs: " + string.Join(",", tabs));
|
||||
Check(Array.IndexOf(tabs, "Pet Breeding") < 0 && tabs.Length == 12, $"ilt: {world}: the same twelve tabs: " + string.Join(",", tabs));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
153
Tools/RynthOracle.Tests/WikiFeedTests.cs
Normal file
153
Tools/RynthOracle.Tests/WikiFeedTests.cs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthOracle;
|
||||
using RynthCore.Plugin.RynthOracle.Data;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthOracle.Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// The wiki page reader (Plugins/Shared/QuestWikiText.cs) and the AC Community Wiki feed's pure parts
|
||||
/// (2026-11-27). The pages here are made up in the wiki's template style; no wiki text is copied in.
|
||||
/// The feed is off by default and never fetches in these tests.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private const string TestWiki = "https://wiki.example/wiki/";
|
||||
|
||||
/// <summary>A made-up quest page: summary box, overview, numbered steps with stamps and items, a stamp listed apart, rewards.</summary>
|
||||
internal const string SampleQuestPage = @"{{Quest Summary
|
||||
| Level = 50+
|
||||
| Recommended Level = 80+
|
||||
| Quest Type = Solo
|
||||
| Starts With = [[Sample Questgiver]]
|
||||
| Starts At = [[Sampletown]]
|
||||
| Repeat Timer = 20 Hours
|
||||
}}
|
||||
<!-- an editor's note that isn't shown -->
|
||||
== Overview ==
|
||||
Sample Questgiver wants a '''fang''' from the [[Sample Beast|beast]] in the hills.<ref>a footnote</ref>
|
||||
== Walkthrough ==
|
||||
# Talk to [[Sample Questgiver]] in Sampletown (12.3N, 45.6E).
|
||||
#* {{stamped|TestErrandStarted}}
|
||||
# Travel to the hills at 20.1s 30.2w and kill the Sample Beast to loot a {{Itemlink|Sample Fang}}.
|
||||
#* It hits hard.
|
||||
# Hand the {{Itemlink|Sample Fang}} to [[Sample Questgiver]].
|
||||
== QB Stamps ==
|
||||
{{stamped|TestErrandFang}} {{stamped|TestErrandDone on first completion}}
|
||||
== Rewards ==
|
||||
{{Rewards Table
|
||||
| Quest Task = Hand in the fang
|
||||
| Item Reward = * {{Itemlink|Sample Trinket}} (x2)
|
||||
| XP Reward = 1,000,000
|
||||
}}
|
||||
[[Category:Quests]]
|
||||
[[Category:Sample Quests]]";
|
||||
|
||||
private const string SampleKillPage = @"{{Quest Summary | Level = 30+ | Kill Task = Yes | Repeat Timer = Non Repeatable | Starts With = [[Sample Hunter]] }}
|
||||
== Walkthrough ==
|
||||
* Kill 50 [[Sample Beast]]s for the hunter. {{stamped|KillTaskSampleBeasts_0101 on first completion}}
|
||||
* Return to the hunter.";
|
||||
|
||||
private const string SampleContractPage = @"{{Intro | Related Quests = [[Test Daily Errand]], [[Test Story Quest|the story]] }}
|
||||
{{Item | Name = Contract for Test Daily Errand | Description = Starts the errand again. | Recommended Level = 50 }}
|
||||
== Notes ==
|
||||
* Purchased from [[Sample Barkeep]] in the Sampletown inn.
|
||||
[[Category:Contracts]]";
|
||||
|
||||
private static void WikiFeed()
|
||||
{
|
||||
// ── The page reader ──
|
||||
Check(QuestWikiText.IsQuestPage(SampleQuestPage) && !QuestWikiText.IsQuestPage("just text"), "a quest page has the summary box");
|
||||
GuideQuest q = QuestWikiText.ParseQuest("Test Daily Errand", SampleQuestPage, 77, TestWiki);
|
||||
Check(q.Url == "https://wiki.example/wiki/Test_Daily_Errand" && q.Rev == 77, "the page's address and revision: " + q.Url);
|
||||
Check(q.Level == "50+" && q.RecommendedLevel == "80+" && q.Type == "Solo" && q.StartsWith == "Sample Questgiver" && q.StartsAt == "Sampletown",
|
||||
"the summary box: level, type, where it starts");
|
||||
Check(q.RepeatSec == 20 * 3600 && q.IsDaily && !q.IsOneTime, "a 20 hour timer is a daily");
|
||||
Check(q.Overview == "Sample Questgiver wants a fang from the beast in the hills.", "the overview, links and markup cleaned: " + q.Overview);
|
||||
Check(q.Steps.Count == 3, $"three numbered steps ({q.Steps.Count})");
|
||||
Check(q.Steps[0].Coords.Count == 1 && q.Steps[0].Coords[0] == "12.3N, 45.6E" && q.Steps[0].Stamps[0] == "TestErrandStarted",
|
||||
"step 1: its coordinates and stamp");
|
||||
Check(q.Steps[1].Coords[0] == "20.1S, 30.2W" && q.Steps[1].Notes.Count == 1 && q.Steps[1].Items[0] == "Sample Fang",
|
||||
"step 2: lower-case coordinates, its tip and its item");
|
||||
Check(q.Steps[1].Stamps.Contains("TestErrandFang"), "a stamp listed apart goes with the step that names it");
|
||||
Check(q.Steps[2].Stamps.Contains("TestErrandDone"), "the last stamp left goes to the last stampless step, cut to its flag");
|
||||
Check(q.ExtraStamps.Count == 0 && q.AllStamps().Count == 3, "every stamp tied to a step");
|
||||
Check(q.Loot.Count == 1 && q.Loot[0] == "Sample Fang", "loot: the item a kill step names, not the hand-in");
|
||||
Check(q.Rewards.Count == 3 && q.Rewards[0] == "For Hand in the fang:" && q.Rewards[1] == "Sample Trinket (x2)" && q.Rewards[2] == "XP: 1,000,000",
|
||||
"the rewards table: " + string.Join(" | ", q.Rewards));
|
||||
Check(q.Categories.Contains("Sample Quests"), "the categories");
|
||||
|
||||
GuideQuest k = QuestWikiText.ParseQuest("Sample Beast Kill Task", SampleKillPage, 5, TestWiki);
|
||||
Check(k.IsKillTaskPage && k.KillTarget == 50 && k.KillCreatureKey == "samplebeast", "a kill task: the box, the count, the creature");
|
||||
Check(k.RepeatSec == 0 && k.IsOneTime, "\"Non Repeatable\" is one-time");
|
||||
Check(k.Steps.Count == 2 && k.Steps[0].Stamps[0] == "KillTaskSampleBeasts_0101", "bullet steps, the counter stamp cut to its flag");
|
||||
|
||||
Check(QuestWikiText.IsContractPage("Contract for Test Daily Errand", SampleContractPage), "a contract page");
|
||||
GuideContract c = QuestWikiText.ParseContract("Contract for Test Daily Errand", SampleContractPage, 9, TestWiki);
|
||||
Check(c.Name == "Contract for Test Daily Errand" && c.Level == "50" && c.Description == "Starts the errand again.", "the contract's item box");
|
||||
Check(c.Quests.Count == 2 && c.Quests[0] == "Test Daily Errand" && c.Quests[1] == "Test Story Quest", "the quests it is for");
|
||||
Check(c.Npc == "Sample Barkeep" && c.Where.StartsWith("Purchased from Sample Barkeep"), "where it comes from: " + c.Where);
|
||||
|
||||
// Paragraph walkthroughs, repeat timers.
|
||||
GuideQuest para = QuestWikiText.ParseQuest("P", "{{Quest Summary}}\n== Walkthrough ==\nFirst go here.\nStill the first.\n\nThen go there 1.0N 2.0E.", 0, TestWiki);
|
||||
Check(para.Steps.Count == 2 && para.Steps[1].Coords[0] == "1.0N, 2.0E", "paragraphs are steps");
|
||||
Check(QuestWikiText.RepeatSeconds("7 days") == 7 * 86400 && QuestWikiText.RepeatSeconds("3d 12h") == 3 * 86400 + 12 * 3600
|
||||
&& QuestWikiText.RepeatSeconds("Weekly") == 7 * 86400 && QuestWikiText.RepeatSeconds("None") == 0
|
||||
&& QuestWikiText.RepeatSeconds("whenever") == -1, "repeat timers");
|
||||
Check(QuestWikiText.Clean("[[File:x.png|thumb|a [[link]]]] [[Foo|bar]] {{Itemlink|Baz}} & <br/>end") == "bar Baz & end", "markup cleaned");
|
||||
|
||||
// ── The API's answers ──
|
||||
var members = QuestWikiText.Members(
|
||||
"{\"continue\":{\"cmcontinue\":\"page|X\",\"continue\":\"-||\"},\"query\":{\"categorymembers\":[{\"ns\":0,\"title\":\"A\"},{\"ns\":14,\"title\":\"Category:B\"},{\"ns\":6,\"title\":\"File:C\"}]}}",
|
||||
"categorymembers");
|
||||
Check(members.Pages.Count == 1 && members.Pages[0] == "A" && members.SubCats.Count == 1 && members.Continue.Count == 2,
|
||||
"category members: pages, sub-categories, continue");
|
||||
Dictionary<string, long> revs = QuestWikiText.LastRevisions("{\"query\":{\"pages\":[{\"title\":\"A\",\"lastrevid\":12},{\"title\":\"Gone\",\"missing\":true}]}}");
|
||||
Check(revs.Count == 1 && revs["A"] == 12, "page revisions, missing pages left out");
|
||||
var contents = QuestWikiText.Contents("{\"query\":{\"pages\":[{\"title\":\"A\",\"revisions\":[{\"revid\":12,\"slots\":{\"main\":{\"content\":\"hello\"}}}]}]}}");
|
||||
Check(contents.Count == 1 && contents[0].Rev == 12 && contents[0].Text == "hello", "page contents");
|
||||
Check(QuestWikiText.Members("not json", "x").Pages.Count == 0 && QuestWikiText.LastRevisions("[").Count == 0, "junk answers are empty");
|
||||
var titles = new List<string>();
|
||||
for (int i = 0; i < 120; i++) titles.Add("T" + i);
|
||||
Check(QuestWikiText.Batches(titles).Count == 3, "titles in batches of 50");
|
||||
string url = QuestWikiText.ApiUrl(CommunityWikiFeed.Api, ("action", "query"), ("titles", "A B|C&D"));
|
||||
Check(url.StartsWith("https://asheron.fandom.com/api.php?format=json&formatversion=2&action=query&titles=A%20B%7CC%26D"), "the API address, values escaped: " + url);
|
||||
|
||||
// ── The feed's pure parts ──
|
||||
Check(CommunityWikiFeed.RankOf("Category:Society Quests: Knight Rank") == "Knight" && CommunityWikiFeed.RankOf("Category:Joining a Society Quests") == "Joining"
|
||||
&& CommunityWikiFeed.RankOf("Category:Other") == "", "society ranks from category names");
|
||||
Check(CommunityWikiFeed.SkipCategory("Category:Quest Items") && CommunityWikiFeed.SkipCategory("Category:Quest NPCs")
|
||||
&& !CommunityWikiFeed.SkipCategory("Category:Society Quests"), "item and NPC lists aren't followed");
|
||||
var old = new QuestGuide { Reader = QuestWikiText.ReaderVersion, UpdatedUtc = DateTime.UtcNow.AddHours(-1) };
|
||||
old.Quests.Add(new GuideQuest { Title = "Same", Rev = 1 });
|
||||
old.Quests.Add(new GuideQuest { Title = "Edited", Rev = 1 });
|
||||
old.Quests.Add(new GuideQuest { Title = "Dropped", Rev = 1 });
|
||||
var listed = new Dictionary<string, long> { ["Same"] = 1, ["Edited"] = 2, ["New"] = 3 };
|
||||
List<string> toRead = CommunityWikiFeed.PagesToRead(old, listed);
|
||||
Check(toRead.Count == 2 && toRead.Contains("Edited") && toRead.Contains("New"), "only new and edited pages are read");
|
||||
Check(CommunityWikiFeed.PagesToRead(new QuestGuide { Reader = 0, Quests = { new GuideQuest { Title = "Same", Rev = 1 } } }, new Dictionary<string, long> { ["Same"] = 1 }).Count == 1,
|
||||
"a guide from an older reader is read again whole");
|
||||
var fresh = new Dictionary<string, GuideQuest> { ["Edited"] = new GuideQuest { Title = "Edited", Rev = 2 }, ["New"] = new GuideQuest { Title = "New", Rev = 3 } };
|
||||
QuestGuide merged = CommunityWikiFeed.Merge(old, listed, fresh, new Dictionary<string, GuideContract>(), DateTime.UtcNow);
|
||||
Check(merged.Quests.Count == 3 && merged.Find("Edited")!.Rev == 2 && merged.Find("Same") != null && merged.Find("Dropped") == null
|
||||
&& merged.Source == CommunityWikiFeed.Host, "the merge: fresh pages, kept pages, dropped pages gone");
|
||||
Check(!CommunityWikiFeed.Due(old, DateTime.UtcNow) && CommunityWikiFeed.Due(old, DateTime.UtcNow.AddDays(1)) && CommunityWikiFeed.Due(new QuestGuide(), DateTime.UtcNow),
|
||||
"read again once a day old (or when there is none)");
|
||||
|
||||
// ── Off by default; it says what it reads and from where ──
|
||||
Check(!new OracleSettings().WikiFeedOn, "the feed is off by default");
|
||||
var feed = new CommunityWikiFeed(System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RynthOracleTests-" + Guid.NewGuid().ToString("N") + "-feed.json"));
|
||||
Check(!feed.Start(on: false) && !feed.Running && !feed.LoginRead(on: false, daily: true, DateTime.UtcNow), "off: no read starts");
|
||||
Check(CommunityWikiFeed.WhatItReads.Contains("https://asheron.fandom.com/api.php") && CommunityWikiFeed.WhatItReads.Contains("no login"),
|
||||
"the disclosure names the address");
|
||||
OracleContext ctx = Context();
|
||||
ctx.Settings.WikiFeedOn = false;
|
||||
var (readOk, readText) = ctx.ReadWikiNow();
|
||||
Check(!readOk && readText.Contains("off") && readText.Contains("asheron.fandom.com/api.php") && !ctx.Wiki.Running, "Read now with the feed off fetches nothing and says why");
|
||||
Check(ctx.SetWikiFeed(false).Text.Contains("already off"), "turning it off when off says so");
|
||||
Check(OracleCommand.Parse("wiki on") is { Verb: OracleVerb.Wiki, Word: "on" } && OracleCommand.Parse("wiki") is { Verb: OracleVerb.Wiki, Word: "status" }
|
||||
&& OracleCommand.Parse("wiki read") is { Verb: OracleVerb.Wiki, Word: "read" }, "/ro wiki words");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue