RynthSuite as of 2026-10-05 (internal 8b7d487): navigation no longer stalls after doorway turns, faster target and attack, corpses used from a distance and closed after looting, patrol wall clearance, add-to-loot-profile from an item, WCID loot rules, scroll and slayer fixes, release 2026.10.5.1

This commit is contained in:
Tom Bohar 2026-10-05 08:03:08 -04:00
commit 53438c65c1
29 changed files with 3951 additions and 86 deletions

View file

@ -0,0 +1,58 @@
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Tells combat when the plugin's busy count is a leftover rather than a real busy client.
///
/// The plugin counts AC's busy count from the engine's increment/decrement events. A cast or
/// an item use (a corpse open) raises it through the hooked increment, but AC lowers it inline
/// when the server's UseDone (0x01C7) arrives, which the hook never sees (see the engine's
/// BusyCountHooks: "the shadow counter never sees AC's inline UseDone decrement"). The engine's
/// reconciler only decrements what is still in the real field, so after a UseDone there is
/// nothing left for it and no decrement event follows. The plugin's count then sits at 1 until
/// its own watchdog force-clears it 5 s later (CorpseOpenController.CheckBusyTimeout), and
/// combat's "busy, don't attack" gate waits all of that.
///
/// Measured (2026-09-29 caster logs, 157 kills): kill to the next cast median 2.5 s, p90 2.7 s,
/// nearly all of it waiting for busy=0, and the steady cast cadence pinned near 5 s by the
/// force-clear. Melee/missile after a corpse open waited up to 4 s the same way (10-01 log).
///
/// The rule: the count is stale when the server has finished an action (the UseDone count moved)
/// SINCE the count last rose, and no cast gesture is animating. Melee and missile swings raise
/// and lower the count through the hooked calls (CommenceAttack / AttackDone), so a swing in
/// progress is never mistaken for stale: no UseDone arrives for it. Inert without the engine's
/// UseDone counter.
/// </summary>
internal sealed class CombatBusyGate
{
private int _lastCount;
private int _seqAtRise;
private bool _haveRise;
/// <summary>Record a new busy count. A rise remembers the UseDone count at that moment.</summary>
public void NoteCount(int count, int useDoneSeqNow)
{
if (count > _lastCount)
{
_seqAtRise = useDoneSeqNow;
_haveRise = true;
}
if (count <= 0) _haveRise = false;
_lastCount = count;
}
/// <summary>True when the busy count is positive but every action behind it has been finished
/// by the server: a UseDone arrived after the last rise and no cast gesture is animating.</summary>
public bool IsStale(int busyCount, bool hasUseDoneSeq, int useDoneSeqNow, bool gestureInProgress)
{
if (busyCount <= 0 || !hasUseDoneSeq || !_haveRise) return false;
if (gestureInProgress) return false;
return useDoneSeqNow != _seqAtRise;
}
/// <summary>Forget the remembered rise (the count was reset to 0 elsewhere).</summary>
public void Reset()
{
_lastCount = 0;
_haveRise = false;
}
}

View file

@ -0,0 +1,122 @@
using System;
using System.Text;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Measures how long combat takes from locking a target to sending the first attack or cast at
/// it, and what it waited on, so a player's own log answers "why didn't it attack right away".
///
/// CombatManager calls <see cref="OnLock"/> when it locks a new target, <see cref="OnTick"/> once
/// per combat tick with the reason that tick didn't attack (the time since the previous tick is
/// charged to that reason), and <see cref="OnAttack"/> when the first attack or cast goes out.
/// OnAttack returns one line per engagement, at most one per <see cref="MinLineGapMs"/> (the
/// skipped ones are counted into the next line):
///
/// [CombatLatency] lock->attack 180 ms (stance 0, face 60, busy 0, cast 120, interval 0, other 0) Magic 'Olthoi Nymph', kill->attack 210 ms
///
/// Pure: the caller passes the clock. Pump thread only.
/// </summary>
internal sealed class CombatLatencyTracker
{
/// <summary>What a tick waited on. Index into the bucket array.</summary>
public enum Wait
{
/// <summary>Weapon or stance not ready (EquipWeaponAndSetStance said wait).</summary>
Stance,
/// <summary>Turning to face, or the settle after letting go of a held turn.</summary>
Face,
/// <summary>The client busy count (an action still in progress).</summary>
Busy,
/// <summary>Magic gates: the previous cast resolving, the cast gesture, the equip gate.</summary>
Cast,
/// <summary>The attack/cast interval since the previous attack command.</summary>
Interval,
/// <summary>Anything else (stall watchdog, scan grace, distance, no ammo).</summary>
Other,
}
public const double MinLineGapMs = 1000;
private const int WaitCount = 6;
private readonly double[] _waits = new double[WaitCount];
private int _targetId;
private double _lockAtMs = double.NaN;
private double _lastTickMs = double.NaN;
private double _killAtMs = double.NaN;
private double _lastLineAtMs = double.NegativeInfinity;
private int _suppressed;
/// <summary>True between a lock and its first attack.</summary>
public bool Pending => !double.IsNaN(_lockAtMs);
/// <summary>A new target was locked. <paramref name="killAtMs"/> is when the previous target's
/// kill was noticed, or NaN when this lock didn't follow a kill.</summary>
public void OnLock(int targetId, double nowMs, double killAtMs = double.NaN)
{
_targetId = targetId;
_lockAtMs = nowMs;
_lastTickMs = nowMs;
_killAtMs = killAtMs;
Array.Clear(_waits);
}
/// <summary>The lock was dropped before any attack went out.</summary>
public void OnDrop()
{
_lockAtMs = double.NaN;
_lastTickMs = double.NaN;
}
/// <summary>A combat tick that did not attack: charge the time since the previous tick to
/// <paramref name="wait"/>.</summary>
public void OnTick(int targetId, double nowMs, Wait wait)
{
if (!Pending) return;
if (targetId != _targetId) { OnDrop(); return; }
double dt = nowMs - _lastTickMs;
if (dt > 0) _waits[(int)wait] += dt;
_lastTickMs = nowMs;
}
/// <summary>The first attack or cast went out. Returns the log line, or null when nothing was
/// pending for this target or the line is throttled.</summary>
public string? OnAttack(int targetId, double nowMs, string mode, string? targetName)
{
if (!Pending || targetId != _targetId) return null;
// The tick that attacked: whatever it waited on before the attack call was the
// interval/other bookkeeping of that same tick, so its slice goes to Other.
double dt = nowMs - _lastTickMs;
if (dt > 0) _waits[(int)Wait.Other] += dt;
double total = nowMs - _lockAtMs;
double killToAttack = double.IsNaN(_killAtMs) ? double.NaN : nowMs - _killAtMs;
_lockAtMs = double.NaN;
_lastTickMs = double.NaN;
if (nowMs - _lastLineAtMs < MinLineGapMs)
{
_suppressed++;
return null;
}
_lastLineAtMs = nowMs;
var sb = new StringBuilder(160);
sb.Append("[CombatLatency] lock->attack ").Append(Ms(total)).Append(" ms (")
.Append("stance ").Append(Ms(_waits[(int)Wait.Stance]))
.Append(", face ").Append(Ms(_waits[(int)Wait.Face]))
.Append(", busy ").Append(Ms(_waits[(int)Wait.Busy]))
.Append(", cast ").Append(Ms(_waits[(int)Wait.Cast]))
.Append(", interval ").Append(Ms(_waits[(int)Wait.Interval]))
.Append(", other ").Append(Ms(_waits[(int)Wait.Other]))
.Append(") ").Append(mode);
if (!string.IsNullOrEmpty(targetName)) sb.Append(" '").Append(targetName).Append('\'');
if (!double.IsNaN(killToAttack)) sb.Append(", kill->attack ").Append(Ms(killToAttack)).Append(" ms");
if (_suppressed > 0) { sb.Append(" (+").Append(_suppressed).Append(" engagements not logged)"); _suppressed = 0; }
return sb.ToString();
}
/// <summary>The time charged to one wait so far (tests and diagnostics).</summary>
public double Waited(Wait wait) => _waits[(int)wait];
private static long Ms(double v) => (long)Math.Round(Math.Max(0, v));
}

View file

@ -226,8 +226,30 @@ public partial class CombatManager : IDisposable
_host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat;
/// <summary>Client busy count — set by plugin from OnBusyCountIncremented/Decremented.
/// When > 0, combat must not send any game actions (SelectItem, attack, cast).</summary>
public int BusyCount { get; set; }
/// When > 0, combat must not send any game actions (SelectItem, attack, cast) — unless
/// <see cref="_busyGate"/> shows the count is a leftover the server already finished.</summary>
public int BusyCount
{
get => _busyCount;
set
{
_busyCount = value;
_busyGate.NoteCount(value, _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0);
}
}
private int _busyCount;
private readonly CombatBusyGate _busyGate = new();
/// <summary>Resets the plugin's shared busy mirror (not AC's real field) once combat finds the
/// count is a leftover: the same thing BuffManager's cast-resolved callback does for buffs.
/// Set by RynthAiPlugin; the argument says why.</summary>
private Action<string>? _onStaleBusy;
public void SetStaleBusyCallback(Action<string> cb) => _onStaleBusy = cb;
private readonly CombatLatencyTracker _latency = new();
private CombatLatencyTracker.Wait _tickWait = CombatLatencyTracker.Wait.Other;
private bool _attackedThisTick;
private int _lastAttackCmdTargetId; // the target the last attack command (lastAttackCmd) was for
/// <summary>D4 (record-only): human-readable reason combat did NOT cast on the
/// most recent tick (or "cast" when it did). Set at every magic skip site; read
@ -1617,6 +1639,20 @@ public partial class CombatManager : IDisposable
_damageSincePendingCast = false;
}
/// <summary>
/// Take a just-killed (or predicted-killed) monster out of the current scan list. The scan
/// skips <see cref="_recentlyKilled"/> ids, but it runs at most every SCAN_INTERVAL_MS and the
/// kill notice arrives between ticks, so the next tick's target pick still saw the dead mob
/// in the old list and locked it again (score ~140: closest and wounded) — a "lock" of the
/// corpse-to-be right after "DropTarget ... killed", dropped one tick later as "hp=0". On
/// every kill in the 2026-10-01/10-04 Olthoi logs; a cast or swing could go at it.
/// </summary>
private void ForgetScanned(int id)
{
for (int i = _scannedTargets.Count - 1; i >= 0; i--)
if (_scannedTargets[i].Id == id) _scannedTargets.RemoveAt(i);
}
private void DropTarget(string reason)
{
if (activeTargetId != 0)
@ -1673,6 +1709,7 @@ public partial class CombatManager : IDisposable
if (swapId == 0) return;
_recentlyKilled[swapId] = DateTime.Now.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS);
ForgetScanned(swapId);
// Queue this predicted one-shot so it's CREDITED when its death confirms —
// we may swap away before its KillerNotification. Capture the name LIVE
// from the world filter (_fightTargetName is often empty this early).
@ -1840,6 +1877,7 @@ public partial class CombatManager : IDisposable
else if (tid != 0 && curMatches)
{
_recentlyKilled[tid] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS);
ForgetScanned(tid);
DropTarget("killed (KillerNotification)");
}
}
@ -2093,7 +2131,67 @@ public partial class CombatManager : IDisposable
return false;
}
/// <summary>Floor between attack commands for the first cast at a new target when the server
/// gates are available (see <see cref="AttackIntervalMs"/>). Only bounds how fast a refused
/// cast could be retried; a refusal sets the target as the last attacked, so the retry waits
/// the full interval anyway.</summary>
internal const double NewTargetCastFloorMs = 300;
/// <summary>True when <see cref="BusyCount"/> is positive only because AC lowered it inline at a
/// server UseDone the busy hook can't see (see <see cref="CombatBusyGate"/>).</summary>
internal bool BusyIsLeftover()
{
bool gesture = _host.HasGetCastBusyState && !_host.CanCastNow;
return _busyGate.IsStale(BusyCount, _host.HasUseDoneSeq,
_host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0, gesture);
}
/// <summary>Times combat found the busy count was a leftover and went ahead (status/tests).</summary>
internal int StaleBusyResets => _staleBusyResets;
private int _staleBusyResets;
/// <summary>
/// The interval the combat tick waits after an attack command before the next one.
/// Melee/missile: 1000 ms (AC paces swings and shots itself). Magic: the Attack Spell Delay
/// setting (≤0 = 1500), except for the first cast at a new target when the engine has the
/// server gates (UseDone and the cast gesture): those already hold the cast until the
/// previous one is finished, so the new target only waits <see cref="NewTargetCastFloorMs"/>.
/// Casting at the same target keeps the full setting.
/// </summary>
internal static double AttackIntervalMs(int combatMode, int attackSpellIntervalMs, bool hasServerGates, bool newTarget)
{
if (combatMode != CombatMode.Magic) return 1000.0;
double interval = attackSpellIntervalMs > 0 ? attackSpellIntervalMs : 1500;
if (newTarget && hasServerGates) return Math.Min(interval, NewTargetCastFloorMs);
return interval;
}
public bool Think()
{
_tickWait = CombatLatencyTracker.Wait.Other;
_attackedThisTick = false;
bool result = ThinkCore();
// [CombatLatency]: charge this tick to what it waited on, or log the engagement once
// its first attack/cast went out (see CombatLatencyTracker).
if (_latency.Pending)
{
double nowMs = Environment.TickCount64;
if (activeTargetId == 0)
_latency.OnDrop();
else if (_attackedThisTick)
{
string? line = _latency.OnAttack(activeTargetId, nowMs, CombatModeName(CurrentCombatMode),
_worldFilter[activeTargetId]?.Name);
if (line != null) _host.Log(line);
}
else
_latency.OnTick(activeTargetId, nowMs, _tickWait);
}
return result;
}
private bool ThinkCore()
{
if (!_settings.EnableCombat) return false;
@ -2189,9 +2287,15 @@ public partial class CombatManager : IDisposable
else if (target != null && IsSpellProjectileName(target.Name))
DropTarget("spell projectile (not a monster)");
else if (target != null && (int)target.ObjectClass != (int)AcObjectClass.Monster)
{
ForgetScanned(activeTargetId);
DropTarget("became corpse");
}
else if (_worldFilter.GetHealthRatio(activeTargetId) == 0f)
{
ForgetScanned(activeTargetId);
DropTarget("hp=0");
}
else if (target != null &&
_worldFilter.Distance(_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId) > disengageLimit)
DropTarget("out of range");
@ -2315,7 +2419,10 @@ public partial class CombatManager : IDisposable
if (!(CurrentCombatMode == CombatMode.Magic && IsCastInFlight()))
{
if (!EquipWeaponAndSetStance(targetObj, "Auto"))
{
_tickWait = CombatLatencyTracker.Wait.Stance;
return true;
}
}
bool useNative = _settings.UseNativeAttack && _host.HasNativeAttack;
@ -2331,10 +2438,17 @@ public partial class CombatManager : IDisposable
// offensive casts stops back-to-back "You're too busy!" refusals that
// silently drop casts and cost kills. ≤0 (e.g. a pre-existing settings
// file saved before this field existed) falls back to 1500ms.
double attackCmdIntervalMs = CurrentCombatMode == CombatMode.Magic
? (_settings.AttackSpellIntervalMs > 0 ? _settings.AttackSpellIntervalMs : 1500)
: 1000.0;
if ((DateTime.Now - lastAttackCmd).TotalMilliseconds >= attackCmdIntervalMs)
// The first cast at a NEW target (after a kill or a predicted-kill swap) doesn't wait out
// the interval left over from the last target when the engine reports UseDone: the
// cast-resolution gate (UseDone) and the gesture gate (CanCastNow) below already hold it
// until the previous cast is finished, which is what the interval stood in for before
// those gates existed (it predates them, 2026-06-06 vs 06-20). See AttackIntervalMs.
double attackCmdIntervalMs = AttackIntervalMs(CurrentCombatMode, _settings.AttackSpellIntervalMs,
hasServerGates: _host.HasUseDoneSeq && _host.HasGetCastBusyState,
newTarget: activeTargetId != _lastAttackCmdTargetId);
if ((DateTime.Now - lastAttackCmd).TotalMilliseconds < attackCmdIntervalMs)
_tickWait = CombatLatencyTracker.Wait.Interval;
else
{
_offensiveCastThisCycle = false;
// Convert any pending offensive cast whose refusal window has
@ -2343,11 +2457,25 @@ public partial class CombatManager : IDisposable
JudgePendingOffensiveCast();
JudgePendingCast(); // verdict on the last cast once its window elapses
// Client is busy processing a previous action — don't queue more
// Client is busy processing a previous action — don't queue more. Unless the count
// is a leftover: the server finished every action behind it (a UseDone arrived after
// it last rose) and no gesture is animating — AC lowered it inline, where the busy
// hook can't see it, and it would otherwise hold combat until the 5 s force-clear.
// The shared mirror is reset (not AC's real field — the engine reconciler owns that),
// the same as BuffManager does when a buff resolves. See CombatBusyGate.
if (BusyCount > 0)
{
LastCombatSkipReason = "busy-count"; // D4 record-only
return true;
if (!BusyIsLeftover())
{
LastCombatSkipReason = "busy-count"; // D4 record-only
_tickWait = CombatLatencyTracker.Wait.Busy;
return true;
}
int was = BusyCount;
_staleBusyResets++;
_onStaleBusy?.Invoke($"combat: the server finished the action (UseDone) — was {was}");
if (BusyCount > 0) BusyCount = 0; // no callback, or the shared mirror was already 0
_busyGate.Reset();
}
// Magic cadence guard: while a previous combat cast is still
@ -2359,6 +2487,7 @@ public partial class CombatManager : IDisposable
if (CurrentCombatMode == CombatMode.Magic && IsAwaitingCastResolution())
{
LastCombatSkipReason = "cast-cadence"; // D4 record-only (IsCastInFlight)
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
}
@ -2385,12 +2514,14 @@ public partial class CombatManager : IDisposable
_facingTarget = false;
_faceSettledAt = DateTime.Now;
LastCombatSkipReason = "face-settle-release"; // D4 record-only
_tickWait = CombatLatencyTracker.Wait.Face;
return true; // settle tick
}
if (CurrentCombatMode == CombatMode.Magic
&& (DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS)
{
LastCombatSkipReason = "face-settle-wait"; // D4 record-only
_tickWait = CombatLatencyTracker.Wait.Face;
return true; // let the turn-stop settle on the server first
}
}
@ -2413,7 +2544,10 @@ public partial class CombatManager : IDisposable
_faceStartTime = DateTime.Now;
}
if ((DateTime.Now - _faceStartTime).TotalMilliseconds < FACE_TIMEOUT_MS)
{
_tickWait = CombatLatencyTracker.Wait.Face;
return true; // not facing yet, keep waiting
}
}
_facingTarget = false;
ClearCombatTurnMotions();
@ -2453,6 +2587,7 @@ public partial class CombatManager : IDisposable
if ((DateTime.Now - lastAttackCmd).TotalMilliseconds > 5000)
_host.Log($"[CombatCast] CanCastNow=false — gesture gate blocking cast (last attack {(DateTime.Now - lastAttackCmd).TotalMilliseconds:0}ms ago, target=0x{activeTargetId:X8})");
LastCombatSkipReason = "cast-gate"; // D4 record-only (CanCastNow=false)
_tickWait = CombatLatencyTracker.Wait.Cast;
return true;
}
@ -2515,6 +2650,7 @@ public partial class CombatManager : IDisposable
_lastEquipTime = DateTime.Now; // gate AttackWithMagic until wand is wielded
_host.ChangeCombatMode(CombatMode.Magic);
lastAttackCmd = DateTime.Now;
_lastAttackCmdTargetId = activeTargetId;
return true;
}
}
@ -2523,6 +2659,7 @@ public partial class CombatManager : IDisposable
// Physical combat always attacks — spell shape flags (UseArc/Bolt/Ring/Streak)
// are only relevant in magic mode and must not gate melee/missile attacks.
physicalSent = AttackTarget();
if (physicalSent) _attackedThisTick = true;
}
// Ring spells hit an area — no per-target damage feedback is generated,
@ -2537,6 +2674,7 @@ public partial class CombatManager : IDisposable
if (!_lastCastWasRing && (!magicMode || _offensiveCastThisCycle) && physicalSent)
RecordOffensiveCast(activeTargetId);
lastAttackCmd = DateTime.Now;
_lastAttackCmdTargetId = activeTargetId;
// Predicted kill shot (set in AttackWithMagic): the cast we just fired
// is expected to finish this mob. DON'T swap yet — on ACE a war cast is
@ -3119,6 +3257,11 @@ public partial class CombatManager : IDisposable
else
_host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, priority {bestPriority}, {DescribeTargetPos(bestId)})");
// [CombatLatency]: time this engagement from the lock to its first attack.
double lockMs = Environment.TickCount64;
double sinceKillMs = _lastKillAt == DateTime.MinValue ? double.MaxValue : (DateTime.Now - _lastKillAt).TotalMilliseconds;
_latency.OnLock(bestId, lockMs, sinceKillMs <= 2000 ? lockMs - sinceKillMs : double.NaN);
activeTargetId = bestId;
_lockedTargetId = bestId;
_lockedPriority = bestPriority;
@ -4311,6 +4454,7 @@ public partial class CombatManager : IDisposable
/// cast waits for it to resolve on the server (see IsAwaitingCastResolution).</summary>
private void MarkCombatCastIssued()
{
_attackedThisTick = true; // [CombatLatency]: a debuff or attack cast went out
_awaitingCastResolution = true;
_castResolutionDeadline = DateTime.Now.AddMilliseconds(CAST_RESOLUTION_TIMEOUT_MS);
_useDoneSeqAtCast = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
@ -4555,9 +4699,10 @@ public partial class CombatManager : IDisposable
LastCombatSkipReason = "equip-gate"; // D4 record-only
return;
}
// Cadence is the motion-end gate (CanCastNow at the AttackWithMagic
// call site, CombatManager.cs:905) — no fixed inter-cast interval;
// fire as soon as the cast gesture completes.
// Cadence is set in Think before this is called: the previous cast must have resolved
// (UseDone, IsAwaitingCastResolution), its gesture must be over (CanCastNow), and the
// Attack Spell Delay must have passed since the last cast at this same target (the first
// cast at a new target skips that delay when the two server gates exist — AttackIntervalMs).
if (_waitingForDebuffResult)
{
@ -4630,6 +4775,22 @@ public partial class CombatManager : IDisposable
int warTier = _spellManager?.GetHighestSpellTier(AcSkillType.WarMagic) ?? 0;
int voidTier = _spellManager?.GetHighestSpellTier(AcSkillType.VoidMagic) ?? 0;
int offensiveSpellId = FindBestShapedSpell(element, rule, out bool isRing, out int castShape, arcTargetId: activeTargetId);
// No spell of that element known (a low caster whose listed knife says Slash, with no
// Slash war spell): cast an element the character does know rather than nothing every
// cycle (2026-10-02 log; found 2026-10-04). Not when an arc gave way to an obstacle.
if (offensiveSpellId == 0 && !_lastShapeArcGaveWay)
{
foreach (string alt in WeaponPlanner.FallbackOrder)
{
if (alt.Equals(element, StringComparison.OrdinalIgnoreCase)) continue;
int altId = FindBestShapedSpell(alt, rule, out bool altRing, out int altShape, arcTargetId: activeTargetId);
if (altId == 0) continue;
if (_noElementFallbackLogged.Add(element))
_host.Log($"[CombatCast] no {element} attack spell known: casting {alt} instead");
element = alt; offensiveSpellId = altId; isRing = altRing; castShape = altShape;
break;
}
}
LogArcChoice(rule, target, castShape);
if (offensiveSpellId != 0)
{
@ -4711,6 +4872,7 @@ public partial class CombatManager : IDisposable
}
private int _autoElemDiagCount;
private readonly HashSet<string> _noElementFallbackLogged = new(StringComparer.OrdinalIgnoreCase);
private string GetPreferredElement(WorldObject? target, MonsterRule? rule)
{

View file

@ -988,10 +988,16 @@ public class WorldObjectCache
/// Read an STypeInt property from an object via CBaseQualities::InqInt.
/// Returns defaultValue if the API is unavailable or the property is not set.
/// </summary>
/// <summary>Decal's synthetic LongValueKey "Type" (0x0D000000): the object's weenie class id
/// (WCID). VTank profiles match WCIDs with it ("loot everything that isn't retail").</summary>
public const uint DecalTypeKey = 0x0D000000;
public int GetIntProperty(int id, uint stype, int defaultValue)
{
if (!_host.HasGetObjectIntProperty) return defaultValue;
uint uid = unchecked((uint)id);
if (stype == DecalTypeKey)
return _host.HasGetObjectWcid && _host.TryGetObjectWcid(uid, out uint wcid) ? unchecked((int)wcid) : defaultValue;
if (!_host.HasGetObjectIntProperty) return defaultValue;
return _host.TryGetObjectIntProperty(uid, stype, out int v) ? v : defaultValue;
}

View file

@ -215,6 +215,35 @@ public sealed partial class RynthAiPlugin
Log($"[RynthAi] shadow busy-reset on cast resolve (was {was}, {reason}) — real field left to the engine reconciler");
}
// CombatManager calls this when the busy count holding its attack is a leftover: the server
// finished every action behind it (a UseDone arrived after it last rose) and no gesture is
// animating — AC lowered the real field inline, where the busy hook can't see it (see
// CombatBusyGate). Same as OnBuffCastResolved: the shadow only, the real field stays with the
// engine reconciler, and it spares CheckBusyTimeout's real-field force-clear 5 s later.
// Logged at most every 10 s (it can happen on every cast).
private long _lastCombatBusyStaleLogAt;
private int _combatBusyStaleSinceLog;
private void OnCombatBusyStale(string reason)
{
if (_busyCount <= 0) return;
int was = _busyCount;
_busyCount = 0;
_busyCountLastIncrementAt = 0;
_busyCountBecamePositiveAt = 0;
if (_combatManager != null) _combatManager.BusyCount = 0;
if (_buffManager != null) _buffManager.BusyCount = 0;
_combatBusyStaleSinceLog++;
long now = CorpseNowMs;
if (now - _lastCombatBusyStaleLogAt >= 10_000)
{
string count = _lastCombatBusyStaleLogAt == 0 ? "first"
: $"{_combatBusyStaleSinceLog} in the last {(now - _lastCombatBusyStaleLogAt) / 1000.0:0}s";
Log($"[RynthAi] shadow busy-reset by combat (was {was}, {reason}; {count}) — real field left to the engine reconciler");
_lastCombatBusyStaleLogAt = now;
_combatBusyStaleSinceLog = 0;
}
}
private long _lastCorpsePruneAt;
private const long CorpsePruneIntervalMs = 60_000; // prune once per minute
// Retain a completed-corpse mark this long. Must exceed the longest AC corpse
@ -285,9 +314,9 @@ public sealed partial class RynthAiPlugin
return;
}
// _completedCorpses is authoritative. FinalizeCorpse deliberately leaves a
// looted corpse open server-side, so AC re-announces its contents every time
// it re-streams into range on a patrol loop. Treat any reopen of a completed
// _completedCorpses is authoritative. On an engine without CloseContainer (API
// before v76) a looted corpse stays open server-side, so AC re-announces its
// contents every time it re-streams into range on a patrol loop. Treat any reopen of a completed
// corpse as a passive re-announce: never clear the mark, never start a loot
// session. Membership alone decides — same rule the polling reconciler
// already enforces in SyncCorpseContainerState. A corpse NOT in the set
@ -1993,10 +2022,13 @@ public sealed partial class RynthAiPlugin
_pendingManaStoneIds.Clear(); _pendingManaTapIds.Clear(); _pendingKeepUpTo.Clear();
ResetCurrentLootItem();
// Clear container state immediately. Do NOT send UseObject(corpse) to close it —
// that increments busy count and blocks the next open until the server acks the close.
// The server will auto-close this corpse when the next UseObject open is sent.
// SyncCorpseContainerState guards against re-claiming via _completedCorpses.
// Close the loot window (CloseCorpseContainer: the client's own close packet, which
// adds nothing to the busy count; never UseObject(corpse), which does and blocks the
// next open until the server acks it). Engines without it keep the old behaviour: the
// server closes this corpse when the next UseObject open is sent.
// Clear container state immediately; SyncCorpseContainerState guards against
// re-claiming via _completedCorpses until the server's close lands.
CloseCorpseContainer(corpseId, "completed");
if (_openedContainerId == corpseId)
{
_openedContainerId = 0;
@ -2363,6 +2395,49 @@ public sealed partial class RynthAiPlugin
_corpseTargetSince = now - _corpseHoldFrozenAge;
}
/// <summary>
/// Closes the loot window of a corpse the bot is done with, when it is the open container:
/// Host.CloseContainer (API v76) sends the 0x0195 NoLongerViewingContents game action, the
/// packet the client sends when the player closes the window. It is not an inventory request:
/// AC's busy count doesn't move (no OnBusyCountIncremented, so the next open isn't held) and
/// the client's one pending item request is left alone. The engine queues it on AC's main
/// thread ahead of the next corpse's UseObject. The server answers with CloseGroundContainer,
/// which closes the window and brings OnStopViewingObjectContents. Older engines: nothing
/// (the server closes the corpse when the next one is opened, as before).
/// </summary>
private void CloseCorpseContainer(int corpseId, string why)
{
if (corpseId == 0 || !Host.HasCloseContainer)
return;
bool isOpen = _openedContainerId == corpseId
|| (Host.HasGetGroundContainerId && unchecked((int)Host.GetGroundContainerId()) == corpseId);
if (!isOpen)
return;
if (Host.CloseContainer(unchecked((uint)corpseId)))
LootDiag($"[RynthAi] Corpse loot: closing 0x{(uint)corpseId:X8} ({why}).");
else
LootDiag($"[RynthAi] Corpse loot: close of 0x{(uint)corpseId:X8} not sent ({why}).");
}
/// <summary>
/// The macro was switched off with a corpse open: close it (the corpse isn't marked
/// completed, so a later run can still loot what is left). The open-container state is
/// cleared by the server's answer (OnStopViewingObjectContents), as for a window the
/// player closes. Called once, on the running-to-stopped transition, so a corpse the
/// player opens by hand while the macro is off is never closed.
/// </summary>
private void CloseOpenCorpseOnMacroStop()
{
int corpseId = _openedContainerId;
if (corpseId == 0 || !IsCorpseLikeObject(corpseId))
return;
ResetCurrentLootItem();
CloseCorpseContainer(corpseId, "macro stopped");
}
private void AbandonCurrentCorpse(long now, string reason)
{
int corpseId = _targetCorpseId != 0 ? _targetCorpseId : _openedContainerId;
@ -2394,8 +2469,10 @@ public sealed partial class RynthAiPlugin
LootDiag($"[RynthAi] Corpse loot: 0x{(uint)corpseId:X8} was never opened (abandon #{abandons}) — retry in {NeverOpenedAbandonRetryMs / 1000}s instead of completed-marking.");
}
// Force-clear container state — don't try UseObject to close.
// The server will auto-close when we open the next corpse or move away.
// Close it the client's way (no busy count; see CloseCorpseContainer) and force-clear
// container state. Never UseObject to close. Without CloseContainer the server closes
// it when we open the next corpse or move away.
CloseCorpseContainer(corpseId, "abandoned");
if (_openedContainerId == corpseId)
{
_openedContainerId = 0;

View file

@ -62,11 +62,42 @@ internal sealed class DungeonGeometry
private readonly Dictionary<uint, List<Vector3[]>> _floors = new();
private readonly Dictionary<uint, List<WallSeg>> _walls = new();
// Every floor polygon and wall of the landblock, bucketed on a grid, for clearance.
private readonly List<FloorPoly> _floorAll = new();
private readonly Dictionary<long, List<int>> _floorGrid = new();
private readonly List<WallSeg> _wallAll = new();
private readonly Dictionary<long, List<int>> _wallGrid = new();
private readonly struct WallSeg
{
public readonly double X0, Y0, X1, Y1, ZMin, ZMax;
public WallSeg(double x0, double y0, double x1, double y1, double zMin, double zMax)
{ X0 = x0; Y0 = y0; X1 = x1; Y1 = y1; ZMin = zMin; ZMax = zMax; }
public readonly Vector3[]? Poly; // the wall polygon, for its height at a point along it
public WallSeg(double x0, double y0, double x1, double y1, double zMin, double zMax, Vector3[]? poly = null)
{ X0 = x0; Y0 = y0; X1 = x1; Y1 = y1; ZMin = zMin; ZMax = zMax; Poly = poly; }
/// <summary>The wall's height range straight above (x, y), a point on its footprint: a
/// wall over a ramp, or the face above an arch, doesn't reach down to the floor all along.</summary>
public (double Lo, double Hi) ZRangeAt(double x, double y)
{
if (Poly == null) return (ZMin, ZMax);
double ux = X1 - X0, uy = Y1 - Y0, len = Math.Sqrt(ux * ux + uy * uy);
if (len < 1e-9) return (ZMin, ZMax);
ux /= len; uy /= len;
double s = (x - X0) * ux + (y - Y0) * uy;
double lo = double.MaxValue, hi = double.MinValue;
int n = Poly.Length;
for (int i = 0; i < n; i++)
{
var a = Poly[i]; var b = Poly[(i + 1) % n];
double sa = (a.X - X0) * ux + (a.Y - Y0) * uy, sb = (b.X - X0) * ux + (b.Y - Y0) * uy;
if ((s < Math.Min(sa, sb) - 1e-6) || (s > Math.Max(sa, sb) + 1e-6)) continue;
double z;
if (Math.Abs(sb - sa) < 1e-9) { lo = Math.Min(lo, Math.Min(a.Z, b.Z)); hi = Math.Max(hi, Math.Max(a.Z, b.Z)); continue; }
z = a.Z + (b.Z - a.Z) * (s - sa) / (sb - sa);
lo = Math.Min(lo, z); hi = Math.Max(hi, z);
}
return lo <= hi ? (lo, hi) : (ZMin, ZMax);
}
}
public int DoorwayCount => _doorways.Count;
@ -95,6 +126,7 @@ internal sealed class DungeonGeometry
if (!IsUpwardFloor(v)) continue; // the "floor" list holds ceilings too
if (!g._floors.TryGetValue(cell, out var list)) g._floors[cell] = list = new List<Vector3[]>();
list.Add(v);
g.AddFloorToGrid(v);
}
foreach (var (cell, v) in wallPolys)
@ -103,6 +135,7 @@ internal sealed class DungeonGeometry
if (!TryWallFootprint(v, out var seg)) continue;
if (!g._walls.TryGetValue(cell, out var list)) g._walls[cell] = list = new List<WallSeg>();
list.Add(seg);
g.AddWallToGrid(seg);
}
// Portal polygons per cell: centre, horizontal normal, width.
@ -228,7 +261,7 @@ internal sealed class DungeonGeometry
if (p.Z > maxZ) maxZ = p.Z;
}
if (maxS - minS < 0.05) return false;
seg = new WallSeg(sx0, sy0, sx1, sy1, minZ, maxZ);
seg = new WallSeg(sx0, sy0, sx1, sy1, minZ, maxZ, v);
return true;
}
@ -248,6 +281,13 @@ internal sealed class DungeonGeometry
public bool TryGetDoorway(uint a, uint b, out DungeonDoorway door) => _doorways.TryGetValue(EdgeKey(a, b), out door!);
/// <summary>Openings whose centre is within r (horizontally) of (x, y) and 2 m of height z.</summary>
public IEnumerable<DungeonDoorway> DoorwaysNear(double x, double y, double z, double r)
{
foreach (var d in _doorways.Values)
if ((d.X - x) * (d.X - x) + (d.Y - y) * (d.Y - y) <= r * r && Math.Abs(d.Z - z) < 2.0) yield return d;
}
public bool HasFloor(uint cell) => _floors.ContainsKey(cell);
/// <summary>True when (x, y) is on one of the cell's floor polygons, the floor at most 1 m
@ -325,6 +365,404 @@ internal sealed class DungeonGeometry
return true;
}
// ── Clearance from walls ────────────────────────────────────────────────
//
// How far a character standing at a point is from anything it can't walk into: an upright
// wall reaching above step height, or the edge of the walkable floor (a drop, or a slope
// too steep to stand on, like the raised sides of the Olthoi hive's corridors). Measured
// over the whole landblock, not one cell: a point beside a doorway is close to the next
// cell's walls too. Probed along 16 directions in 0.1 m steps, following the floor up and
// down ramps, plus the exact distance to the nearest wall.
/// <summary>AC's walkable slope limit (PhysicsGlobals.FloorZ = 0.66417, about 48 degrees):
/// a steeper "floor" polygon is a slope the character slides off, so it bounds the floor.</summary>
public const double WalkableNz = 0.664;
private const double GridCell = 4.0;
private const int ProbeDirs = 16;
private const double ProbeStep = 0.1;
// Height change allowed between two probe steps 0.1 m apart: a 48 degree slope rises 0.11,
// a stair 0.25; more is a ledge.
private const double ProbeMaxRise = 0.3;
// A wall counts for clearance when it reaches into this band above the floor: lower lips
// are stepped over (the human Setup's step-up height is 0.45; see PatrolProof "human").
private const double ClearWallLow = 0.45, ClearWallHigh = 1.8;
private sealed class FloorPoly
{
public Vector3[] V = null!;
public double Nx, Ny, Nz, Px, Py, Pz; // unit normal and a point on the plane
public double MinX, MinY, MaxX, MaxY;
public bool Walkable;
public double HeightAt(double x, double y) => Pz - (Nx * (x - Px) + Ny * (y - Py)) / Nz;
}
private static long GridKey(int gx, int gy) => ((long)gx << 32) ^ (uint)gy;
private static int GridOf(double v) => (int)Math.Floor(v / GridCell);
private void AddFloorToGrid(Vector3[] v)
{
NewellNormal(v, out double nx, out double ny, out double nz);
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
if (len < 1e-9 || nz <= 1e-9) return;
var f = new FloorPoly { V = v, Nx = nx / len, Ny = ny / len, Nz = nz / len, MinX = double.MaxValue, MinY = double.MaxValue, MaxX = double.MinValue, MaxY = double.MinValue };
double sx = 0, sy = 0, sz = 0;
foreach (var p in v)
{
sx += p.X; sy += p.Y; sz += p.Z;
f.MinX = Math.Min(f.MinX, p.X); f.MaxX = Math.Max(f.MaxX, p.X);
f.MinY = Math.Min(f.MinY, p.Y); f.MaxY = Math.Max(f.MaxY, p.Y);
}
f.Px = sx / v.Length; f.Py = sy / v.Length; f.Pz = sz / v.Length;
f.Walkable = f.Nz >= WalkableNz;
int idx = _floorAll.Count;
_floorAll.Add(f);
for (int gx = GridOf(f.MinX); gx <= GridOf(f.MaxX); gx++)
for (int gy = GridOf(f.MinY); gy <= GridOf(f.MaxY); gy++)
{
long k = GridKey(gx, gy);
if (!_floorGrid.TryGetValue(k, out var list)) _floorGrid[k] = list = new List<int>();
list.Add(idx);
}
}
private void AddWallToGrid(WallSeg w)
{
int idx = _wallAll.Count;
_wallAll.Add(w);
for (int gx = GridOf(Math.Min(w.X0, w.X1)); gx <= GridOf(Math.Max(w.X0, w.X1)); gx++)
for (int gy = GridOf(Math.Min(w.Y0, w.Y1)); gy <= GridOf(Math.Max(w.Y0, w.Y1)); gy++)
{
long k = GridKey(gx, gy);
if (!_wallGrid.TryGetValue(k, out var list)) _wallGrid[k] = list = new List<int>();
list.Add(idx);
}
}
/// <summary>The floor under (x, y) nearest in height to zRef, at most <paramref name="up"/>
/// above and <paramref name="down"/> below it, of any cell. <paramref name="walkable"/>:
/// flat enough to stand on.</summary>
private bool FloorUnder(double x, double y, double zRef, double up, double down, out double h, out bool walkable)
{
if (FloorUnderExact(x, y, zRef, up, down, out h, out walkable)) return true;
// A point exactly on the seam between two polygons can fall outside both.
return FloorUnderExact(x + 1.3e-3, y + 0.7e-3, zRef, up, down, out h, out walkable);
}
private bool FloorUnderExact(double x, double y, double zRef, double up, double down, out double h, out bool walkable)
{
h = 0; walkable = false;
if (!_floorGrid.TryGetValue(GridKey(GridOf(x), GridOf(y)), out var list)) return false;
double best = double.MaxValue;
foreach (int i in list)
{
var f = _floorAll[i];
if (x < f.MinX || x > f.MaxX || y < f.MinY || y > f.MaxY) continue;
if (!InsidePolygon2D(f.V, x, y)) continue;
double fh = f.HeightAt(x, y), dz = fh - zRef;
if (dz > up || dz < -down) continue;
if (Math.Abs(dz) < best) { best = Math.Abs(dz); h = fh; walkable = f.Walkable; }
}
return best < double.MaxValue;
}
/// <summary>True when (x, y) stands on walkable floor (any cell) about height z.</summary>
public bool OnWalkableFloor(double x, double y, double z)
=> FloorUnder(x, y, z, FloorAbove, FloorBelow, out _, out bool w) && w;
/// <summary>
/// How far (metres, up to <paramref name="maxR"/>) a character at (x, y), floor height about
/// z, is from the nearest wall or edge of the walkable floor. 0 when the point is off the
/// floor (in or behind a wall, on a slope too steep to stand on). Where the landblock has no
/// floor data near the point, only walls are measured.
/// </summary>
public double Clearance(double x, double y, double z, double maxR = 3.0)
{
bool floorKnown = FloorUnder(x, y, z, FloorAbove, FloorBelow, out double h0, out bool walk);
if (floorKnown && !walk) return 0;
if (!floorKnown)
{
if (FloorNear(x, y, z)) return 0; // past the floor's edge: in or behind a wall
h0 = z;
}
double best = maxR;
for (int k = 0; k < ProbeDirs && best > 0; k++)
{
double a = k * (2 * Math.PI / ProbeDirs);
best = Math.Min(best, FreeRun(x, y, h0, Math.Cos(a), Math.Sin(a), best, floorKnown));
}
return Math.Min(best, WallDistance(x, y, h0 + ClearWallLow, h0 + ClearWallHigh, best));
}
// Clearance is asked again and again for the same spots (a patrol passes a doorway several
// times a lap; every standoff is tried in turn): remembered to the centimetre.
private readonly Dictionary<(long, long, long, int), double> _clearanceMemo = new();
internal double ClearanceMemo(double x, double y, double z, double maxR)
{
var key = ((long)Math.Round(x * 100), (long)Math.Round(y * 100), (long)Math.Round(z * 10), (int)Math.Round(maxR * 100));
if (_clearanceMemo.TryGetValue(key, out double c)) return c;
if (_clearanceMemo.Count > 200_000) _clearanceMemo.Clear();
return _clearanceMemo[key] = Clearance(x, y, z, maxR);
}
/// <summary>
/// Moves (x, y) to where a character has <paramref name="want"/> clearance, at most
/// <paramref name="maxMove"/> from where it started, staying on walkable floor (and on the
/// floor of <paramref name="cells"/> when given): away from the walls and floor edges it is
/// too close to, each probe direction that hits something within reach pushing the other
/// way. Between two walls closer than 2 x want it ends on the middle line. A point off the
/// floor (a dead end's cell origin inside its end cap) first goes to the nearest floor.
/// Returns the clearance where it ends; the point is left alone when nothing is better.
/// </summary>
public double PushClear(ref double x, ref double y, double z, double want, double maxMove, IReadOnlyCollection<uint>? cells = null)
{
double reach = want + 0.5;
double ox = x, oy = y;
double c = ClearanceMemo(x, y, z, reach);
if (c >= want) return c;
bool Allowed(double px, double py)
=> (px - ox) * (px - ox) + (py - oy) * (py - oy) <= maxMove * maxMove + 1e-9
&& OnWalkableFloor(px, py, z)
&& (cells == null || OnFloorOfAny(cells, px, py, z));
if (c <= 0 && !OnWalkableFloor(x, y, z))
{
// Off the floor: the ring nearest the point that has floor with any room, its best spot.
bool found = false;
for (double r = 0.1; r <= maxMove + 1e-9 && !found; r += 0.1)
{
double bx = 0, by = 0, bc = 0;
for (int k = 0; k < ProbeDirs; k++)
{
double a = k * (2 * Math.PI / ProbeDirs);
double px = ox + Math.Cos(a) * r, py = oy + Math.Sin(a) * r;
if (!Allowed(px, py)) continue;
double pc = ClearanceMemo(px, py, z, reach);
if (pc > bc) { bc = pc; bx = px; by = py; }
}
if (bc > 0) { x = bx; y = by; c = bc; found = true; }
}
if (!found) return c;
}
for (int iter = 0; iter < 16 && c < want; iter++)
{
var runs = ProbeRuns(x, y, z, reach);
double vx = 0, vy = 0;
for (int k = 0; k < ProbeDirs; k++)
{
double push = want - runs[k];
if (push <= 0) continue;
double a = k * (2 * Math.PI / ProbeDirs);
vx -= Math.Cos(a) * push;
vy -= Math.Sin(a) * push;
}
double vl = Math.Sqrt(vx * vx + vy * vy);
if (vl < 1e-9) break;
vx /= vl; vy /= vl;
bool moved = false;
for (double step = Math.Max(0.05, want - c); step >= 0.02 && !moved; step *= 0.5)
{
double px = x + vx * step, py = y + vy * step;
if (!Allowed(px, py)) continue;
double pc = ClearanceMemo(px, py, z, reach);
if (pc > c + 0.01) { x = px; y = py; c = pc; moved = true; }
}
if (!moved) break;
}
if (c >= want) return c;
// The push found no way out (the point sits right on a wall line or a floor corner, where
// every probe stops at once): the nearest spot round it that has the clearance, else the
// clearest spot within reach.
double rx = x, ry = y, rc = c;
for (double r = 0.1; r <= maxMove + 1e-9 && rc < want; r += 0.1)
for (int k = 0; k < ProbeDirs; k++)
{
double a = k * (2 * Math.PI / ProbeDirs);
double px = x + Math.Cos(a) * r, py = y + Math.Sin(a) * r;
if (!Allowed(px, py)) continue;
double pc = ClearanceMemo(px, py, z, reach);
if (pc > rc + 0.02) { rx = px; ry = py; rc = pc; }
}
if (rc > c) { x = rx; y = ry; c = rc; }
return c;
}
/// <summary>
/// The least clearance (up to maxR) along the straight walk from p0 to p1, leaving out
/// <paramref name="skipEnds"/> at each end (the end points are judged on their own),
/// sampled every 0.4 m following the floor up and down ramps; where it is least in
/// (wx, wy, wz). maxR when the walk is shorter than the two ends.
/// </summary>
public double LegClearance(double x0, double y0, double z0, double x1, double y1, double z1,
double maxR, double skipEnds, out double wx, out double wy, out double wz)
{
wx = (x0 + x1) * 0.5; wy = (y0 + y1) * 0.5; wz = (z0 + z1) * 0.5;
double dx = x1 - x0, dy = y1 - y0, len = Math.Sqrt(dx * dx + dy * dy);
if (len <= 2 * skipEnds) return maxR;
int steps = Math.Max(1, (int)Math.Ceiling((len - 2 * skipEnds) / 0.4));
double best = maxR, zf = z0;
for (int i = 0; i <= steps; i++)
{
double d = skipEnds + (len - 2 * skipEnds) * i / steps, t = d / len;
double x = x0 + dx * t, y = y0 + dy * t, zl = z0 + (z1 - z0) * t;
if (TryFloorHeight(x, y, zf, 0.6, out double h)) zf = h;
else if (TryFloorHeight(x, y, zl, 0.6, out h)) zf = h;
else zf = zl;
double c = ClearanceMemo(x, y, zf, maxR);
if (c < best) { best = c; wx = x; wy = y; wz = zf; }
}
return best;
}
/// <summary>Distances (metres, up to maxR) from (x, y) to the first wall or floor edge along
/// each of the 16 probe directions (k * 22.5 degrees from east, counter-clockwise).</summary>
internal double[] ProbeRuns(double x, double y, double z, double maxR)
{
var runs = new double[ProbeDirs];
bool floorKnown = FloorUnder(x, y, z, FloorAbove, FloorBelow, out double h0, out bool walk);
if (floorKnown && !walk) return runs;
if (!floorKnown) h0 = z;
for (int k = 0; k < ProbeDirs; k++)
{
double a = k * (2 * Math.PI / ProbeDirs);
runs[k] = FreeRun(x, y, h0, Math.Cos(a), Math.Sin(a), maxR, floorKnown);
}
return runs;
}
// Any floor (steep or not) at about the point's height within 2 m of a point that has none
// under it: the point is past the floor's edge (a dead end's cell origin is inside its end
// cap), not in a cell whose floor the dats don't give (0x0174 has such cells above others).
private bool FloorNear(double x, double y, double z)
{
for (double r = 0.5; r <= 2.0 + 1e-9; r += 0.5)
for (int k = 0; k < 8; k++)
{
double a = k * Math.PI / 4;
if (FloorUnder(x + Math.Cos(a) * r, y + Math.Sin(a) * r, z, FloorAbove, 1.5, out _, out _)) return true;
}
return false;
}
/// <summary>The height of the floor (any cell) under (x, y) nearest zRef, within
/// <paramref name="band"/> above or below it.</summary>
internal bool TryFloorHeight(double x, double y, double zRef, double band, out double h)
=> FloorUnder(x, y, zRef, band, band, out h, out _);
// Distance along (dx, dy) from (x, y) to the first wall crossed or the first step off the
// walkable floor, following the floor's height; maxR when nothing is hit.
private double FreeRun(double x, double y, double h0, double dx, double dy, double maxR, bool checkFloor)
{
double px = x, py = y, ph = h0, prevR = 0;
int n = (int)Math.Ceiling(maxR / ProbeStep - 1e-9);
for (int i = 1; i <= n; i++)
{
double r = Math.Min(i * ProbeStep, maxR);
double qx = x + dx * r, qy = y + dy * r, qh = ph;
if (checkFloor && (!FloorUnder(qx, qy, ph, ProbeMaxRise, ProbeMaxRise, out qh, out bool w) || !w))
return prevR + (r - prevR) * 0.5;
if (WallHit(px, py, qx, qy, Math.Min(ph, qh) + ClearWallLow, Math.Max(ph, qh) + ClearWallHigh, out double t))
return prevR + (r - prevR) * t;
px = qx; py = qy; ph = qh; prevR = r;
}
return maxR;
}
// The first wall (reaching into zLo..zHi) the segment p0-p1 crosses, as a fraction along it.
private bool WallHit(double x0, double y0, double x1, double y1, double zLo, double zHi, out double t)
{
t = 1;
bool hit = false;
// Every bucket the step touches (a wall is in every bucket its own box touches).
for (int gx = GridOf(Math.Min(x0, x1)); gx <= GridOf(Math.Max(x0, x1)); gx++)
for (int gy = GridOf(Math.Min(y0, y1)); gy <= GridOf(Math.Max(y0, y1)); gy++)
{
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
foreach (int i in list)
{
var w = _wallAll[i];
if (w.ZMax < zLo || w.ZMin > zHi) continue;
if (!SegmentParam(x0, y0, x1, y1, w.X0, w.Y0, w.X1, w.Y1, out double s) || s >= t) continue;
var (lo, hi) = w.ZRangeAt(x0 + (x1 - x0) * s, y0 + (y1 - y0) * s);
if (hi < zLo || lo > zHi) continue;
t = s; hit = true;
}
}
return hit;
}
/// <summary>Walls (footprint and height range) within r of (x, y), for offline inspection.</summary>
internal List<(double X0, double Y0, double X1, double Y1, double ZMin, double ZMax, double Dist)> WallsNear(double x, double y, double r)
{
var res = new List<(double, double, double, double, double, double, double)>();
var seen = new HashSet<int>();
for (int gx = GridOf(x - r); gx <= GridOf(x + r); gx++)
for (int gy = GridOf(y - r); gy <= GridOf(y + r); gy++)
{
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
foreach (int i in list)
{
if (!seen.Add(i)) continue;
var w = _wallAll[i];
double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
var (lo, hi) = w.ZRangeAt(cx, cy); // its height range at the nearest point
if (d <= r) res.Add((w.X0, w.Y0, w.X1, w.Y1, lo, hi, d));
}
}
return res;
}
// Exact distance from (x, y) to the nearest wall reaching into zLo..zHi, up to maxR.
private double WallDistance(double x, double y, double zLo, double zHi, double maxR)
{
double best = maxR;
for (int gx = GridOf(x - maxR); gx <= GridOf(x + maxR); gx++)
for (int gy = GridOf(y - maxR); gy <= GridOf(y + maxR); gy++)
{
if (!_wallGrid.TryGetValue(GridKey(gx, gy), out var list)) continue;
foreach (int i in list)
{
var w = _wallAll[i];
if (w.ZMax < zLo || w.ZMin > zHi) continue;
double d = PointSegDist(x, y, w.X0, w.Y0, w.X1, w.Y1, out double cx, out double cy);
if (d >= best) continue;
var (lo, hi) = w.ZRangeAt(cx, cy);
if (hi < zLo || lo > zHi) continue;
best = d;
}
}
return best;
}
private static double PointSegDist(double px, double py, double ax, double ay, double bx, double by)
=> PointSegDist(px, py, ax, ay, bx, by, out _, out _);
private static double PointSegDist(double px, double py, double ax, double ay, double bx, double by, out double cx, out double cy)
{
double dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy;
double t = len2 < 1e-12 ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / len2, 0, 1);
cx = ax + dx * t; cy = ay + dy * t;
return Math.Sqrt((cx - px) * (cx - px) + (cy - py) * (cy - py));
}
// Where segment a-b meets segment c-d, as a fraction along a-b (touching counts).
private static bool SegmentParam(double ax, double ay, double bx, double by,
double cx, double cy, double dx, double dy, out double t)
{
t = 0;
double rx = bx - ax, ry = by - ay, sx = dx - cx, sy = dy - cy;
double den = rx * sy - ry * sx;
if (Math.Abs(den) < 1e-12) return false;
double qx = cx - ax, qy = cy - ay;
t = (qx * sy - qy * sx) / den;
double u = (qx * ry - qy * rx) / den;
return t >= 0 && t <= 1 && u >= 0 && u <= 1;
}
// ── Helpers ─────────────────────────────────────────────────────────────
internal static ulong EdgeKey(uint a, uint b)

View file

@ -40,11 +40,27 @@ internal sealed class DungeonRooms
internal static partial class DungeonPathfinder
{
// Approach / exit points: this far in front of / beyond the opening's centre, shortened
// (down to the last value) until the point is on the cell's floor.
// (in DoorwayStandoffStep steps, down to the shortest) until the point is on the cell's
// floor AND clear of walls (WallClearance).
// 4 m (was 2.5): at 2.5 the turn into the opening still began close enough to climb the
// raised sides of a hallway mouth (Tom, 2026-10-04: "plenty of room to get into the hallway").
private static readonly double[] DoorwayStandoffs = { 4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0 };
// Room crossings must keep this much room either side of the walking line.
private const double DoorwayStandoffLongest = 4.0, DoorwayStandoffShortest = 1.0, DoorwayStandoffStep = 0.25;
// Every point laid keeps at least this far from walls and floor edges where the space
// allows. The character is a 0.48 m sphere stack (human Setup 0x02000001, PatrolProof
// "human"); the other half metre is steering slack: the arrival ring, the arc of a turn
// begun at speed, the sweep pass. Points closer than this put the character's body on the
// wall when it arrives and it stuck there (Tom, 2026-10-04, testing 2026.10.4.x: "nav
// points ... almost in the wall"). Measured with PatrolProof "clear": in crypts and
// castles most approach/exit points in short bend and junction cells sat on the bend's
// outer wall (Rithwic Crypt: 440 of 488 under 0.25 m), and a dead end's look-in point is
// its cell origin, which is inside the end cap.
internal const double WallClearance = 1.0;
// How far a point may be pushed off where its rule put it to get that clearance.
private const double DoorwayPushMax = 2.0, CornerPushMax = 1.5, MiddlePushMax = 4.5;
// Room crossings keep WallClearance either side of the walking line where the room allows,
// else at least this much (the crossing as it was before the clearance work).
private const double CrossingClearance = 0.5;
// Emitted points closer than this to the previous one are dropped.
private const double MinPointSpacing = 0.3;
@ -393,9 +409,108 @@ internal static partial class DungeonPathfinder
CrossRoom(pts, graph, geo, rooms, rd, prev, prevCell, dest, destCell, revisit: false);
DropCollinear(pts, closed);
KeepLegsOffWalls(geo, pts, closed);
return pts;
}
// A leg brushing a wall: its least clearance (away from its end points) under this, or under
// its end points' own when they are tighter (a narrow opening's centre).
private const double LegMinClearance = 0.6;
private const double LegEndSkip = 0.5, LegCornerPushMax = 2.5, LegCornerSearch = 4.0;
/// <summary>
/// Every leg between consecutive points is walked along (DungeonGeometry.LegClearance) and
/// where it passes closer to a wall than LegMinClearance (cutting an inside corner after
/// the points were pushed, a run of openings that jogs sideways, a turning run's diagonal
/// across a corner), a corner is put in: the leg's tightest spot, pushed off the wall,
/// kept only when both new legs are clearer than the old one.
/// </summary>
internal static void KeepLegsOffWalls(DungeonGeometry geo, List<NavPoint> pts, bool closed)
{
int budget = pts.Count / 2 + 8, perLeg = 0;
int i = 0;
while (i < (closed ? pts.Count : pts.Count - 1) && pts.Count >= 2)
{
var a = pts[i]; var b = pts[(i + 1) % pts.Count];
double least = LegLeast(geo, a, b, out double wx, out double wy, out double wz);
double target = Math.Min(LegMinClearance, Math.Min(PointClearance(geo, a), PointClearance(geo, b)));
if (least >= target - 0.05 || budget <= 0 || perLeg >= 3) { i++; perLeg = 0; continue; }
// The corner leaving both new legs clearest, if that is clearly better.
NavPoint? best = BestCorner(geo, a, b, wx, wy, wz, least + 0.1, out _);
if (best != null)
{
pts.Insert(i + 1, Tag(best, "leg-corner"));
budget--; perLeg++;
continue; // check the first new leg next
}
// No one corner does it (a jog round two corners): a first corner the walk reaches
// clear, then the best corner for the rest.
bool two = false;
foreach (var first in CornerCandidates(geo, wx, wy, wz))
{
if (LegLeast(geo, a, first, out _, out _, out _) < target - 0.05 || TurnsBack(a, first, b)) continue;
double rest = LegLeast(geo, first, b, out double rx, out double ry, out double rz);
var second = BestCorner(geo, first, b, rx, ry, rz, Math.Max(rest, least) + 0.1, out double m2);
if (second == null || m2 <= least + 0.1) continue;
pts.Insert(i + 1, Tag(first, "leg-corner"));
pts.Insert(i + 2, Tag(second, "leg-corner"));
budget -= 2; perLeg += 2;
two = true;
break;
}
if (two) continue;
i++; perLeg = 0;
}
}
// Corners to try for a leg whose tightest spot is (wx, wy, wz): that spot pushed off the
// wall, and the centres of the openings near it (a leg that jogs through the wrong side of a
// junction needs the opening it skipped).
private static List<NavPoint> CornerCandidates(DungeonGeometry geo, double wx, double wy, double wz)
{
double cx = wx, cy = wy;
geo.PushClear(ref cx, ref cy, wz, WallClearance, LegCornerPushMax);
var list = new List<NavPoint> { WorldPoint(cx, cy, wz, false) };
foreach (var d in geo.DoorwaysNear(wx, wy, wz, LegCornerSearch)) list.Add(WorldPoint(d.X, d.Y, d.Z, false));
return list;
}
// The candidate leaving both new legs a-corner-b clearest, if better than mustBeat.
private static NavPoint? BestCorner(DungeonGeometry geo, NavPoint a, NavPoint b, double wx, double wy, double wz,
double mustBeat, out double bestMin)
{
NavPoint? best = null;
bestMin = mustBeat;
foreach (var corner in CornerCandidates(geo, wx, wy, wz))
{
if (PointClearance(geo, corner) <= mustBeat) continue;
if (TurnsBack(a, corner, b)) continue;
double m = Math.Min(LegLeast(geo, a, corner, out _, out _, out _), LegLeast(geo, corner, b, out _, out _, out _));
if (m > bestMin) { bestMin = m; best = corner; }
}
return best;
}
// A corner that sends the walk back more than 120 degrees: a detour round something the
// map draws but the character walks through (render faces across a ramp at 0x6544), not a
// way round a corner.
private static bool TurnsBack(NavPoint a, NavPoint corner, NavPoint b)
{
double ux = corner.EW - a.EW, uy = corner.NS - a.NS, vx = b.EW - corner.EW, vy = b.NS - corner.NS;
double lu = Math.Sqrt(ux * ux + uy * uy), lv = Math.Sqrt(vx * vx + vy * vy);
if (lu < 1e-12 || lv < 1e-12) return false;
return (ux * vx + uy * vy) / (lu * lv) < Math.Cos(120.0 * Math.PI / 180.0);
}
private static double LegLeast(DungeonGeometry geo, NavPoint a, NavPoint b, out double wx, out double wy, out double wz)
=> geo.LegClearance(DungeonGeometry.NavToWorld(a.EW), DungeonGeometry.NavToWorld(a.NS), a.Z * 240.0,
DungeonGeometry.NavToWorld(b.EW), DungeonGeometry.NavToWorld(b.NS), b.Z * 240.0,
WallClearance, LegEndSkip, out wx, out wy, out wz);
private static double PointClearance(DungeonGeometry geo, NavPoint p)
=> geo.ClearanceMemo(DungeonGeometry.NavToWorld(p.EW), DungeonGeometry.NavToWorld(p.NS), p.Z * 240.0, WallClearance + 0.5);
// A big room (its cells spread over 10 m or more) left again close to where it was entered is looked into: a
// walk to its middle and back. A straight crossing to a nearby opening would only skirt
// it (the patrol hunts; the old cell walk went all round such rooms). Also any room left
@ -464,11 +579,11 @@ internal static partial class DungeonPathfinder
DoorwayPoints(graph, geo, rooms, steps[i].From, steps[i].To, out approach, out _, out bool n0);
DoorwayPoints(graph, geo, rooms, steps[j].From, steps[j].To, out _, out exit, out bool n1);
narrow = n0 || n1;
var doors = new List<(DungeonDoorway Door, uint From)>();
var doors = new List<(DungeonDoorway Door, uint From, int Step)>();
for (int k = i; k <= j; k++)
{
if (!geo.TryGetDoorway(steps[k].From, steps[k].To, out var d)) continue;
doors.Add((d, steps[k].From));
doors.Add((d, steps[k].From, k));
narrow |= !d.IsWide;
}
bool turns = false;
@ -479,7 +594,23 @@ internal static partial class DungeonPathfinder
turns = ax * bx + ay * by < Math.Cos(25.0 * Math.PI / 180.0);
}
if (turns)
foreach (var (d, _) in doors) middle.Add(WorldPoint(d.X, d.Y, d.Z, !d.IsWide));
{
// The openings' centres, and between two of them the way through the room they
// share: the straight line from one centre to the next cut the inside corner of a
// bend (crypt corners: an L of two junction pieces, the line through its wall).
NavPoint? prevM = null;
int prevStep = -1;
foreach (var (d, _, k) in doors)
{
var m = Tag(WorldPoint(d.X, d.Y, d.Z, !d.IsWide), "run-opening");
if (prevM != null && k == prevStep + 1
&& rooms.RoomOf.TryGetValue(steps[prevStep].To, out int ra) && rooms.RoomOf.TryGetValue(steps[k].From, out int rb) && ra == rb)
PullThrough(middle, graph, geo, rooms, rooms.Cells[ra], prevM, steps[prevStep].To, m, steps[k].From);
Append(middle, m);
prevM = m;
prevStep = k;
}
}
if (narrow) { approach.Doorway = true; exit.Doorway = true; }
}
@ -499,27 +630,68 @@ internal static partial class DungeonPathfinder
{
var (nx, ny) = d.NormalFrom(a);
narrow = !d.IsWide;
double sa = PickStandoff(geo, rooms, a, d, -nx, -ny);
double sb = PickStandoff(geo, rooms, b, d, nx, ny);
approach = WorldPoint(d.X - nx * sa, d.Y - ny * sa, d.Z, narrow);
exit = WorldPoint(d.X + nx * sb, d.Y + ny * sb, d.Z, narrow);
approach = Tag(DoorwayPoint(geo, rooms, a, d, -nx, -ny, narrow), "approach");
exit = Tag(DoorwayPoint(geo, rooms, b, d, nx, ny, narrow), "exit");
return true;
}
var na = graph[a]; var nb = graph[b];
double dNS = nb.NS - na.NS, dEW = nb.EW - na.EW, dZ = nb.Z - na.Z;
approach = new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.3, EW = na.EW + dEW * 0.3, Z = (na.Z + dZ * 0.3) / 240.0 };
exit = new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.5, EW = na.EW + dEW * 0.5, Z = (na.Z + dZ * 0.5) / 240.0 };
approach = Tag(new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.3, EW = na.EW + dEW * 0.3, Z = (na.Z + dZ * 0.3) / 240.0 }, "cell-fallback");
exit = Tag(new NavPoint { Type = NavPointType.Point, NS = na.NS + dNS * 0.5, EW = na.EW + dEW * 0.5, Z = (na.Z + dZ * 0.5) / 240.0 }, "cell-fallback");
PushOffWalls(geo, approach, RoomCells(rooms, a), CornerPushMax);
PushOffWalls(geo, exit, null, CornerPushMax); // on the line between the two rooms
return false;
}
// The longest standoff whose point is on the floor of the cell's room (or the shortest).
private static double PickStandoff(DungeonGeometry geo, DungeonRooms rooms, uint cell, DungeonDoorway d, double dirX, double dirY)
/// <summary>
/// The doorway point on <paramref name="cell"/>'s side of the opening: on its centre line,
/// at the longest standoff (4 m down to 1 m) that is on the room's floor and keeps
/// WallClearance from every wall. Where no standoff does (a short bend or junction cell:
/// the centre line runs into the bend's outer wall), the clearest one, pushed off the walls
/// (in a corridor too narrow for the clearance, onto its middle).
/// </summary>
private static NavPoint DoorwayPoint(DungeonGeometry geo, DungeonRooms rooms, uint cell, DungeonDoorway d,
double dirX, double dirY, bool narrow)
{
var cells = rooms.RoomOf.TryGetValue(cell, out int r) ? (IEnumerable<uint>)rooms.Cells[r] : new[] { cell };
foreach (double s in DoorwayStandoffs)
if (geo.OnFloorOfAny(cells, d.X + dirX * s, d.Y + dirY * s, d.Z)) return s;
return DoorwayStandoffs[DoorwayStandoffs.Length - 1];
var cells = RoomCells(rooms, cell);
double s = PickStandoff(geo, cells, d, dirX, dirY, out double clearance);
var p = WorldPoint(d.X + dirX * s, d.Y + dirY * s, d.Z, narrow);
if (clearance < WallClearance) PushOffWalls(geo, p, cells, DoorwayPushMax);
return p;
}
private static IReadOnlyCollection<uint> RoomCells(DungeonRooms rooms, uint cell)
=> rooms.RoomOf.TryGetValue(cell, out int r) ? rooms.Cells[r] : new[] { cell };
// The longest standoff whose point is on the floor of the cell's room with WallClearance;
// else the one with the most clearance (the longer of near ties); else the shortest.
internal static double PickStandoff(DungeonGeometry geo, IReadOnlyCollection<uint> cells, DungeonDoorway d,
double dirX, double dirY, out double clearance)
{
double bestS = -1;
clearance = 0;
for (double s = DoorwayStandoffLongest; s >= DoorwayStandoffShortest - 1e-9; s -= DoorwayStandoffStep)
{
double px = d.X + dirX * s, py = d.Y + dirY * s;
if (!geo.OnFloorOfAny(cells, px, py, d.Z)) continue;
double c = geo.ClearanceMemo(px, py, d.Z, WallClearance + 0.5);
if (c >= WallClearance) { clearance = c; return s; }
if (bestS < 0 || c > clearance + 0.05) { bestS = s; clearance = c; }
}
return bestS > 0 ? bestS : DoorwayStandoffShortest;
}
/// <summary>Moves a point (in place) to WallClearance from walls and floor edges, at most
/// <paramref name="maxMove"/>, staying on the floor of <paramref name="cells"/> when given.</summary>
private static void PushOffWalls(DungeonGeometry geo, NavPoint p, IReadOnlyCollection<uint>? cells, double maxMove)
{
double x = DungeonGeometry.NavToWorld(p.EW), y = DungeonGeometry.NavToWorld(p.NS);
double ox = x, oy = y;
geo.PushClear(ref x, ref y, p.Z * 240.0, WallClearance, maxMove, cells);
if (x == ox && y == oy) return;
p.EW = DungeonGeometry.WorldToNav(x);
p.NS = DungeonGeometry.WorldToNav(y);
}
// ── Crossing a room ──────────────────────────────────────────────────────
@ -552,48 +724,76 @@ internal static partial class DungeonPathfinder
internal static Action<string>? Trace;
// Legs across a room keep WallClearance either side where the room allows: the straight
// line, else the room's cells string-pulled with every leg that clear. Where the room is
// too tight for that, the crossing as before (0.5 m either side).
private static void PullThrough(List<NavPoint> pts, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo,
DungeonRooms rooms, List<uint> cells, NavPoint from, uint fromCell, NavPoint to, uint toCell)
{
if (Clear(geo, cells, from, to)) return;
if (Clear(geo, cells, from, to, WallClearance)) return;
// Through the room's own cells: the openings between them (or cell-centre midpoints).
// Through the room's own cells: the openings between them (or cell-centre midpoints),
// pushed off the walls like every other point.
var cellPath = CellBfs(graph, rooms, fromCell, toCell);
var corners = new List<NavPoint>();
for (int i = 0; i + 1 < cellPath.Count; i++)
{
uint a = cellPath[i], b = cellPath[i + 1];
if (geo.TryGetDoorway(a, b, out var d)) corners.Add(WorldPoint(d.X, d.Y, d.Z, false));
NavPoint corner;
if (geo.TryGetDoorway(a, b, out var d)) corner = Tag(WorldPoint(d.X, d.Y, d.Z, false), "pull-opening");
else
{
var na = graph[a]; var nb = graph[b];
corners.Add(new NavPoint { Type = NavPointType.Point, NS = (na.NS + nb.NS) * 0.5, EW = (na.EW + nb.EW) * 0.5, Z = (na.Z + nb.Z) * 0.5 / 240.0 });
corner = Tag(new NavPoint { Type = NavPointType.Point, NS = (na.NS + nb.NS) * 0.5, EW = (na.EW + nb.EW) * 0.5, Z = (na.Z + nb.Z) * 0.5 / 240.0 }, "pull-midpoint");
}
PushOffWalls(geo, corner, cells, CornerPushMax);
corners.Add(corner);
}
corners.Add(to);
// String-pull: from the anchor, the farthest corner in a clear straight line.
var strict = new List<NavPoint>();
if (StringPull(strict, geo, cells, from, corners, WallClearance))
{
foreach (var p in strict) Append(pts, p);
return;
}
if (Clear(geo, cells, from, to, CrossingClearance)) return;
var loose = new List<NavPoint>();
StringPull(loose, geo, cells, from, corners, CrossingClearance);
foreach (var p in loose) Append(pts, p);
}
// From the anchor, the farthest corner in a clear straight line, and on; the last corner
// (the end) not included. True when every leg of the result is clear.
private static bool StringPull(List<NavPoint> outPts, DungeonGeometry geo, List<uint> cells, NavPoint from,
List<NavPoint> corners, double clearance)
{
var to = corners[corners.Count - 1];
if (Clear(geo, cells, from, to, clearance)) return true;
NavPoint anchor = from;
int at = 0;
bool allClear = true;
int guard = corners.Count + 2;
while (at < corners.Count - 1 && guard-- > 0)
{
int pick = at; // always move on at least one corner
for (int k = corners.Count - 1; k > at; k--)
if (Clear(geo, cells, anchor, corners[k])) { pick = k; break; }
if (pick == corners.Count - 1) break; // the end is in sight
Append(pts, corners[pick]);
int pick = -1;
for (int k = corners.Count - 1; k >= at; k--)
if (Clear(geo, cells, anchor, corners[k], clearance)) { pick = k; break; }
if (pick < 0) { pick = at; allClear = false; } // always move on at least one corner
if (pick == corners.Count - 1) return allClear; // the end is in sight
outPts.Add(corners[pick]);
anchor = corners[pick];
at = pick + 1;
if (Clear(geo, cells, anchor, to)) break;
if (Clear(geo, cells, anchor, to, clearance)) return allClear;
}
return allClear && Clear(geo, cells, anchor, to, clearance);
}
private static bool Clear(DungeonGeometry geo, List<uint> cells, NavPoint a, NavPoint b)
private static bool Clear(DungeonGeometry geo, List<uint> cells, NavPoint a, NavPoint b, double clearance)
=> geo.SegmentClear(cells,
DungeonGeometry.NavToWorld(a.EW), DungeonGeometry.NavToWorld(a.NS), a.Z * 240.0,
DungeonGeometry.NavToWorld(b.EW), DungeonGeometry.NavToWorld(b.NS), b.Z * 240.0,
CrossingClearance);
clearance);
// Shortest cell path inside one room (inclusive), or just [from, to] when there is none.
private static List<uint> CellBfs(Dictionary<uint, DungeonNavNode> graph, DungeonRooms rooms, uint from, uint to)
@ -621,7 +821,7 @@ internal static partial class DungeonPathfinder
}
// The point a patrol visits to look into a room: the middle of its cell centres when that
// is on its floor, else the cell centre nearest that middle.
// is on its floor, else the cell centre nearest that middle; then pushed off the walls.
private static NavPoint? RoomMiddle(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, List<uint> cells, out uint midCell)
{
midCell = 0;
@ -646,13 +846,27 @@ internal static partial class DungeonPathfinder
}
if (nearest == null) return null;
midCell = nearest.CellId;
if (geo.OnCellFloor(nearest.CellId, sx, sy, sz) || geo.OnFloorOfAny(cells, sx, sy, sz) && !geo.HasFloor(nearest.CellId))
return WorldPoint(sx, sy, sz, false);
return WorldPoint(DungeonGeometry.NavToWorld(nearest.EW), DungeonGeometry.NavToWorld(nearest.NS), nearest.Z, false);
NavPoint mid = geo.OnCellFloor(nearest.CellId, sx, sy, sz) || geo.OnFloorOfAny(cells, sx, sy, sz) && !geo.HasFloor(nearest.CellId)
? Tag(WorldPoint(sx, sy, sz, false), "room-middle")
: Tag(WorldPoint(DungeonGeometry.NavToWorld(nearest.EW), DungeonGeometry.NavToWorld(nearest.NS), nearest.Z, false), "room-middle-cell");
// A one-cell dead end's origin is inside its end cap; a big room's middle can be a pillar.
PushOffWalls(geo, mid, cells, MiddlePushMax);
return mid;
}
// ── Point list helpers ───────────────────────────────────────────────────
/// <summary>Offline tools (PatrolProof) set this to learn which rule laid each point:
/// approach, exit, run-opening, pull-opening, pull-midpoint, room-middle, room-middle-cell,
/// cell-fallback.</summary>
internal static Dictionary<NavPoint, string>? KindLog;
private static NavPoint Tag(NavPoint p, string kind)
{
if (KindLog != null) KindLog[p] = kind;
return p;
}
private static NavPoint WorldPoint(double wx, double wy, double wz, bool doorway) => new()
{
Type = NavPointType.Point,

View file

@ -634,6 +634,11 @@ internal static partial class DungeonPathfinder
}
SimplifyRoute(route);
// The map geometry is there but the room patrol found nothing to walk (the start is cut
// off from every doorway): the cell walk's points still keep off the walls.
if (geo != null)
foreach (var p in route.Points)
PushOffWalls(geo, Tag(p, "cell-walk"), null, CornerPushMax);
return route;
}

View file

@ -3,7 +3,9 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using RynthCore.Loot;
using RynthCore.Loot.Editing;
using RynthCore.Loot.VTank;
namespace RynthCore.Plugin.RynthAi.Loot;
@ -13,7 +15,8 @@ namespace RynthCore.Plugin.RynthAi.Loot;
/// hot reload after a save. The engine calls the exports (PluginExports, "Loot
/// editor bridge") from its UI data hub on the plugin pump thread, the same
/// thread as the plugin tick; the lock only guards against any other caller.
/// Nothing here touches AC.
/// Nothing here touches AC: what it needs about items (the "Add to loot
/// profile" popup, /ra loot add) comes through <see cref="Items"/>.
/// </summary>
internal sealed class LootEditorBridge
{
@ -30,6 +33,15 @@ internal sealed class LootEditorBridge
private long _nextDiskCheck;
private string? _vocabJson;
// "Add to loot profile": the popup's current rule, and a second session for a
// target profile the editor doesn't have open (so the editor's view never changes).
private LootEditItemDraft? _draft;
private long _draftRevision;
private LootEditSession? _other;
/// <summary>RynthAi's item lookups for "Add to loot profile". Set once by the plugin.</summary>
public LootItemHooks Items { get; set; } = new();
public LootEditorBridge(Func<string> inUsePath, Action<string> onSaved, params string[] vendorFolders)
{
_inUsePath = inUsePath;
@ -56,10 +68,13 @@ internal sealed class LootEditorBridge
if (_followInUse && !_session.IsDirty && inUse.Length > 0 && !LootEditSession.SamePath(inUse, _session.Path))
_session.Open(inUse);
}
return unchecked((int)_session.Revision);
return unchecked((int)StateRevision);
}
}
// The session's revision plus the popup draft's: both only grow, so the sum moves when either does.
private long StateRevision => _session.Revision + _draftRevision;
public string StateJson()
{
lock (_sync)
@ -67,6 +82,8 @@ internal sealed class LootEditorBridge
string inUse = InUse;
if (!_session.IsOpen && _followInUse && inUse.Length > 0) _session.Open(inUse);
LootEditState state = _session.BuildState(inUse, ListFiles());
state.Revision = StateRevision;
state.ItemDraft = _draft;
return JsonSerializer.Serialize(state, LootEditJsonContext.Default.LootEditState);
}
}
@ -87,6 +104,11 @@ internal sealed class LootEditorBridge
{
LootEditCommand? cmd = JsonSerializer.Deserialize(json, LootEditJsonContext.Default.LootEditCommand);
if (cmd == null) return;
if (cmd.Op is "item_preview" or "item_add" or "item_close")
{
ItemCommand(cmd);
return;
}
string? saved = null;
lock (_sync)
{
@ -115,6 +137,147 @@ internal sealed class LootEditorBridge
if (saved != null) _onSaved(saved);
}
// =====================================================================
// Add to loot profile (a clicked item)
// =====================================================================
private void ItemCommand(LootEditCommand cmd)
{
LootEditItemDraft? added = null;
lock (_sync)
{
if (cmd.Op == "item_close")
{
if (_draft == null) return;
_draft = null;
_draftRevision++;
return;
}
LootEditItemDraft d = BuildDraft(cmd.Item ?? new LootEditItemRequest(), cmd.Op == "item_add");
_draft = d;
_draftRevision++;
if (d.Added) added = d;
}
if (added != null) Items.Added(added);
}
/// <summary>
/// /ra loot add: the popup's preview (<paramref name="add"/> false) or Add,
/// without touching the popup's draft. After an add, Items.Added has run
/// (chat line, reload) before this returns.
/// </summary>
public LootEditItemDraft AddItem(LootEditItemRequest request, bool add)
{
LootEditItemDraft d;
lock (_sync) d = BuildDraft(request, add);
if (d.Added) Items.Added(d);
return d;
}
/// <summary>The rule the item makes, where it goes, and (add) the insert and save. Under the lock.</summary>
private LootEditItemDraft BuildDraft(LootEditItemRequest req, bool add)
{
var d = new LootEditItemDraft { Seq = req.Seq };
uint id = req.ItemId != 0 ? req.ItemId : Items.SelectedItemId();
if (id == 0) return Refuse(d, "No item selected. Click an item first.");
d.ItemId = id;
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like);
if (facts == null) return Refuse(d, $"RynthAi doesn't know item 0x{id:X8} yet. Select it again in a moment.");
d.ItemName = facts.Name;
d.ClassName = LootItemRules.ClassName(facts.ObjectClass);
d.Stackable = facts.Stackable;
string inUse = InUse;
string target = req.ToOpenProfile && _session.IsOpen ? _session.Path : inUse;
if (target.Length == 0) return Refuse(d, "No loot profile selected. Pick one in RynthAi first.");
d.TargetPath = target;
d.TargetFile = Path.GetFileName(target);
d.TargetInUse = LootEditSession.SamePath(target, inUse);
if (!File.Exists(target)) return Refuse(d, $"Loot profile not found: {target}");
LootEditSession s = SessionFor(target);
if (!s.IsOpen || !LootEditSession.SamePath(s.Path, target)) return Refuse(d, s.Message);
d.Format = s.Format;
if (!s.CanInsert) return Refuse(d, $"{d.TargetFile} is read-only here: {s.ReadOnlyReason}");
var options = new LootItemRuleOptions
{
Match = match,
Action = req.Action == 0 ? null : (VTankLootAction)req.Action,
KeepCount = req.KeepCount < 0 ? null : req.KeepCount,
RuleName = req.RuleName,
};
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
if (draft == null) return Refuse(d, error);
d.Match = (int)draft.Match;
d.Action = (int)draft.Action;
d.KeepCount = draft.KeepCount;
d.RuleName = draft.Rule.Name;
d.DefaultRuleName = draft.DefaultName;
d.Preview = LootItemRules.PreviewLines(draft.Rule);
d.Notes.AddRange(draft.Notes);
bool json = s.Format == "json";
LootRule? native = null;
if (json)
{
var dropped = new List<string>();
native = LootItemRules.ToNative(draft.Rule, dropped);
foreach (string c in dropped) d.Notes.Add($"Left out (the native format has no such condition): {c}");
if (native == null) return Refuse(d, "The native format can't hold any of this rule's conditions.");
}
// Just before the first rule that decides this item now (first match wins), else the end.
int count = s.RuleCount;
int first = json ? Items.FirstMatchNative(id, s.JsonProfile!) : Items.FirstMatchUtl(id, s.Profile!);
if (first >= count) first = -1;
int at = first >= 0 ? first : count;
d.InsertAt = at;
d.RuleCount = count;
if (first >= 0)
{
string name = json ? s.JsonProfile!.Rules[first].Name : s.Profile!.Rules[first].Name;
name = string.IsNullOrWhiteSpace(name) ? $"#{first + 1}" : name.Trim();
string action = json ? s.JsonProfile!.Rules[first].Action.ToString() : LootRuleText.ActionName(s.Profile!.Rules[first].Action);
bool same = json ? LootItemRules.SameRule(native!, s.JsonProfile!.Rules[first]) : LootItemRules.SameRule(draft.Rule, s.Profile!.Rules[first]);
if (same) return Refuse(d, $"Already there: rule {first + 1} '{name}' does exactly this.");
d.OrderNote = $"Goes in at {at + 1} of {count + 1}, just before rule {first + 1} '{name}' ({action}), which takes this item now. "
+ "Rules are checked top to bottom and the first match wins, so this is the lowest spot where the new rule still decides; the rules above it are untouched.";
}
else
d.OrderNote = $"Goes in at the end ({at + 1} of {count + 1}): no rule takes this item now, so at the end it only gets items no other rule wants.";
if (s.IsDirty) return Refuse(d, $"The Loot Editor has unsaved changes in {d.TargetFile}. Save or discard them first.");
d.Ok = true;
if (!add) return d;
if (!s.InsertAndSave(draft.Rule, native, at)) return Refuse(d, s.Message);
d.Added = true;
d.Message = $"Added loot rule '{draft.Rule.Name}' to {d.TargetFile}";
return d;
}
private static LootEditItemDraft Refuse(LootEditItemDraft d, string error)
{
d.Ok = false;
d.Error = error;
return d;
}
/// <summary>The editor's session when it has <paramref name="target"/> open, else a second one (fresh from disk).</summary>
private LootEditSession SessionFor(string target)
{
if (_session.IsOpen && LootEditSession.SamePath(_session.Path, target))
{
_session.CheckDisk();
return _session;
}
_other ??= new LootEditSession();
if (_other.IsOpen && LootEditSession.SamePath(_other.Path, target)) _other.CheckDisk();
else _other.Open(target, force: true);
return _other;
}
/// <summary>LootProfiles (*.utl, *.json), then AutoVendor profiles, then the open file if it is elsewhere.</summary>
private List<LootEditFile> ListFiles()
{
@ -144,3 +307,18 @@ internal sealed class LootEditorBridge
return files;
}
}
/// <summary>What the loot editor bridge asks RynthAi about items (the plugin fills these in).</summary>
internal sealed class LootItemHooks
{
/// <summary>The item selected in the game, or 0.</summary>
public Func<uint> SelectedItemId { get; set; } = () => 0;
/// <summary>The item's facts from the object cache, or null. The bool: "items like this" (ask for an ID if it isn't identified).</summary>
public Func<uint, bool, LootItemFacts?> Facts { get; set; } = (_, _) => null;
/// <summary>The first rule of the .utl profile that matches the item now, or -1.</summary>
public Func<uint, VTankLootProfile, int> FirstMatchUtl { get; set; } = (_, _) => -1;
/// <summary>The first rule of the native profile that matches the item now, or -1.</summary>
public Func<uint, LootProfile, int> FirstMatchNative { get; set; } = (_, _) => -1;
/// <summary>A rule was added and saved: say so and reload the profile. Outside the bridge's lock.</summary>
public Action<LootEditItemDraft> Added { get; set; } = _ => { };
}

View file

@ -219,7 +219,10 @@ internal sealed class NavigationEngine
private const double DoorwayTurnEnter = 8.0, DoorwayTurnExit = 3.0;
private bool _steerDoorway;
private double TurnEnterNow => _steerDoorway ? Math.Min(BigTurnEnter, DoorwayTurnEnter) : BigTurnEnter;
private double TurnExitNow => _steerDoorway ? Math.Min(BigTurnExit, DoorwayTurnExit) : BigTurnExit;
// Never tighter than the turn dead zone (+0.5): the servo stops turning inside DeadZone, so an
// exit below it left the error between the two, no turn and no run: nav stood still until the
// player tapped forward (doorway exit 3 vs dead zone 4, 2026-10-04).
private double TurnExitNow => Math.Max(DeadZone + 0.5, _steerDoorway ? Math.Min(BigTurnExit, DoorwayTurnExit) : BigTurnExit);
private double SweepMult => Math.Max(1.0, _settings.NavSweepMult);
// Nav point reach (FollowNavMin, VTank's "Follow/Nav Min Distance"): how close to get to
// each nav point before moving on. Floored at the Settings minimum (0.5); it used to be
@ -2752,12 +2755,21 @@ internal sealed class NavigationEngine
// MOVEMENT HELPERS
// ══════════════════════════════════════════════════════════════════════════
// Auto-run re-sent this often while nav wants to move. The flag alone trusted that auto-run
// stayed on; a cast, a stance change, a corpse use or a server stop turns it off without
// telling nav, and nav sat still until the player tapped forward (2026-10-04). Setting it
// on when it already is costs nothing; nav only ticks while it's the active activity.
private const long ForwardReassertMs = 1000;
private long _lastForwardAssertMs;
private void StartForward()
{
if (!_isMovingForward)
long now = Environment.TickCount64;
if (!_isMovingForward || now - _lastForwardAssertMs >= ForwardReassertMs)
{
_host.SetAutoRun(true);
_isMovingForward = true;
_lastForwardAssertMs = now;
}
}

View file

@ -74,6 +74,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] /ra lootparse — inspect the selected loot profile");
ChatLine("[RynthAi] /ra lootcheckinv — test the loot profile against inventory");
ChatLine("[RynthAi] /ra lootcheck — classify selected item (on|off = auto on click)");
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item");
ChatLine("[RynthAi] /ra dumpinv — dump all inventory items (cache + direct)");
ChatLine("[RynthAi] /ra combat — dump combat state machine snapshot");
ChatLine("[RynthAi] /ra why — one-glance diagnosis of why the bot is idle/attacking");
@ -1507,7 +1508,17 @@ public sealed partial class RynthAiPlugin
internal LootEditorBridge LootEditor => _lootEditor ??= new LootEditorBridge(
() => _dashboard?.Settings?.CurrentLootPath ?? string.Empty,
OnLootProfileEdited,
Vendor.AutoVendorManager.MainProfileDir);
Vendor.AutoVendorManager.MainProfileDir)
{
Items = new LootItemHooks
{
SelectedItemId = () => Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0,
Facts = BuildLootItemFacts,
FirstMatchUtl = FirstLootRuleFor,
FirstMatchNative = FirstLootRuleFor,
Added = OnLootRuleAdded,
},
};
/// <summary>
/// The Loot Editor saved <paramref name="path"/>: drop the cached copies and,
@ -1515,6 +1526,19 @@ public sealed partial class RynthAiPlugin
/// Plugin pump thread (the editor's export), the same thread as the tick.
/// </summary>
private void OnLootProfileEdited(string path)
{
string name = System.IO.Path.GetFileName(path);
if (!ForgetLootProfile(path))
{
ChatLine($"[RynthAi] Loot Editor saved {name}.");
return;
}
ChatLine($"[RynthAi] Loot Editor saved {name}; reloading it.");
ReloadLootProfileInUse(path);
}
/// <summary>Drops the cached copies of <paramref name="path"/>. True when it is the loot profile in use.</summary>
private bool ForgetLootProfile(string path)
{
bool Same(string a) => RynthCore.Loot.Editing.LootEditSession.SamePath(a, path);
if (Same(_loadedLootProfilePath))
@ -1527,17 +1551,136 @@ public sealed partial class RynthAiPlugin
_nativeLootProfile = null;
_nativeLootProfileTime = DateTime.MinValue;
}
string name = System.IO.Path.GetFileName(path);
if (!Same(_dashboard?.Settings?.CurrentLootPath ?? string.Empty))
{
ChatLine($"[RynthAi] Loot Editor saved {name}.");
return;
}
ChatLine($"[RynthAi] Loot Editor saved {name}; reloading it.");
return Same(_dashboard?.Settings?.CurrentLootPath ?? string.Empty);
}
private void ReloadLootProfileInUse(string path)
{
if (path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) TryLoadNativeLootProfile(out _, out _);
else TryLoadLootProfile(string.Empty, out _, out _);
}
// ── Add to loot profile (a clicked item; /ra loot add, the engine's popup) ──
/// <summary>A rule from "Add to loot profile" was saved: say so, and reload the profile when it is the one in use.</summary>
private void OnLootRuleAdded(RynthCore.Loot.Editing.LootEditItemDraft d)
{
bool inUse = ForgetLootProfile(d.TargetPath);
ChatLine($"[RynthAi] {d.Message}{(inUse ? "" : " (not the profile RynthAi loots with)")}.");
if (inUse) ReloadLootProfileInUse(d.TargetPath);
}
/// <summary>What a loot rule can be built from: the item's name, class, stack and key properties, from the object cache.</summary>
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like)
{
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
if (wo == null) return null;
var f = new RynthCore.Loot.Editing.LootItemFacts
{
Id = wo.Id,
Name = wo.Name,
ObjectClass = (int)wo.ObjectClass,
StackSize = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)),
MaxStackSize = Math.Max(1, wo.Values(LongValueKey.MaxStackSize, 1)),
};
foreach (int key in RynthCore.Loot.Editing.LootItemRules.IntKeys)
{
int v = wo.Values(key, 0);
if (v != 0) f.Ints[key] = v;
}
foreach (int key in RynthCore.Loot.Editing.LootItemRules.DoubleKeys)
{
double v = wo.Values((DoubleValueKey)key, 0.0);
if (v != 0) f.Doubles[key] = v;
}
if (like)
{
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
foreach (string n in ctx.GetItemSpellNames(itemId))
if (!string.IsNullOrEmpty(n)) f.Spells.Add(n);
// Material, workmanship and spells need an ID: ask for one, so the next preview has them.
if (Host.HasRequestId && Host.HasHasAppraisalData && !Host.HasAppraisalData(itemId)) Host.RequestId(itemId);
}
return f;
}
/// <summary>The first rule of <paramref name="profile"/> that takes the item now (the corpse looter's order), or -1.</summary>
private int FirstLootRuleFor(uint itemId, VTankLootProfile profile)
{
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
if (wo == null) return -1;
VTankLootEvaluator.FirstMatch(profile, wo, new VTankLootContext(Host, _playerId) { Cache = _objectCache }, out int index);
return index;
}
private int FirstLootRuleFor(uint itemId, RynthCore.Loot.LootProfile profile)
{
WorldObject? wo = _objectCache?[unchecked((int)itemId)];
if (wo == null) return -1;
for (int i = 0; i < profile.Rules.Count; i++)
if (Loot.LootEvaluator.Matches(profile.Rules[i], wo, _charSkills)) return i;
return -1;
}
/// <summary>
/// /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview]: a rule for
/// the selected item, straight into the loot profile in use (the defaults: exact
/// name and class; Read for scrolls, Keep # one full stack for stacks, else Keep).
/// </summary>
private void HandleLootCommand(string[] parts)
{
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : string.Empty;
if (sub != "add")
{
ChatLine("[RynthAi] /ra loot add [keep|keep N|salvage|sell|read] [name|like] [preview] — add a loot rule for the selected item to the loot profile in use");
ChatLine("[RynthAi] default: exact name + class; Read for scrolls, Keep # (one full stack) for stacks, else Keep. name = name only, like = items like this. preview = show it, add nothing.");
ChatLine("[RynthAi] Also: right-click an item in the Inventory panel, or 'Add selected item' in the Loot Editor.");
return;
}
var req = new RynthCore.Loot.Editing.LootEditItemRequest();
bool preview = false;
for (int i = 3; i < parts.Length; i++)
{
string w = parts[i].ToLowerInvariant();
switch (w)
{
case "keep": req.Action = (int)VTankLootAction.Keep; break;
case "keep#": req.Action = (int)VTankLootAction.KeepUpTo; break;
case "salvage": req.Action = (int)VTankLootAction.Salvage; break;
case "sell": req.Action = (int)VTankLootAction.Sell; break;
case "read": req.Action = (int)VTankLootAction.Read; break;
case "name": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Name; break;
case "like": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.Like; break;
case "exact": req.Match = (int)RynthCore.Loot.Editing.LootItemMatch.NameAndClass; break;
case "preview":
case "?": preview = true; break;
default:
if (int.TryParse(w.TrimStart('#'), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int n) && n >= 0)
{
req.Action = (int)VTankLootAction.KeepUpTo;
req.KeepCount = n;
break;
}
ChatLine($"[RynthAi] loot add: '{parts[i]}'? Use keep, keep N, salvage, sell, read, name, like or preview.");
return;
}
}
RynthCore.Loot.Editing.LootEditItemDraft d = LootEditor.AddItem(req, add: !preview);
if (d.Preview.Count > 0 && (preview || !d.Ok))
{
ChatLine($"[RynthAi] {d.ItemName} -> {d.TargetFile}:");
foreach (string line in d.Preview) ChatLine("[RynthAi] " + line);
if (d.OrderNote.Length > 0) ChatLine("[RynthAi] " + d.OrderNote);
}
foreach (string note in d.Notes) ChatLine("[RynthAi] Note: " + note);
if (!d.Ok) ChatLine("[RynthAi] Loot rule not added: " + d.Error);
else if (preview) ChatLine("[RynthAi] (preview only; /ra loot add without 'preview' adds it)");
else if (d.Added && d.OrderNote.Length > 0) ChatLine("[RynthAi] " + d.OrderNote);
// An add's own chat line comes from OnLootRuleAdded.
}
private bool TryLoadNativeLootProfile(out RynthCore.Loot.LootProfile profile, out string loadedPath)
{
string candidatePath = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"');

View file

@ -524,6 +524,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
if (_buffManager != null)
_buffManager.OffhandStowed = id => _combatManager?.NoteOffhandStowed(id);
_combatManager.SetCharacterSkills(_charSkills);
@ -1362,6 +1363,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
// while nav owns the tick, so it never got to clear these itself.
_doorRequestedId = 0;
ResetDoorState();
// A corpse left open mid-loot is closed, as a player would close its window.
try { CloseOpenCorpseOnMacroStop(); }
catch (Exception ex) { Host.Log($"[RynthAi] Macro-stop corpse close failed: {ex.Message}"); }
try
{
int busyBefore = Host.HasGetBusyState ? Host.GetBusyState() : -1;
@ -2918,6 +2922,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "lootparse": HandleLootParseCommand(trimmed); break;
case "lootcheckinv": HandleLootCheckInventoryCommand(trimmed); break;
case "lootcheck": HandleLootCheckSelectedCommand(parts); break;
case "loot": HandleLootCommand(parts); break;
case "corpseinfo": HandleCorpseInfoCommand(); break;
case "corpsecheck": HandleCorpseCheckCommand(parts); break;
case "corpseopen": HandleCorpseOpenCommand(); break;

View file

@ -81,6 +81,8 @@ internal static class AutoVendorRules
// Decal's synthetic LongValueKey ids start at 0x0D000000; RynthAi reads STypes only.
internal const int MaxStandardKey = 0xFFFF;
// Except Decal's "Type" (0x0D000000), the weenie class id, which RynthAi reads too.
internal const int DecalTypeKey = 0x0D000000;
// RynthAi derives ObjectClass from ITEM_TYPE alone. Decal splits these further
// (Misc -> HealingKit/Lockpick, Book -> Scroll/Journal/Sign, Container -> Foci,
@ -126,6 +128,7 @@ internal static class AutoVendorRules
case VTankNodeTypes.LongValKeyNE:
case VTankNodeTypes.LongValKeyFlagExists:
{
if (TryKey(d, 1, out int wkey) && wkey == DecalTypeKey) return true; // the WCID: always known
if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false;
if (f.IsVendorListing) return ListingIntKeys.Contains(key);
return f.Appraised || PwdIntKeys.Contains(key);

View file

@ -43,6 +43,17 @@ public sealed class LootEditSession
public int RuleCount => Shown?.Rules.Count ?? _json?.Rules.Count ?? 0;
/// <summary>The edited model (null for JSON / nothing open). Tests read it.</summary>
public VTankLootProfile? Profile => _utl;
/// <summary>The open .json profile (native format), else null.</summary>
public LootProfile? JsonProfile => _json;
/// <summary>"utl", "json", or empty when nothing is open.</summary>
public string Format => !IsOpen ? string.Empty : _json != null ? "json" : "utl";
/// <summary>Why edits are refused (empty when they aren't).</summary>
public string ReadOnlyReason => _readOnlyReason;
/// <summary>True when InsertAndSave can add a rule: an editable .utl, or a .json profile.</summary>
public bool CanInsert => _utl != null || _json != null;
/// <summary>The last message (what the last command or load did).</summary>
public string Message => _message;
public bool MessageOk => _messageOk;
// =====================================================================
// Load
@ -422,19 +433,7 @@ public sealed class LootEditSession
return Fail($"{FileName(_path)} changed on disk since you opened it. Reload (drops your edits) or Save anyway.");
}
byte[] bytes = Encode();
string? dir = System.IO.Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
string tmp = _path + ".tmp";
File.WriteAllBytes(tmp, bytes);
if (File.Exists(_path))
{
try { File.Replace(tmp, _path, _path + ".bak", ignoreMetadataErrors: true); }
catch (PlatformNotSupportedException) { File.Copy(tmp, _path, overwrite: true); File.Delete(tmp); }
catch (IOException) { File.Copy(_path, _path + ".bak", overwrite: true); File.Copy(tmp, _path, overwrite: true); File.Delete(tmp); }
}
else File.Move(tmp, _path);
WriteFile(_path, Encode());
_stamp = FileStamp.Read(_path);
_dirty = false;
_changedOnDisk = false;
@ -446,6 +445,135 @@ public sealed class LootEditSession
}
}
/// <summary>Writes a temp file and swaps it in, the old file kept as .bak.</summary>
private static void WriteFile(string path, byte[] bytes)
{
string? dir = System.IO.Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
string tmp = path + ".tmp";
File.WriteAllBytes(tmp, bytes);
if (File.Exists(path))
{
try { File.Replace(tmp, path, path + ".bak", ignoreMetadataErrors: true); }
catch (PlatformNotSupportedException) { File.Copy(tmp, path, overwrite: true); File.Delete(tmp); }
catch (IOException) { File.Copy(path, path + ".bak", overwrite: true); File.Copy(tmp, path, overwrite: true); File.Delete(tmp); }
}
else File.Move(tmp, path);
}
// =====================================================================
// Add one rule and save (the "Add to loot profile" of a clicked item)
// =====================================================================
/// <summary>
/// Inserts <paramref name="rule"/> at <paramref name="index"/> (clamped; the
/// end when out of range) and saves at once, the old file kept as .bak.
/// .utl: through the edited model, refused while there are unsaved edits (so
/// it never saves someone's half-done changes with it) or when the file opens
/// read-only. .json: <paramref name="native"/> is spliced into the file's
/// Rules array as text, so every other byte stays as it was (the JSON writer
/// itself is lossy). Both check before writing that the result reads back
/// with every other rule unchanged; nothing is written when it doesn't.
/// </summary>
public bool InsertAndSave(VTankLootRule rule, LootRule? native, int index)
{
if (!IsOpen) return Fail("No profile open.");
if (_dirty) return Fail($"Unsaved changes in {FileName(_path)}. Save or discard them in the Loot Editor first.");
if (_json != null)
return native == null ? Fail("That rule can't be written in the native format.") : InsertJson(native, index);
if (_utl == null) return Fail(_readOnlyReason);
if (!_stamp.Exists) return Fail($"{FileName(_path)} doesn't exist yet. Save it once in the Loot Editor first.");
List<VTankLootRule> rules = _utl.Rules;
int at = index < 0 || index > rules.Count ? rules.Count : index;
if (_utl.FileVersion < 1) rule.CustomExpression = null;
else rule.CustomExpression ??= string.Empty;
var before = new List<string>(rules.Count);
foreach (VTankLootRule r in rules) before.Add(RuleText(_utl, r));
rules.Insert(at, rule);
string? bad = VerifyUtl(before, at);
if (bad != null)
{
rules.RemoveAt(at);
return Fail("Not added (the profile would not read back the same): " + bad);
}
_dirty = true;
if (!Save())
{
string why = _message;
rules.RemoveAt(at);
_dirty = false;
if (_changedOnDisk)
{
// Someone else wrote the file: show theirs (nothing of ours is pending).
Open(_path, force: true);
return Fail($"Not added: {FileName(_path)} changed on disk; reloaded it. Try again.");
}
return Fail("Not added. " + why);
}
_focus = at;
return Ok($"Added \"{rule.Name}\" at {at + 1} and saved {FileName(_path)} ({RuleCount} rules).");
}
private static string RuleText(VTankLootProfile owner, VTankLootRule r) =>
VTankLootWriter.Serialize(new VTankLootProfile { FileVersion = owner.FileVersion, Rules = { r } });
/// <summary>Null when the model, written and parsed back, has the old rules unchanged and the new one at <paramref name="at"/>.</summary>
private string? VerifyUtl(List<string> before, int at)
{
VTankLootProfile back;
try { back = VTankLootParser.LoadFromText(Decode(Encode(), out _, out _)); }
catch (Exception ex) { return ex.Message; }
if (back.Rules.Count != before.Count + 1) return $"{back.Rules.Count} rules instead of {before.Count + 1}.";
if (!SameSalvage(back.SalvageCombine, _utl!.SalvageCombine)) return "the salvage combine settings changed.";
for (int i = 0, j = 0; i < back.Rules.Count; i++)
{
string text = RuleText(back, back.Rules[i]);
if (i == at)
{
if (text != RuleText(_utl, _utl.Rules[at])) return "the new rule reads back differently.";
continue;
}
if (text != before[j++]) return $"rule {i + 1} would change.";
}
return null;
}
private static bool SameSalvage(SalvageCombineSettings? a, SalvageCombineSettings? b)
{
if (a == null || b == null) return a == null && b == null;
string Text(SalvageCombineSettings s) => VTankLootWriter.Serialize(new VTankLootProfile { FileVersion = 1, SalvageCombine = s });
return Text(a) == Text(b);
}
private bool InsertJson(LootRule native, int index)
{
try
{
byte[] bytes = File.ReadAllBytes(_path);
if (!FileStamp.Of(_path, bytes).SameContent(_stamp))
{
Open(_path, force: true);
return Fail($"{FileName(_path)} changed on disk; reloaded it. Try again.");
}
byte[]? spliced = LootJsonSplice.Insert(bytes, native, index, out int at, out string error);
if (spliced == null) return Fail("Not added: " + error);
WriteFile(_path, spliced);
_json = System.Text.Json.JsonSerializer.Deserialize(Decode(spliced, out _, out _), LootJsonContext.Default.LootProfile) ?? new LootProfile();
_stamp = FileStamp.Read(_path);
_changedOnDisk = false;
_focus = at;
Revision++;
return Ok($"Added \"{native.Name}\" at {at + 1} and saved {FileName(_path)} ({RuleCount} rules).");
}
catch (Exception ex)
{
return Fail($"Not added: {ex.Message}");
}
}
/// <summary>The file's bytes as Save writes them (its own encoding, line endings, BOM).</summary>
public byte[] Encode()
{

View file

@ -41,6 +41,12 @@ public sealed class LootEditState
/// <summary>Profiles in the loot folder, for the picker.</summary>
public List<LootEditFile> Files { get; set; } = new();
public List<LootEditRow> Rules { get; set; } = new();
/// <summary>
/// The "Add to loot profile" popup's rule (item_preview / item_add), or null.
/// Added 2026-10; an older engine ignores it.
/// </summary>
public LootEditItemDraft? ItemDraft { get; set; }
}
public sealed class LootEditFile
@ -103,6 +109,67 @@ public sealed class LootEditCommand
/// <summary>open/reload: discard unsaved edits; save: overwrite a file that changed on disk.</summary>
public bool Force { get; set; }
public LootEditRule? Rule { get; set; }
/// <summary>item_preview / item_add: the item and the popup's choices (added 2026-10).</summary>
public LootEditItemRequest? Item { get; set; }
}
/// <summary>
/// "Add to loot profile" from a clicked item (added 2026-10): what the popup
/// asks for. item_preview builds the rule into LootEditState.ItemDraft;
/// item_add builds it and adds it to the profile (saved, RynthAi reloads it);
/// item_close drops the draft.
/// </summary>
public sealed class LootEditItemRequest
{
/// <summary>The item; 0 = the item selected in the game.</summary>
public uint ItemId { get; set; }
/// <summary>LootItemMatch: 0 name + class, 1 name only, 2 items like this.</summary>
public int Match { get; set; }
/// <summary>VTank action code (1 Keep, 2 Salvage, 3 Sell, 4 Read, 10 Keep #); 0 = the item's default.</summary>
public int Action { get; set; }
/// <summary>Keep # count; -1 = default (one full stack).</summary>
public int KeepCount { get; set; } = -1;
/// <summary>Empty = the default name ("Keep Copper Pea").</summary>
public string RuleName { get; set; } = string.Empty;
/// <summary>True: the profile open in the Loot Editor; false: the one RynthAi loots with.</summary>
public bool ToOpenProfile { get; set; }
/// <summary>Echoed in the draft so the popup knows the answer is to its latest ask.</summary>
public int Seq { get; set; }
}
/// <summary>The rule an item makes, as the popup shows it, and what happened when it was added.</summary>
public sealed class LootEditItemDraft
{
public int Seq { get; set; }
/// <summary>False: Error says why there is no rule (no item selected, read-only profile...).</summary>
public bool Ok { get; set; }
public string Error { get; set; } = string.Empty;
public uint ItemId { get; set; }
public string ItemName { get; set; } = string.Empty;
public string ClassName { get; set; } = string.Empty;
public bool Stackable { get; set; }
public string TargetPath { get; set; } = string.Empty;
public string TargetFile { get; set; } = string.Empty;
/// <summary>The target is the profile RynthAi loots with.</summary>
public bool TargetInUse { get; set; }
/// <summary>"utl" or "json".</summary>
public string Format { get; set; } = string.Empty;
/// <summary>What was built (the defaults filled in).</summary>
public int Match { get; set; }
public int Action { get; set; }
public int KeepCount { get; set; }
public string RuleName { get; set; } = string.Empty;
public string DefaultRuleName { get; set; } = string.Empty;
/// <summary>The rule in words: name, action, one line per condition (ASCII).</summary>
public List<string> Preview { get; set; } = new();
/// <summary>Where it goes (0-based) among RuleCount rules, and why there.</summary>
public int InsertAt { get; set; } = -1;
public int RuleCount { get; set; }
public string OrderNote { get; set; } = string.Empty;
public List<string> Notes { get; set; } = new();
/// <summary>item_add went through; Message says what was added where.</summary>
public bool Added { get; set; }
public string Message { get; set; } = string.Empty;
}
/// <summary>Names for the face's pickers. Sent once per plugin load.</summary>

View file

@ -0,0 +1,390 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using RynthCore.Loot.VTank;
namespace RynthCore.Loot.Editing;
// "Add to loot profile" from a clicked item (2026-10-04): the rule built from
// one item, in the VTank model (the native JSON format gets a converted copy),
// its preview text, and where it goes in the list. Pure data, no AC types:
// RynthAi fills LootItemFacts from its object cache and does the matching.
/// <summary>What RynthAi knows about one item, as plain numbers (no AC or plugin types).</summary>
public sealed class LootItemFacts
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
/// <summary>AcObjectClass (VTank/Decal numbering).</summary>
public int ObjectClass { get; set; }
public int StackSize { get; set; } = 1;
public int MaxStackSize { get; set; } = 1;
/// <summary>Int properties (STypeInt ids, the keys loot rules use). Missing = 0 / unknown.</summary>
public Dictionary<int, int> Ints { get; set; } = new();
/// <summary>Float properties (STypeFloat ids).</summary>
public Dictionary<int, double> Doubles { get; set; } = new();
/// <summary>The item's spell names (empty when none or not identified).</summary>
public List<string> Spells { get; set; } = new();
public bool Stackable => MaxStackSize > 1 || StackSize > 1;
public int Int(int key) => Ints.TryGetValue(key, out int v) ? v : 0;
public double Double(int key) => Doubles.TryGetValue(key, out double v) ? v : 0;
}
/// <summary>How the rule recognises the item.</summary>
public enum LootItemMatch
{
/// <summary>Exact name and object class (the default).</summary>
NameAndClass = 0,
/// <summary>Exact name only.</summary>
Name = 1,
/// <summary>"Items like this": the class plus key properties (material, workmanship, stats, spells); no name.</summary>
Like = 2,
}
public sealed class LootItemRuleOptions
{
public LootItemMatch Match { get; set; } = LootItemMatch.NameAndClass;
/// <summary>Null: the item's default action (Read for scrolls, Keep # for stacks, else Keep).</summary>
public VTankLootAction? Action { get; set; }
/// <summary>Keep # count; null: one full stack.</summary>
public int? KeepCount { get; set; }
/// <summary>Null or blank: "Keep Copper Pea" and the like.</summary>
public string? RuleName { get; set; }
}
/// <summary>A built rule, ready to preview and insert.</summary>
public sealed class LootItemRuleDraft
{
public VTankLootRule Rule { get; init; } = new();
public LootItemMatch Match { get; init; }
public VTankLootAction Action { get; init; }
public int KeepCount { get; init; }
public string DefaultName { get; init; } = string.Empty;
/// <summary>Things the player should know (a broad rule, spells left out...).</summary>
public List<string> Notes { get; init; } = new();
}
public static class LootItemRules
{
// Property ids (STypeInt / STypeFloat, as RynthAi's evaluators read them).
public const int KeyArmorLevel = 28, KeyEquipSlots = 9, KeyDamage = 44, KeyWeaponSkill = 48,
KeyWorkmanship = 105, KeyMaterial = 131, KeyWieldSkill = 159;
public const int KeyElementalDamageMod = 152;
/// <summary>The ratings TotalRatingsGE adds up (same list as both evaluators).</summary>
public static readonly int[] RatingKeys = { 370, 371, 372, 373, 374, 375, 376, 379 };
/// <summary>The int properties a "like this" rule can use: what RynthAi reads into LootItemFacts.</summary>
public static readonly int[] IntKeys =
{ KeyArmorLevel, KeyEquipSlots, KeyDamage, KeyWeaponSkill, KeyWorkmanship, KeyMaterial, KeyWieldSkill, 370, 371, 372, 373, 374, 375, 376, 379 };
public static readonly int[] DoubleKeys = { KeyElementalDamageMod };
/// <summary>Spell conditions a "like this" rule takes at most (all must match: more makes it narrower).</summary>
public const int MaxSpells = 4;
/// <summary>Read for spell scrolls, Keep # for anything that stacks, else Keep.</summary>
public static VTankLootAction DefaultAction(LootItemFacts f)
{
if (f.ObjectClass == (int)AcObjectClass.Scroll) return VTankLootAction.Read;
if (f.Stackable) return VTankLootAction.KeepUpTo;
return VTankLootAction.Keep;
}
/// <summary>Keep # default: one full stack (the item's own stack when the maximum isn't known).</summary>
public static int DefaultKeepCount(LootItemFacts f) => Math.Max(1, f.MaxStackSize > 1 ? f.MaxStackSize : f.StackSize);
/// <summary>
/// A name as an exact, case-insensitive regex: ^name$ with the regex
/// metacharacters escaped (spaces left alone, unlike Regex.Escape, so it reads well).
/// </summary>
public static string ExactPattern(string name)
{
var sb = new StringBuilder(name.Length + 8);
sb.Append('^');
foreach (char ch in name)
{
if ("\\*+?|{}[]()^$.#".IndexOf(ch) >= 0) sb.Append('\\');
sb.Append(ch);
}
sb.Append('$');
return sb.ToString();
}
public static string ClassName(int objectClass) =>
Enum.IsDefined(typeof(AcObjectClass), objectClass) ? ((AcObjectClass)objectClass).ToString() : "class " + objectClass.ToString(CultureInfo.InvariantCulture);
/// <summary>"Keep Copper Pea", "Keep 100 Copper Pea", "Salvage like Iron Mace".</summary>
public static string DefaultRuleName(string itemName, VTankLootAction action, int keepCount, LootItemMatch match)
{
string verb = action == VTankLootAction.KeepUpTo
? "Keep " + keepCount.ToString(CultureInfo.InvariantCulture)
: LootRuleText.ActionName(action);
return match == LootItemMatch.Like ? $"{verb} like {itemName}" : $"{verb} {itemName}";
}
/// <summary>Builds the rule. Null (and <paramref name="error"/>) when the item can't make one.</summary>
public static LootItemRuleDraft? Build(LootItemFacts f, LootItemRuleOptions o, out string error)
{
error = string.Empty;
string name = OneLine(f.Name).Trim();
if (name.Length == 0 && o.Match != LootItemMatch.Like)
{
error = "That item has no name yet; try again in a moment.";
return null;
}
VTankLootAction action = o.Action ?? DefaultAction(f);
if (!LootRuleText.IsKnownAction((int)action))
{
error = $"Unknown action {(int)action}.";
return null;
}
int keep = o.KeepCount ?? DefaultKeepCount(f);
if (action == VTankLootAction.KeepUpTo && keep < 0)
{
error = "Keep # needs a count of 0 or more.";
return null;
}
var notes = new List<string>();
var rule = new VTankLootRule
{
CustomExpression = string.Empty,
Action = action,
KeepCount = action == VTankLootAction.KeepUpTo ? keep : null,
};
bool hasClass = f.ObjectClass != (int)AcObjectClass.Unknown;
LootItemMatch match = o.Match;
if (match == LootItemMatch.NameAndClass && !hasClass)
{
match = LootItemMatch.Name;
notes.Add("The item's class isn't known yet, so the rule matches the name only.");
}
switch (match)
{
case LootItemMatch.NameAndClass:
rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass)));
rule.Conditions.Add(Cond(VTankNodeTypes.StringValueMatch, ExactPattern(name), "1"));
break;
case LootItemMatch.Name:
rule.Conditions.Add(Cond(VTankNodeTypes.StringValueMatch, ExactPattern(name), "1"));
break;
case LootItemMatch.Like:
if (!hasClass)
{
error = "The item's class isn't known yet; \"items like this\" needs it.";
return null;
}
rule.Conditions.Add(Cond(VTankNodeTypes.ObjectClass, Num(f.ObjectClass)));
int extra = AddLikeConditions(rule, f, notes);
if (extra == 0)
notes.Add($"Nothing but the class to go on: this rule matches every {ClassName(f.ObjectClass)}."
+ (f.Ints.Count == 0 ? " (Assess the item first for its material, workmanship and stats.)" : string.Empty));
break;
}
string defaultName = DefaultRuleName(name.Length > 0 ? name : ClassName(f.ObjectClass), action, keep, match);
string ruleName = OneLine(o.RuleName).Trim();
rule.Name = ruleName.Length > 0 ? ruleName : defaultName;
return new LootItemRuleDraft { Rule = rule, Match = match, Action = action, KeepCount = keep, DefaultName = defaultName, Notes = notes };
}
/// <summary>The "like this" conditions for the item's kind; how many it added.</summary>
private static int AddLikeConditions(VTankLootRule rule, LootItemFacts f, List<string> notes)
{
int n = rule.Conditions.Count;
var cls = (AcObjectClass)f.ObjectClass;
void LongE(int key) { int v = f.Int(key); if (v != 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyE, Num(v), Num(key))); }
void LongGE(int key) { int v = f.Int(key); if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.LongValKeyGE, Num(v), Num(key))); }
void DoubleGE(int key)
{
double v = f.Double(key);
if (v > 0) rule.Conditions.Add(Cond(VTankNodeTypes.DoubleValKeyGE, v.ToString("0.####", CultureInfo.InvariantCulture), Num(key)));
}
LongE(KeyMaterial);
LongGE(KeyWorkmanship);
switch (cls)
{
case AcObjectClass.MeleeWeapon:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); else LongE(KeyWeaponSkill);
LongGE(KeyDamage);
break;
case AcObjectClass.MissileWeapon:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill); else LongE(KeyWeaponSkill);
break;
case AcObjectClass.WandStaffOrb:
if (f.Int(KeyWieldSkill) != 0) LongE(KeyWieldSkill);
DoubleGE(KeyElementalDamageMod);
break;
case AcObjectClass.Armor:
case AcObjectClass.Clothing:
LongE(KeyEquipSlots);
LongGE(KeyArmorLevel);
break;
case AcObjectClass.Jewelry:
LongE(KeyEquipSlots);
break;
}
int ratings = 0;
foreach (int k in RatingKeys) ratings += Math.Max(0, f.Int(k));
if (ratings > 0) rule.Conditions.Add(Cond(VTankNodeTypes.TotalRatingsGE, Num(ratings)));
int spells = 0;
foreach (string s in f.Spells)
{
string sn = OneLine(s).Trim();
if (sn.Length == 0) continue;
if (spells == MaxSpells)
{
notes.Add($"The item has more than {MaxSpells} spells; the rule checks the first {MaxSpells}.");
break;
}
rule.Conditions.Add(Cond(VTankNodeTypes.SpellNameMatch, ExactPattern(sn)));
spells++;
}
return rule.Conditions.Count - n;
}
private static VTankLootCondition Cond(int type, params string[] lines) => new(type, "0", lines);
private static string Num(int v) => v.ToString(CultureInfo.InvariantCulture);
private static string OneLine(string? s) =>
string.IsNullOrEmpty(s) ? string.Empty : s.Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
// =====================================================================
// Native (JSON) profiles
// =====================================================================
/// <summary>
/// The rule in the native format. Conditions it has no class for (spells)
/// are left out and named in <paramref name="dropped"/>; null when the rule
/// would end up with none of its conditions (it would match everything).
/// </summary>
public static LootRule? ToNative(VTankLootRule r, List<string> dropped)
{
var rule = new LootRule
{
Name = r.Name,
Enabled = r.Enabled,
Action = r.Action switch
{
VTankLootAction.Sell => LootAction.Sell,
VTankLootAction.Salvage => LootAction.Salvage,
VTankLootAction.Read => LootAction.Read,
VTankLootAction.KeepUpTo => LootAction.KeepUpTo,
_ => LootAction.Keep,
},
KeepCount = r.Action == VTankLootAction.KeepUpTo ? r.KeepCount ?? 0 : 1,
};
int wanted = 0;
foreach (VTankLootCondition c in r.Conditions)
{
if (c.NodeType == VTankNodeTypes.DisabledRule) continue;
wanted++;
LootCondition? n = NativeCondition(c);
if (n != null) rule.Conditions.Add(n);
else dropped.Add(LootRuleText.Condition(c));
}
return wanted > 0 && rule.Conditions.Count == 0 ? null : rule;
}
private static LootCondition? NativeCondition(VTankLootCondition c)
{
IList<string> d = c.DataLines;
int I(int i) => int.Parse(d[i], NumberStyles.Integer, CultureInfo.InvariantCulture);
double D(int i) => double.Parse(d[i], NumberStyles.Float, CultureInfo.InvariantCulture);
try
{
return c.NodeType switch
{
VTankNodeTypes.ObjectClass => new ObjectClassCondition { ObjectClass = (AcObjectClass)I(0) },
VTankNodeTypes.StringValueMatch => new StringValueCondition { Pattern = d[0], Key = I(1) },
VTankNodeTypes.LongValKeyE => new LongValKeyECondition { Value = I(0), Key = I(1) },
VTankNodeTypes.LongValKeyNE => new LongValKeyNECondition { Value = I(0), Key = I(1) },
VTankNodeTypes.LongValKeyGE => new LongValKeyGECondition { Value = I(0), Key = I(1) },
VTankNodeTypes.LongValKeyLE => new LongValKeyLECondition { Value = I(0), Key = I(1) },
VTankNodeTypes.LongValKeyFlagExists => new LongValKeyFlagCondition { FlagValue = I(0), Key = I(1) },
VTankNodeTypes.DoubleValKeyGE => new DoubleValKeyGECondition { Value = D(0), Key = I(1) },
VTankNodeTypes.DoubleValKeyLE => new DoubleValKeyLECondition { Value = D(0), Key = I(1) },
VTankNodeTypes.TotalRatingsGE => new TotalRatingsGECondition { Value = (int)Math.Ceiling(D(0)) },
VTankNodeTypes.MinDamageGE => new MinDamageGECondition { Value = D(0) },
_ => null,
};
}
catch (FormatException) { return null; }
catch (ArgumentOutOfRangeException) { return null; }
}
// =====================================================================
// Preview and placement
// =====================================================================
/// <summary>The rule as the popup shows it: name, action, one line per condition.</summary>
public static List<string> PreviewLines(VTankLootRule r)
{
var lines = new List<string>
{
"Rule: " + r.Name,
"Action: " + (r.Action == VTankLootAction.KeepUpTo
? "Keep # " + (r.KeepCount ?? 0).ToString(CultureInfo.InvariantCulture)
: LootRuleText.ActionName(r.Action)),
};
bool first = true;
foreach (VTankLootCondition c in r.Conditions)
{
if (c.NodeType == VTankNodeTypes.DisabledRule) continue;
lines.Add((first ? "If: " : "and ") + LootRuleText.Condition(c));
first = false;
}
if (first) lines.Add("If: (every item)");
return lines;
}
/// <summary>
/// Where the rule goes: just before the first rule that matches the item now
/// (rules run top to bottom and the first match wins, so this is the latest
/// spot where the new rule still decides the item, and it moves no other
/// rule's items but this item's look-alikes); the end when nothing matches it.
/// <paramref name="matches"/> says whether rule i matches the item.
/// </summary>
public static int ChooseIndex(int ruleCount, Func<int, bool> matches)
{
for (int i = 0; i < ruleCount; i++)
if (matches(i)) return i;
return ruleCount;
}
/// <summary>Same action (and count) and the same conditions in the same order, names aside.</summary>
public static bool SameRule(VTankLootRule a, VTankLootRule b)
{
if (a.Action != b.Action || a.Enabled != b.Enabled) return false;
if (a.Action == VTankLootAction.KeepUpTo && (a.KeepCount ?? 0) != (b.KeepCount ?? 0)) return false;
var ca = Live(a);
var cb = Live(b);
if (ca.Count != cb.Count) return false;
for (int i = 0; i < ca.Count; i++)
{
if (ca[i].NodeType != cb[i].NodeType || ca[i].DataLines.Count != cb[i].DataLines.Count) return false;
for (int j = 0; j < ca[i].DataLines.Count; j++)
if (!string.Equals(ca[i].DataLines[j].Trim(), cb[i].DataLines[j].Trim(), StringComparison.OrdinalIgnoreCase)) return false;
}
return true;
static List<VTankLootCondition> Live(VTankLootRule r) => r.Conditions.FindAll(c => c.NodeType != VTankNodeTypes.DisabledRule);
}
/// <summary>Native rules: same action (and count) and the same conditions, names aside.</summary>
public static bool SameRule(LootRule a, LootRule b)
{
if (a.Action != b.Action || a.Enabled != b.Enabled) return false;
if (a.Action == LootAction.KeepUpTo && a.KeepCount != b.KeepCount) return false;
if (a.Conditions.Count != b.Conditions.Count) return false;
for (int i = 0; i < a.Conditions.Count; i++)
if (!string.Equals(a.Conditions[i].ToString(), b.Conditions[i].ToString(), StringComparison.OrdinalIgnoreCase)) return false;
return true;
}
}

View file

@ -0,0 +1,173 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
namespace RynthCore.Loot.Editing;
/// <summary>
/// Adds one rule to a native (.json) loot profile by splicing its JSON into the
/// file's "Rules" array: every byte outside the insertion stays as it was
/// (LootProfile.Save would rewrite the whole file, and the JSON writer drops
/// what it doesn't know). The result is checked before it is returned: it must
/// load, have one more rule, and serialise exactly like the original once the
/// new rule is taken out again.
/// </summary>
public static class LootJsonSplice
{
/// <summary>
/// The file's bytes with <paramref name="rule"/> inserted at <paramref name="index"/>
/// (the end when out of range; <paramref name="at"/> says where it went), or
/// null with <paramref name="error"/>.
/// </summary>
public static byte[]? Insert(byte[] file, LootRule rule, int index, out int at, out string error)
{
at = -1;
error = string.Empty;
int start = file.Length >= 3 && file[0] == 0xEF && file[1] == 0xBB && file[2] == 0xBF ? 3 : 0;
LootProfile? before;
try
{
// Strict UTF-8: a file that isn't is refused rather than re-encoded.
string text = new UTF8Encoding(false, true).GetString(file, start, file.Length - start);
before = JsonSerializer.Deserialize(text, LootJsonContext.Default.LootProfile);
}
catch (Exception ex)
{
error = "the profile doesn't load as it is (" + ex.Message + ").";
return null;
}
if (before == null) { error = "the profile is empty (null)."; return null; }
if (!FindRules(file, start, out int open, out int close, out List<(int Start, int End)> elements, out error))
return null;
if (elements.Count != before.Rules.Count)
{
error = $"found {elements.Count} rules in the text but {before.Rules.Count} when loaded.";
return null;
}
string nl = Contains(file, start, "\r\n") ? "\r\n" : "\n";
string ruleJson = JsonSerializer.Serialize(rule, LootJsonContext.Default.LootRule).Replace("\r\n", "\n");
at = index < 0 || index > elements.Count ? elements.Count : index;
string insert;
int spliceAt, spliceEnd;
if (elements.Count == 0)
{
// "[]" or "[ ... ]" with only whitespace: replace the inside.
string outer = LineIndent(file, start, open);
string indent = outer + " ";
insert = nl + indent + Reindent(ruleJson, indent, nl) + nl + outer;
spliceAt = open + 1;
spliceEnd = close;
}
else
{
string indent = LineIndent(file, start, elements[0].Start);
if (at < elements.Count)
{
insert = Reindent(ruleJson, indent, nl) + "," + nl + indent;
spliceAt = spliceEnd = elements[at].Start;
}
else
{
insert = "," + nl + indent + Reindent(ruleJson, indent, nl);
spliceAt = spliceEnd = elements[^1].End;
}
}
byte[] add = Encoding.UTF8.GetBytes(insert);
var result = new byte[spliceAt + add.Length + (file.Length - spliceEnd)];
Array.Copy(file, 0, result, 0, spliceAt);
Array.Copy(add, 0, result, spliceAt, add.Length);
Array.Copy(file, spliceEnd, result, spliceAt + add.Length, file.Length - spliceEnd);
// Check: loads, one more rule, the new one where it should be, the rest unchanged.
try
{
LootProfile? after = JsonSerializer.Deserialize(Encoding.UTF8.GetString(result, start, result.Length - start), LootJsonContext.Default.LootProfile);
if (after == null || after.Rules.Count != before.Rules.Count + 1)
{
error = "the result doesn't have exactly one more rule.";
return null;
}
if (JsonSerializer.Serialize(after.Rules[at], LootJsonContext.Default.LootRule) != JsonSerializer.Serialize(rule, LootJsonContext.Default.LootRule))
{
error = "the new rule reads back differently.";
return null;
}
after.Rules.RemoveAt(at);
if (JsonSerializer.Serialize(after, LootJsonContext.Default.LootProfile) != JsonSerializer.Serialize(before, LootJsonContext.Default.LootProfile))
{
error = "another part of the profile would change.";
return null;
}
}
catch (Exception ex)
{
error = "the result doesn't load (" + ex.Message + ").";
return null;
}
return result;
}
/// <summary>Finds the root object's "Rules" array: its brackets and each element's byte range.</summary>
private static bool FindRules(byte[] file, int start, out int open, out int close, out List<(int Start, int End)> elements, out string error)
{
open = close = -1;
elements = new List<(int, int)>();
error = string.Empty;
var reader = new Utf8JsonReader(new ReadOnlySpan<byte>(file, start, file.Length - start));
bool found = false;
try
{
if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) { error = "the file isn't a JSON object."; return false; }
while (reader.Read() && reader.TokenType == JsonTokenType.PropertyName)
{
if (!reader.ValueTextEquals("Rules"u8))
{
reader.Skip();
continue;
}
if (found) { error = "the file has two \"Rules\" lists."; return false; }
found = true;
if (!reader.Read() || reader.TokenType != JsonTokenType.StartArray) { error = "\"Rules\" isn't a list."; return false; }
open = start + (int)reader.TokenStartIndex;
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
int s = start + (int)reader.TokenStartIndex;
reader.Skip();
elements.Add((s, start + (int)reader.TokenStartIndex + 1));
}
close = start + (int)reader.TokenStartIndex;
}
}
catch (JsonException ex)
{
error = "the file isn't valid JSON (" + ex.Message + ").";
return false;
}
if (!found) { error = "the file has no \"Rules\" list."; return false; }
return true;
}
/// <summary>The spaces/tabs from the start of the line holding <paramref name="pos"/> up to the first other character.</summary>
private static string LineIndent(byte[] file, int start, int pos)
{
int lineStart = pos;
while (lineStart > start && file[lineStart - 1] != (byte)'\n') lineStart--;
int end = lineStart;
while (end < pos && (file[end] == (byte)' ' || file[end] == (byte)'\t')) end++;
return Encoding.ASCII.GetString(file, lineStart, end - lineStart);
}
/// <summary>The serializer's indented JSON (LF) shifted right by <paramref name="indent"/> after its first line.</summary>
private static string Reindent(string json, string indent, string nl) => json.Replace("\n", nl + indent);
private static bool Contains(byte[] file, int start, string ascii)
{
byte[] needle = Encoding.ASCII.GetBytes(ascii);
return new ReadOnlySpan<byte>(file, start, file.Length - start).IndexOf(needle) >= 0;
}
}

View file

@ -40,13 +40,14 @@ public static class LootRuleText
public static readonly (int Id, string Name)[] LongKeys =
{
(5, "EncumbVal"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (45, "DamageType"),
(5, "EncumbVal"), (9, "Locations"), (19, "Value"), (25, "Level"), (28, "ArmorLevel"), (44, "Damage"), (45, "DamageType"),
(48, "WeaponSkill"), (54, "MaxDamage"),
(87, "MaxStructure"), (88, "Structure"), (105, "ItemWorkmanship"), (107, "ItemMaxMana"),
(131, "MaterialType"), (158, "WieldRequirements"), (159, "WieldSkilltype"), (160, "WieldDifficulty"),
(218, "EquippedSlots"), (353, "ImbuedEffect"), (370, "DamageRating"), (371, "DamageResistRating"),
(372, "CritRating"), (373, "CritResistRating"), (374, "CritDamageRating"),
(375, "CritDamageResistRating"), (376, "HealBoostRating"), (379, "VitalityRating"),
(0x0D000000, "Type (WCID)"), // Decal's synthetic key: the weenie class id
};
public static readonly (int Id, string Name)[] DoubleKeys =

View file

@ -0,0 +1,506 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using RynthCore.Loot;
using RynthCore.Loot.Editing;
using RynthCore.Loot.VTank;
namespace RynthCore.LootSdkTests;
// "Add to loot profile" from a clicked item (2026-10-04): the rule an item
// makes (LootItemRules), its placement, and LootEditSession.InsertAndSave on
// both formats. The safety tests check the saved file byte for byte: the
// original with one rule spliced in, the old file kept as .bak, and the result
// opening editable in the in-game editor and loading in the parser the external
// editor and the evaluator use. Only temp copies are ever written.
internal static partial class Program
{
private static string _addDir = string.Empty;
private static void RunLootAddTests(string[] args)
{
_addDir = Path.Combine(Path.GetTempPath(), "RynthLootAddTests_" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_addDir);
try
{
TestAddDefaults();
TestAddExactPattern();
TestAddLikeThis();
TestAddPreviewAndOrder();
TestAddNative();
TestAddUtlInsert(crlf: false);
TestAddUtlInsert(crlf: true);
TestAddUtlRefusals();
TestAddUtlV0();
TestAddJsonInsert(crlf: false);
TestAddJsonInsert(crlf: true);
TestAddJsonEdgeCases();
TestAddDeployedCopies(args);
}
finally
{
try { Directory.Delete(_addDir, recursive: true); } catch { }
}
}
private static string AddFile(string name, byte[] bytes)
{
string path = Path.Combine(_addDir, name);
File.WriteAllBytes(path, bytes);
return path;
}
private static LootItemFacts Pea() => new() { Id = 1, Name = "Copper Pea", ObjectClass = (int)AcObjectClass.Misc, StackSize = 5, MaxStackSize = 100 };
private static LootItemFacts Opal() => new() { Id = 2, Name = "Black Opal", ObjectClass = (int)AcObjectClass.Gem, Ints = { [131] = 16, [105] = 6 } };
private static LootItemRuleDraft BuildOk(LootItemFacts f, LootItemRuleOptions? o = null)
{
LootItemRuleDraft? d = LootItemRules.Build(f, o ?? new LootItemRuleOptions(), out string error);
Check(d != null, $"build {f.Name}: {error}");
return d ?? new LootItemRuleDraft();
}
private static string Lines(VTankLootCondition c) => c.NodeType + ":" + string.Join("|", c.DataLines);
private static void TestAddDefaults()
{
Console.WriteLine("\n-- LootAdd: rule from an item, defaults --");
LootItemRuleDraft opal = BuildOk(Opal());
Eq(opal.Rule.Action, VTankLootAction.Keep, "gem: Keep");
Eq(opal.Rule.KeepCount, (int?)null, "Keep has no count line");
Eq(opal.Rule.Name, "Keep Black Opal", "default name");
Eq(string.Join(" ; ", opal.Rule.Conditions.Select(Lines)), "7:11 ; 1:^Black Opal$|1", "name + class conditions");
Eq(opal.Rule.CustomExpression, "", "v1 custom expression line (empty)");
Check(opal.Rule.Enabled, "enabled");
LootItemRuleDraft pea = BuildOk(Pea());
Eq(pea.Rule.Action, VTankLootAction.KeepUpTo, "stack: Keep #");
Eq(pea.Rule.KeepCount, (int?)100, "Keep # defaults to one full stack");
Eq(pea.Rule.Name, "Keep 100 Copper Pea", "Keep # name says the count");
var scroll = new LootItemFacts { Name = "Scroll of Fire Bolt VI", ObjectClass = (int)AcObjectClass.Scroll };
Eq(BuildOk(scroll).Rule.Action, VTankLootAction.Read, "spell scroll: Read");
var bag = new LootItemFacts { Name = "Salvaged Iron", ObjectClass = (int)AcObjectClass.Salvage, Ints = { [131] = 61 } };
Eq(BuildOk(bag).Rule.Action, VTankLootAction.Keep, "salvage bag: Keep (it is salvage already)");
var unstacked = new LootItemFacts { Name = "Mana Stone", ObjectClass = (int)AcObjectClass.ManaStone, StackSize = 3 };
Eq(BuildOk(unstacked).Rule.KeepCount, (int?)3, "no max stack known: its own stack");
LootItemRuleDraft named = BuildOk(Pea(), new LootItemRuleOptions
{
Match = LootItemMatch.Name, Action = VTankLootAction.Sell, RuleName = " Sell peas\nplease ",
});
Eq(named.Rule.Action, VTankLootAction.Sell, "action chosen");
Eq(named.Rule.KeepCount, (int?)null, "Sell: no count");
Eq(named.Rule.Name, "Sell peas please", "rule name: one line, trimmed");
Eq(string.Join(" ; ", named.Rule.Conditions.Select(Lines)), "1:^Copper Pea$|1", "name only");
LootItemRuleDraft kc = BuildOk(Pea(), new LootItemRuleOptions { Action = VTankLootAction.KeepUpTo, KeepCount = 25 });
Eq(kc.Rule.KeepCount, (int?)25, "Keep # count chosen");
Eq(kc.DefaultName, "Keep 25 Copper Pea", "default name follows the count");
var unknown = new LootItemFacts { Name = "Odd Thing" };
LootItemRuleDraft u = BuildOk(unknown);
Eq(u.Match, LootItemMatch.Name, "unknown class: name only");
Check(u.Notes.Count == 1, "and says so");
Check(LootItemRules.Build(new LootItemFacts { ObjectClass = 11 }, new LootItemRuleOptions(), out string e1) == null && e1.Length > 0, "no name: refused");
Check(LootItemRules.Build(Pea(), new LootItemRuleOptions { Action = (VTankLootAction)7 }, out string e2) == null && e2.Length > 0, "unknown action: refused");
Check(LootItemRules.Build(Pea(), new LootItemRuleOptions { Action = VTankLootAction.KeepUpTo, KeepCount = -1 }, out _) == null, "negative Keep #: refused");
}
private static void TestAddExactPattern()
{
Console.WriteLine("\n-- LootAdd: exact name patterns --");
string name = "Scroll of Fire Bolt (III). [x] a+b? $5 ^ | {1} #9 \\";
string pattern = LootItemRules.ExactPattern(name);
Check(Regex.IsMatch(name, pattern, RegexOptions.IgnoreCase), "matches its own name");
Check(Regex.IsMatch(name.ToUpperInvariant(), pattern, RegexOptions.IgnoreCase), "case-insensitive (as both evaluators match)");
Check(!Regex.IsMatch(name + "x", pattern, RegexOptions.IgnoreCase), "not a longer name");
Check(!Regex.IsMatch("x" + name, pattern, RegexOptions.IgnoreCase), "not a name with a prefix");
Eq(LootItemRules.ExactPattern("Copper Pea"), "^Copper Pea$", "plain names stay readable (spaces not escaped)");
Check(!Regex.IsMatch("Copper Peas", LootItemRules.ExactPattern("Copper Pea"), RegexOptions.IgnoreCase), "Copper Pea is not Copper Peas");
}
private static void TestAddLikeThis()
{
Console.WriteLine("\n-- LootAdd: items like this --");
var armor = new LootItemFacts
{
Name = "Iron Breastplate", ObjectClass = (int)AcObjectClass.Armor,
Ints = { [131] = 61, [105] = 7, [28] = 300, [9] = 512, [370] = 2, [374] = 1 },
Spells = { "Strength Self VI", "Impenetrability VI", "", "Blade Bane VI", "Fire Bane VI", "Acid Bane VI" },
};
LootItemRuleDraft d = BuildOk(armor, new LootItemRuleOptions { Match = LootItemMatch.Like });
string conds = string.Join(" ; ", d.Rule.Conditions.Select(Lines));
Eq(conds, "7:2 ; 12:61|131 ; 3:7|105 ; 12:512|9 ; 3:300|28 ; 2007:3 ; 0:^Strength Self VI$ ; 0:^Impenetrability VI$ ; 0:^Blade Bane VI$ ; 0:^Fire Bane VI$",
"class, material, workmanship >=, slot, armor >=, ratings >=, the first 4 spells");
Check(!d.Rule.Conditions.Any(c => c.NodeType == VTankNodeTypes.StringValueMatch), "no name condition");
Check(d.Notes.Any(n => n.Contains("more than 4 spells")), "says spells were left out");
Eq(d.Rule.Name, "Keep like Iron Breastplate", "like name");
var mace = new LootItemFacts { Name = "Iron Mace", ObjectClass = (int)AcObjectClass.MeleeWeapon, Ints = { [159] = 45, [44] = 20, [48] = 5 } };
Eq(string.Join(" ; ", BuildOk(mace, new() { Match = LootItemMatch.Like }).Rule.Conditions.Select(Lines)),
"7:1 ; 12:45|159 ; 3:20|44", "melee: wield skill and damage >= (wield skill preferred to weapon skill)");
var wand = new LootItemFacts { Name = "Wand", ObjectClass = (int)AcObjectClass.WandStaffOrb, Doubles = { [152] = 1.12 } };
Eq(string.Join(" ; ", BuildOk(wand, new() { Match = LootItemMatch.Like }).Rule.Conditions.Select(Lines)),
"7:31 ; 5:1.12|152", "caster: elemental damage >=");
LootItemRuleDraft bare = BuildOk(new LootItemFacts { Name = "Gem", ObjectClass = 11 }, new() { Match = LootItemMatch.Like });
Eq(bare.Rule.Conditions.Count, 1, "nothing known: class only");
Check(bare.Notes.Any(n => n.Contains("every Gem") && n.Contains("Assess")), "warns that it matches every Gem");
Check(LootItemRules.Build(new LootItemFacts { Name = "x" }, new() { Match = LootItemMatch.Like }, out string e) == null && e.Length > 0,
"like without a class: refused");
}
private static void TestAddPreviewAndOrder()
{
Console.WriteLine("\n-- LootAdd: preview and placement --");
List<string> p = LootItemRules.PreviewLines(BuildOk(Opal(), new() { Match = LootItemMatch.Like }).Rule);
Eq(string.Join(" / ", p), "Rule: Keep like Black Opal / Action: Keep / If: Class is Gem / and MaterialType = Black Opal / and ItemWorkmanship >= 6",
"preview lines (values by name)");
List<string> k = LootItemRules.PreviewLines(BuildOk(Pea()).Rule);
Eq(k[1], "Action: Keep # 100", "Keep # preview");
Eq(k[3], "and Name matches \"^Copper Pea$\"", "name line");
Eq(LootItemRules.ChooseIndex(5, i => i == 3 || i == 4), 3, "before the first rule that matches");
Eq(LootItemRules.ChooseIndex(5, _ => false), 5, "nothing matches: the end");
Eq(LootItemRules.ChooseIndex(0, _ => true), 0, "empty profile: 0");
VTankLootRule a = BuildOk(Opal()).Rule, b = BuildOk(Opal(), new() { RuleName = "other" }).Rule;
Check(LootItemRules.SameRule(a, b), "same rule, names aside");
Check(!LootItemRules.SameRule(a, BuildOk(Opal(), new() { Action = VTankLootAction.Sell }).Rule), "another action differs");
Check(!LootItemRules.SameRule(a, BuildOk(Opal(), new() { Match = LootItemMatch.Name }).Rule), "other conditions differ");
}
private static void TestAddNative()
{
Console.WriteLine("\n-- LootAdd: native (JSON) form --");
var dropped = new List<string>();
LootRule? n = LootItemRules.ToNative(BuildOk(Pea()).Rule, dropped);
Check(n != null && dropped.Count == 0, "name + class converts whole");
Eq(n?.Action, LootAction.KeepUpTo, "Keep #");
Eq(n?.KeepCount, 100, "count");
Eq(n == null ? "" : string.Join(" ; ", n.Conditions), "ObjectClass == Misc ; StringKey[1] matches \"^Copper Pea$\"", "conditions");
Eq(LootItemRules.ToNative(BuildOk(Opal()).Rule, dropped)?.KeepCount, 1, "Keep: count 1 (the native default)");
var armor = new LootItemFacts { Name = "Robe", ObjectClass = (int)AcObjectClass.Clothing, Ints = { [28] = 50 }, Spells = { "Epic Strength" } };
dropped.Clear();
LootRule? like = LootItemRules.ToNative(BuildOk(armor, new() { Match = LootItemMatch.Like }).Rule, dropped);
Eq(like == null ? "" : string.Join(" ; ", like.Conditions), "ObjectClass == Clothing ; LongKey[28] >= 50", "spell left out");
Eq(dropped.Count, 1, "and named");
var onlySpell = new VTankLootRule { Conditions = { new VTankLootCondition(VTankNodeTypes.SpellNameMatch, "0", new[] { "x" }) } };
Check(LootItemRules.ToNative(onlySpell, new List<string>()) == null, "a rule left with no conditions is refused (it would match everything)");
}
// ── .utl ─────────────────────────────────────────────────────────────
/// <summary>
/// <paramref name="after"/> is <paramref name="before"/> with the rule count line
/// bumped and one block of <paramref name="blockLines"/> lines inserted, nothing else.
/// </summary>
private static void CheckSplicedUtl(string before, string after, int blockLines, string label)
{
string nl = before.Contains("\r\n") ? "\r\n" : "\n";
Check(after.Contains("\r\n") == (nl == "\r\n"), $"{label}: line endings kept");
var a = before.Split(nl).ToList();
var b = after.Split(nl).ToList();
Eq(b.Count, a.Count + blockLines, $"{label}: one block of {blockLines} lines added");
int countLine = a[0] == "UTL" ? 2 : 0;
Eq(int.Parse(b[countLine]), int.Parse(a[countLine]) + 1, $"{label}: rule count line +1");
b[countLine] = a[countLine];
int first = 0;
while (first < a.Count && a[first] == b[first]) first++;
b.RemoveRange(first, Math.Min(blockLines, b.Count - first));
Check(a.SequenceEqual(b), $"{label}: every other line unchanged");
}
private static int RuleLineCount(VTankLootRule r, int version)
{
string text = VTankLootWriter.Serialize(new VTankLootProfile { FileVersion = version, Rules = { r } });
return text.Split('\n').Length - 1 - (version >= 1 ? 3 : 1);
}
private static void TestAddUtlInsert(bool crlf)
{
string label = crlf ? "utl CRLF" : "utl LF";
Console.WriteLine($"\n-- LootAdd: insert into a .utl ({label}) --");
string text = crlf ? EditFixture.Replace("\n", "\r\n") : EditFixture;
byte[] original = Encoding.UTF8.GetBytes(text);
string path = AddFile(crlf ? "add-crlf.utl" : "add.utl", original);
var s = new LootEditSession();
Check(s.Open(path) && !s.IsReadOnly && s.CanInsert, $"{label}: opens editable");
var before = VTankLootParser.LoadFromText(text);
VTankLootRule rule = BuildOk(Pea()).Rule;
Check(s.InsertAndSave(rule, null, 2), $"{label}: inserted at 3: {s.Message}");
Check(s.Message.Contains("Added \"Keep 100 Copper Pea\" at 3"), $"{label}: message says what and where ({s.Message})");
Check(!s.IsDirty, $"{label}: saved, nothing pending");
Eq(s.BuildState("", null).Focus, 2, $"{label}: focus on the new rule (the editor selects it)");
byte[] saved = File.ReadAllBytes(path);
Check(File.ReadAllBytes(path + ".bak").AsSpan().SequenceEqual(original), $"{label}: .bak == the original bytes");
Check(!File.Exists(path + ".tmp"), $"{label}: no .tmp left");
CheckSplicedUtl(text, Encoding.UTF8.GetString(saved), RuleLineCount(rule, 1), label);
// Loads everywhere: the parser (external editor, evaluator, /ra lootparse) and the in-game editor.
VTankLootProfile back = VTankLootParser.Load(path);
Eq(back.Rules.Count, 6, $"{label}: parser reads 6 rules");
Eq(back.Rules[2].Name, "Keep 100 Copper Pea", $"{label}: new rule at 3");
Eq(back.Rules[2].KeepCount, (int?)100, $"{label}: its count");
Eq(string.Join(" ; ", back.Rules[2].Conditions.Select(Lines)), "7:8 ; 1:^Copper Pea$|1", $"{label}: its conditions");
for (int i = 0, j = 0; i < back.Rules.Count; i++)
{
if (i == 2) continue;
VTankLootRule o = before.Rules[j++], n = back.Rules[i];
Check(o.Name == n.Name && o.Action == n.Action && o.KeepCount == n.KeepCount && o.Priority == n.Priority
&& o.CustomExpression == n.CustomExpression && o.Conditions.Select(Lines).SequenceEqual(n.Conditions.Select(Lines))
&& o.Conditions.Select(c => c.LengthCode).SequenceEqual(n.Conditions.Select(c => c.LengthCode)),
$"{label}: rule '{o.Name}' unchanged");
}
Check(back.SalvageCombine != null && back.SalvageCombine.PerMaterial.Count == before.SalvageCombine!.PerMaterial.Count,
$"{label}: salvage combine block kept");
var again = new LootEditSession();
Check(again.Open(path) && !again.IsReadOnly, $"{label}: reopens editable in the in-game editor (round-trips)");
Check(again.Encode().AsSpan().SequenceEqual(saved), $"{label}: and would save it byte-identical");
// At the end, then at the top.
Check(s.InsertAndSave(BuildOk(Opal()).Rule, null, -1), $"{label}: append");
Eq(VTankLootParser.Load(path).Rules[^1].Name, "Keep Black Opal", $"{label}: appended last");
Check(s.InsertAndSave(BuildOk(Opal(), new() { RuleName = "Top" }).Rule, null, 0), $"{label}: insert at the top");
Eq(VTankLootParser.Load(path).Rules[0].Name, "Top", $"{label}: first");
Eq(VTankLootParser.Load(path).Rules.Count, 8, $"{label}: 8 rules");
}
private static void TestAddUtlRefusals()
{
Console.WriteLine("\n-- LootAdd: .utl refusals leave the file alone --");
byte[] original = Encoding.UTF8.GetBytes(EditFixture);
string path = AddFile("refuse.utl", original);
var s = new LootEditSession();
s.Open(path);
Cmd(s, "rename", 0, "half-done edit");
Check(s.IsDirty, "an unsaved edit");
Check(!s.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "refused while there are unsaved edits");
Check(s.Message.Contains("Unsaved changes"), "says why");
Check(File.ReadAllBytes(path).AsSpan().SequenceEqual(original), "file untouched");
Eq(s.RuleCount, 5, "no phantom rule in the session");
string odd = EditFixture.Replace("3;1;7", "3;1;7;abc");
string opath = AddFile("refuse-odd.utl", Encoding.UTF8.GetBytes(odd));
var o = new LootEditSession();
o.Open(opath);
Check(o.IsReadOnly && !o.CanInsert, "non-round-tripping .utl: no insert");
Check(!o.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "refused");
Eq(File.ReadAllText(opath), odd, "file untouched");
// Changed on disk since it was opened: refused, the file reloaded, then it works.
string cpath = AddFile("refuse-changed.utl", original);
var c = new LootEditSession();
c.Open(cpath);
string changed = EditFixture.Replace("Keep Coins", "Keep Coins!");
File.WriteAllText(cpath, changed);
Check(!c.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "file changed on disk: refused");
Check(c.Message.Contains("changed on disk"), $"says so ({c.Message})");
Eq(File.ReadAllText(cpath), changed, "the other writer's file untouched");
Check(!c.IsDirty && c.Profile?.Rules[0].Name == "Keep Coins!", "reloaded their version");
Check(c.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "then the add works");
Eq(VTankLootParser.Load(cpath).Rules[1].Name, "Keep Coins!", "on top of their change");
var none = new LootEditSession();
Check(!none.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "nothing open: refused");
var fresh = new LootEditSession();
fresh.Open(Path.Combine(_addDir, "not-there.utl"));
Check(!fresh.InsertAndSave(BuildOk(Pea()).Rule, null, 0), "a profile that doesn't exist yet: refused");
Check(!File.Exists(Path.Combine(_addDir, "not-there.utl")), "and not created");
}
private static void TestAddUtlV0()
{
Console.WriteLine("\n-- LootAdd: v0 (headerless) .utl --");
string v0 = string.Join("\n", new[] { "1", "Keep Coins", "3;1;7", "7" }) + "\n";
string path = AddFile("v0.utl", Encoding.UTF8.GetBytes(v0));
var s = new LootEditSession();
Check(s.Open(path) && !s.IsReadOnly, "v0 opens editable");
VTankLootRule rule = BuildOk(Opal()).Rule;
Check(s.InsertAndSave(rule, null, -1), $"append: {s.Message}");
string after = File.ReadAllText(path);
CheckSplicedUtl(v0, after, RuleLineCount(rule, 0), "v0");
Check(!after.Contains("\n\n"), "no custom-expression line in a v0 file");
Eq(VTankLootParser.Load(path).Rules.Count, 2, "2 rules");
Check(new LootEditSession() is var r && r.Open(path) && !r.IsReadOnly, "reopens editable");
}
// ── .json ────────────────────────────────────────────────────────────
private static LootProfile JsonFixture()
{
var p = new LootProfile { Name = "native" };
var gems = new LootRule { Name = "Keep gems", Action = LootAction.Keep };
gems.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
var off = new LootRule { Name = "Off", Enabled = false, Action = LootAction.Sell };
off.Conditions.Add(new LongValKeyGECondition { Key = 19, Value = 5000 });
var peas = new LootRule { Name = "Peas", Action = LootAction.KeepUpTo, KeepCount = 0 };
peas.Conditions.Add(new StringValueCondition { Key = 1, Pattern = "Pea$" });
peas.Conditions.Add(new CharacterSkillGECondition { Skill = AcSkillType.Salvaging, Value = 100 });
p.Rules.AddRange(new[] { gems, off, peas });
p.SalvageCombine = new SalvageCombineSettings { Enabled = true, DefaultBands = "1-6, 7-10" };
return p;
}
private static void TestAddJsonInsert(bool crlf)
{
string label = crlf ? "json CRLF" : "json LF";
Console.WriteLine($"\n-- LootAdd: insert into a native .json ({label}) --");
string json = System.Text.Json.JsonSerializer.Serialize(JsonFixture(), LootJsonContext.Default.LootProfile).Replace("\r\n", "\n");
// A property this build doesn't know: the splice keeps it (LootProfile.Save would drop it).
json = json.Replace("\"Name\": \"native\",", "\"Name\": \"native\",\n \"FutureField\": { \"a\": [1, 2] },");
if (crlf) json = json.Replace("\n", "\r\n");
byte[] original = Encoding.UTF8.GetBytes(json);
string path = AddFile(crlf ? "add-crlf.json" : "add.json", original);
var s = new LootEditSession();
Check(s.Open(path) && s.IsReadOnly && s.CanInsert, $"{label}: opens (read-only for edits) and takes an insert");
Eq(s.Format, "json", $"{label}: format");
var dropped = new List<string>();
LootRule native = LootItemRules.ToNative(BuildOk(Pea()).Rule, dropped)!;
Check(s.InsertAndSave(BuildOk(Pea()).Rule, native, 1), $"{label}: inserted at 2: {s.Message}");
Eq(s.RuleCount, 4, $"{label}: session shows 4 rules");
Eq(s.JsonProfile?.Rules[1].Name, "Keep 100 Copper Pea", $"{label}: session's copy has it");
byte[] saved = File.ReadAllBytes(path);
string after = Encoding.UTF8.GetString(saved);
Check(File.ReadAllBytes(path + ".bak").AsSpan().SequenceEqual(original), $"{label}: .bak == original");
Check(after.Contains("\"FutureField\": { \"a\": [1, 2] }"), $"{label}: unknown property kept");
Check(after.Contains("\r\n") == crlf && (crlf || !after.Contains('\r')), $"{label}: line endings kept");
// Byte-level: a common prefix and suffix, the middle is the new rule only.
int pre = 0;
while (pre < json.Length && json[pre] == after[pre]) pre++;
int suf = 0;
while (suf < json.Length - pre && json[json.Length - 1 - suf] == after[after.Length - 1 - suf]) suf++;
Eq(pre + suf, json.Length, $"{label}: the original is all there, in order");
string added = after.Substring(pre, after.Length - json.Length);
Check(added.Contains("Copper Pea") && !added.Contains("Keep gems") && !added.Contains("\"Peas\""), $"{label}: only the new rule was added");
LootProfile back = LootProfile.Load(path);
Eq(back.Rules.Count, 4, $"{label}: loads with 4 rules (RynthAi's loader, the external editor's)");
Eq(back.Rules[1].Name, "Keep 100 Copper Pea", $"{label}: at 2");
Eq(back.Rules[1].Action, LootAction.KeepUpTo, $"{label}: action");
Eq(back.Rules[1].KeepCount, 100, $"{label}: count");
Eq(string.Join(" ; ", back.Rules[1].Conditions), "ObjectClass == Misc ; StringKey[1] matches \"^Copper Pea$\"", $"{label}: conditions");
LootProfile orig = JsonFixture();
Eq(back.Rules[0].Name, "Keep gems", $"{label}: rule 1 kept");
Check(!back.Rules[2].Enabled && back.Rules[2].Action == LootAction.Sell && back.Rules[2].Conditions[0].ToString() == orig.Rules[1].Conditions[0].ToString(),
$"{label}: disabled rule kept as it was");
Eq(back.Rules[3].KeepCount, 1, $"{label}: (KeepCount 0 reads back as 1 in the native loader, before and after alike)");
Eq(LootProfile.Load(path + ".bak").Rules[2].KeepCount, back.Rules[3].KeepCount, $"{label}: same as the original reads");
Eq(string.Join(" ; ", back.Rules[3].Conditions), string.Join(" ; ", orig.Rules[2].Conditions), $"{label}: rule 3's conditions kept");
Eq(back.SalvageCombine?.DefaultBands, "1-6, 7-10", $"{label}: salvage combine kept");
// The end, then the top.
Check(s.InsertAndSave(BuildOk(Opal()).Rule, LootItemRules.ToNative(BuildOk(Opal()).Rule, dropped), -1), $"{label}: append");
Eq(LootProfile.Load(path).Rules[^1].Name, "Keep Black Opal", $"{label}: last");
Check(s.InsertAndSave(BuildOk(Opal()).Rule, LootItemRules.ToNative(BuildOk(Opal(), new() { RuleName = "Top" }).Rule, dropped), 0), $"{label}: top");
Eq(LootProfile.Load(path).Rules[0].Name, "Top", $"{label}: first");
Eq(LootProfile.Load(path).Rules.Count, 6, $"{label}: 6 rules");
Check(new LootEditSession() is var r && r.Open(path) && r.RuleCount == 6, $"{label}: the in-game editor opens it");
}
private static void TestAddJsonEdgeCases()
{
Console.WriteLine("\n-- LootAdd: native .json edge cases --");
LootRule native = LootItemRules.ToNative(BuildOk(Opal()).Rule, new List<string>())!;
string empty = "{\n \"Name\": \"e\",\n \"Rules\": []\n}";
string epath = AddFile("empty.json", Encoding.UTF8.GetBytes(empty));
var e = new LootEditSession();
e.Open(epath);
Check(e.InsertAndSave(BuildOk(Opal()).Rule, native, 0), $"empty Rules list: {e.Message}");
Eq(LootProfile.Load(epath).Rules.Count, 1, "one rule");
Check(File.ReadAllText(epath).StartsWith("{\n \"Name\": \"e\",\n \"Rules\": [\n {"), "indented like the writer");
byte[] bom = new byte[] { 0xEF, 0xBB, 0xBF }.Concat(Encoding.UTF8.GetBytes("{\"Rules\":[{\"Name\":\"a\",\"Enabled\":true}]}")).ToArray();
string bpath = AddFile("bom.json", bom);
var b = new LootEditSession();
b.Open(bpath);
Check(b.InsertAndSave(BuildOk(Opal()).Rule, native, 0), $"BOM, one line: {b.Message}");
byte[] bsaved = File.ReadAllBytes(bpath);
Check(bsaved[0] == 0xEF && bsaved[1] == 0xBB && bsaved[2] == 0xBF, "BOM kept");
Eq(LootProfile.Load(bpath).Rules[1].Name, "a", "old rule now second");
foreach (var (name, text) in new[]
{
("norules.json", "{\"Name\":\"x\"}"),
("twice.json", "{\"Rules\":[],\"Rules\":[]}"),
("notlist.json", "{\"Rules\":{}}"),
})
{
string path = AddFile(name, Encoding.UTF8.GetBytes(text));
var s = new LootEditSession();
if (!s.Open(path)) { Check(true, $"{name}: doesn't even open"); Eq(File.ReadAllText(path), text, $"{name}: untouched"); continue; }
Check(!s.InsertAndSave(BuildOk(Opal()).Rule, native, 0), $"{name}: refused ({s.Message})");
Eq(File.ReadAllText(path), text, $"{name}: untouched");
}
// Changed on disk: refused and reloaded, then fine.
string json = "{\"Rules\":[{\"Name\":\"a\",\"Enabled\":true}]}";
string cpath = AddFile("changed.json", Encoding.UTF8.GetBytes(json));
var c = new LootEditSession();
c.Open(cpath);
string theirs = "{\"Rules\":[{\"Name\":\"b\",\"Enabled\":true}]}";
File.WriteAllText(cpath, theirs);
Check(!c.InsertAndSave(BuildOk(Opal()).Rule, native, 0), "changed on disk: refused");
Eq(File.ReadAllText(cpath), theirs, "theirs untouched");
Check(c.InsertAndSave(BuildOk(Opal()).Rule, native, -1), "then fine");
Eq(LootProfile.Load(cpath).Rules[0].Name, "b", "on top of theirs");
Check(!c.InsertAndSave(BuildOk(Opal()).Rule, null, 0), "no native form: refused");
}
/// <summary>Bonus: every deployed loot profile, as a temp copy (the originals are only read).</summary>
private static void TestAddDeployedCopies(string[] args)
{
const string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
if (!Directory.Exists(folder)) return;
var files = Directory.GetFiles(folder, "*.utl").Concat(Directory.GetFiles(folder, "*.json")).ToList();
if (files.Count == 0) return;
Console.WriteLine($"\n-- LootAdd: deployed profiles, temp copies (bonus, {files.Count}) --");
foreach (string src in files)
{
byte[] original = File.ReadAllBytes(src);
string copy = AddFile("deployed-" + Path.GetFileName(src), original);
var s = new LootEditSession();
if (!s.Open(copy)) { Console.WriteLine($" [skip] {Path.GetFileName(src)}: {s.Message}"); continue; }
if (!s.CanInsert)
{
Check(!s.InsertAndSave(BuildOk(Pea()).Rule, null, 0), $"{Path.GetFileName(src)}: read-only, refused");
Check(File.ReadAllBytes(copy).AsSpan().SequenceEqual(original), $"{Path.GetFileName(src)}: untouched");
continue;
}
int count = s.RuleCount;
VTankLootRule rule = BuildOk(Pea()).Rule;
LootRule? native = LootItemRules.ToNative(rule, new List<string>());
int at = count / 2;
Check(s.InsertAndSave(rule, native, at), $"{Path.GetFileName(src)}: insert at {at + 1}: {s.Message}");
var again = new LootEditSession();
Check(again.Open(copy) && again.RuleCount == count + 1, $"{Path.GetFileName(src)}: reopens with {count + 1} rules");
if (s.Format == "utl")
{
Check(!again.IsReadOnly, $"{Path.GetFileName(src)}: still editable");
CheckSplicedUtl(LootEditSession_Decode(original), LootEditSession_Decode(File.ReadAllBytes(copy)), RuleLineCount(rule, s.Profile!.FileVersion),
Path.GetFileName(src));
}
Check(File.ReadAllBytes(src).AsSpan().SequenceEqual(original), $"{Path.GetFileName(src)}: the deployed original is untouched");
}
}
private static string LootEditSession_Decode(byte[] bytes)
{
try { return new UTF8Encoding(false, true).GetString(bytes).TrimStart('\uFEFF'); }
catch (DecoderFallbackException) { return Encoding.Latin1.GetString(bytes); }
}
}

View file

@ -43,6 +43,7 @@ internal static partial class Program
TestVTankFixtureParse();
TestMalformedInputs();
RunLootEditTests(args);
RunLootAddTests(args);
Console.WriteLine($"\nGolden tests: {_asserts} assertions, {_fails} failed.");

View file

@ -0,0 +1,295 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
namespace RynthCore.PatrolProof;
// "clear" mode: how far each point the dungeon pathfinder lays is from the nearest wall or
// edge of the walkable floor (DungeonGeometry.Clearance), by the rule that laid it
// (DungeonPathfinder.KindLog), for the patrol from a dozen start cells and for dunnav /
// recovery paths between 40 random cell pairs, in each landblock given. Also the route
// totals (points, doorway points, lap length, turns), to compare runs before and after a
// change, and each leg's least clearance along it (sampled every 0.25 m).
//
// Run: dotnet run -c Release -- clear [landblock hex ...] [worst N] [human] [csv <file>]
internal static class Clearance
{
private static readonly string[] Buckets = { "<0.25", "<0.50", "<0.75", "<1.00", "<1.50", ">=1.5" };
private static readonly double[] Edges = { 0.25, 0.5, 0.75, 1.0, 1.5 };
public static int Run(string[] args)
{
string acDir = @"C:\Turbine\Asheron's Call";
var lbs = new List<uint>();
int worst = 0;
string csv = null;
bool human = false;
var probes = new List<(double X, double Y, double Z)>();
var legProbes = new List<double[]>();
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
if (a == "worst" && i + 1 < args.Length) worst = int.Parse(args[++i]);
else if (a == "csv" && i + 1 < args.Length) csv = args[++i];
else if (a == "human") human = true;
else if (a == "leg" && i + 6 < args.Length)
{
var v = Enumerable.Range(1, 6).Select(k => double.Parse(args[i + k], CultureInfo.InvariantCulture)).ToArray();
legProbes.Add(v);
i += 6;
}
else if (a == "probe" && i + 3 < args.Length)
{
probes.Add((double.Parse(args[i + 1], CultureInfo.InvariantCulture), double.Parse(args[i + 2], CultureInfo.InvariantCulture), double.Parse(args[i + 3], CultureInfo.InvariantCulture)));
i += 3;
}
else if (a.Length <= 6 && uint.TryParse(a.Replace("0x", ""), NumberStyles.HexNumber, null, out uint v)) lbs.Add(v);
else acDir = a;
}
if (lbs.Count == 0) lbs.AddRange(new uint[] { 0x6346, 0x6544, 0x0174 });
var loader = new GeometryLoader();
if (!loader.Initialize(acDir)) { Console.WriteLine("Geometry loader failed: " + loader.StatusMessage); return 1; }
if (human)
{
var s = new SetupInfo();
byte[] data = loader.PortalDat.GetFileData(0x02000001);
if (data != null && s.Unpack(data))
Console.WriteLine($"Human setup 0x02000001: radius {s.Radius:F3} height {s.Height:F3}, cylinders [{string.Join(", ", s.Cylinders.Select(c => $"r={c.Radius:F3} h={c.Height:F3}"))}], spheres [{string.Join(", ", s.Spheres.Select(c => $"r={c.Radius:F3} z={c.Center.Z:F2}"))}]");
else Console.WriteLine("Human setup: could not read");
}
StreamWriter csvOut = csv != null ? new StreamWriter(csv) : null;
csvOut?.WriteLine("lb,set,kind,x,y,z,clearance");
var pathfinderType = typeof(DungeonPathfinder);
foreach (uint lb in lbs)
{
DungeonPathfinder.InvalidateCache();
var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
if (graph.Count == 0) { Console.WriteLine($"0x{lb:X4}: no cells"); continue; }
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
var floors = loader.DungeonLOS.GetDungeonMapFloorPolygons(lb);
Console.WriteLine();
Console.WriteLine($"=== 0x{lb:X4}: {graph.Count} cells, {geo.DoorwayCount} openings, floors for {geo.FloorCellCount} cells");
foreach (var v in legProbes)
{
double least = geo.LegClearance(v[0], v[1], v[2], v[3], v[4], v[5], 1.0, 0.5, out double wx, out double wy, out double wz);
double cx = wx, cy = wy;
double cc = geo.PushClear(ref cx, ref cy, wz, 1.0, 2.5);
double la = geo.LegClearance(v[0], v[1], v[2], cx, cy, wz, 1.0, 0.5, out _, out _, out _);
double lb2 = geo.LegClearance(cx, cy, wz, v[3], v[4], v[5], 1.0, 0.5, out _, out _, out _);
Console.WriteLine($" leg ({v[0]},{v[1]},{v[2]})->({v[3]},{v[4]},{v[5]}): least {least:F2} at ({wx:F2},{wy:F2},{wz:F2}); corner pushed to ({cx:F2},{cy:F2}) clearance {cc:F2}; new legs {la:F2} / {lb2:F2}");
foreach (var d in geo.DoorwaysNear(wx, wy, wz, 4.0))
Console.WriteLine($" opening {d.CellA:X8}-{d.CellB:X8} ({d.X:F2},{d.Y:F2},{d.Z:F2}) w={d.Width:F2} clearance {geo.Clearance(d.X, d.Y, d.Z, 1.5):F2}; legs {geo.LegClearance(v[0], v[1], v[2], d.X, d.Y, d.Z, 1.0, 0.5, out _, out _, out _):F2} / {geo.LegClearance(d.X, d.Y, d.Z, v[3], v[4], v[5], 1.0, 0.5, out _, out _, out _):F2}");
var two = new List<NavPoint> { NP(v[0], v[1], v[2]), NP(v[3], v[4], v[5]) };
DungeonPathfinder.KeepLegsOffWalls(geo, two, false);
Console.WriteLine(" plugin's leg pass: " + string.Join(" -> ", two.Select(p => $"({X(p):F2},{Y(p):F2})")));
}
if (legProbes.Count > 0 && probes.Count == 0) continue;
if (probes.Count > 0)
{
foreach (var (px, py, pz) in probes)
{
var runs = geo.ProbeRuns(px, py, pz, 4.0);
Console.WriteLine($" probe ({px}, {py}, {pz}): clearance {geo.Clearance(px, py, pz, 4.0):F2}, on walkable floor {geo.OnWalkableFloor(px, py, pz)}; runs E,ENE,..: {string.Join(" ", runs.Select(r => r.ToString("F2")))}");
foreach (var w in geo.WallsNear(px, py, 1.0).OrderBy(w => w.Dist))
Console.WriteLine($" wall ({w.X0:F2},{w.Y0:F2})-({w.X1:F2},{w.Y1:F2}) z {w.ZMin:F2}..{w.ZMax:F2} at {w.Dist:F2}");
foreach (var f in floors.Where(f => f.Vertices.Any(v => Math.Abs(v.X - px) < 2 && Math.Abs(v.Y - py) < 2)))
Console.WriteLine($" floor {f.CellId:X8} up={DungeonGeometry.IsUpwardFloor(f.Vertices)}: " + string.Join(" ", f.Vertices.Select(v => $"({v.X:F2},{v.Y:F2},{v.Z:F2})")));
}
continue;
}
// Patrol from a dozen start cells.
var kinds = new Dictionary<NavPoint, string>(ReferenceEqualityComparer.Instance);
DungeonPathfinder.KindLog = kinds;
var starts = graph.Keys.OrderBy(k => k).Where((k, i) => i % Math.Max(1, graph.Count / 12) == 0).ToList();
var patrolSamples = new List<(string Kind, NavPoint P, double C)>();
var patrolLegs = new List<double>();
var worstLegs = new List<(NavPoint A, NavPoint B, double C, double Wx, double Wy)>();
int pts = 0, door = 0, t60 = 0, t120 = 0, off = 0; double len = 0, buildMs = 0;
foreach (uint s in starts)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var r = DungeonPathfinder.BuildPatrolRoute(graph, s, null, geo);
buildMs += sw.Elapsed.TotalMilliseconds;
int n = r.Points.Count;
pts += n; door += r.Points.Count(p => p.Doorway);
for (int i = 0; i < n; i++)
{
var a = r.Points[i]; var b = r.Points[(i + 1) % n];
len += Yd(a, b);
if (n > 2)
{
double turn = TurnDeg(a, b, r.Points[(i + 2) % n]);
if (turn > 60) t60++;
if (turn > 120) t120++;
}
if (!LegOnFloor(a, b, floors)) off++;
double lc = LegClearance(geo, a, b, out double wx, out double wy);
patrolLegs.Add(lc);
worstLegs.Add((a, b, lc, wx, wy));
patrolSamples.Add((kinds.TryGetValue(a, out var k) ? k : "other", a, PointClearance(geo, a)));
}
}
Console.WriteLine($" patrol, {starts.Count} starts: {pts} points ({door} doorway), {len:F0} yd, turns >60 {t60}, >120 {t120}, off-floor legs {off}; built in {buildMs / starts.Count:F0} ms each");
Table("patrol", patrolSamples, patrolLegs);
// Dunnav / recovery paths.
kinds.Clear();
var rnd = new Random(6346);
var ids = graph.Keys.OrderBy(k => k).ToList();
var pathSamples = new List<(string Kind, NavPoint P, double C)>();
var pathLegs = new List<double>();
int pairs = 0, ppts = 0, pdoor = 0, pt60 = 0, poff = 0; double plen = 0;
for (int k = 0; k < 40; k++)
{
uint a = ids[rnd.Next(ids.Count)], b = ids[rnd.Next(ids.Count)];
var path = DungeonPathfinder.FindPath(a, b, graph);
if (path.Count < 3) continue;
pairs++;
var na = graph[a]; var nb = graph[b];
var r = DungeonPathfinder.BuildNavRoute(path, graph, nb.NS, nb.EW, geo, null, na.NS, na.EW, na.Z, nb.Z);
r.Points.Insert(0, new NavPoint { NS = na.NS, EW = na.EW, Z = na.Z / 240.0 });
ppts += r.Points.Count; pdoor += r.Points.Count(p => p.Doorway);
for (int i = 0; i + 1 < r.Points.Count; i++)
{
plen += Yd(r.Points[i], r.Points[i + 1]);
if (i + 2 < r.Points.Count && TurnDeg(r.Points[i], r.Points[i + 1], r.Points[i + 2]) > 60) pt60++;
if (!LegOnFloor(r.Points[i], r.Points[i + 1], floors)) poff++;
// Legs from the start cell centre and into the destination aren't the pathfinder's.
if (i > 0 && i + 2 < r.Points.Count) pathLegs.Add(LegClearance(geo, r.Points[i], r.Points[i + 1], out _, out _));
}
for (int i = 1; i + 1 < r.Points.Count; i++)
pathSamples.Add((kinds.TryGetValue(r.Points[i], out var kk) ? kk : "other", r.Points[i], PointClearance(geo, r.Points[i])));
}
DungeonPathfinder.KindLog = null;
Console.WriteLine($" dunnav/recovery, {pairs} paths: {ppts} points ({pdoor} doorway), {plen:F0} yd, turns >60 {pt60}, off-floor legs {poff}");
Table("paths", pathSamples, pathLegs);
if (worst > 0)
{
Console.WriteLine($" worst {worst} patrol points:");
foreach (var w in patrolSamples.OrderBy(s => s.C).Take(worst))
Console.WriteLine($" {w.Kind,-16} ({X(w.P):F2}, {Y(w.P):F2}, {w.P.Z * 240:F2}) clearance {w.C:F2}");
Console.WriteLine($" worst {worst} path points:");
foreach (var w in pathSamples.OrderBy(s => s.C).Take(worst))
Console.WriteLine($" {w.Kind,-16} ({X(w.P):F2}, {Y(w.P):F2}, {w.P.Z * 240:F2}) clearance {w.C:F2}");
Console.WriteLine($" worst {worst} patrol legs:");
foreach (var w in worstLegs.OrderBy(s => s.C).Take(worst))
Console.WriteLine($" ({X(w.A):F2}, {Y(w.A):F2}, {w.A.Z * 240:F2}) -> ({X(w.B):F2}, {Y(w.B):F2}, {w.B.Z * 240:F2}) least {w.C:F2} at ({w.Wx:F2}, {w.Wy:F2})");
}
if (csvOut != null)
{
foreach (var s in patrolSamples) csvOut.WriteLine(Row(lb, "patrol", s));
foreach (var s in pathSamples) csvOut.WriteLine(Row(lb, "paths", s));
}
}
csvOut?.Dispose();
return 0;
}
private static string Row(uint lb, string set, (string Kind, NavPoint P, double C) s)
=> string.Join(",", $"0x{lb:X4}", set, s.Kind,
X(s.P).ToString("F2", CultureInfo.InvariantCulture), Y(s.P).ToString("F2", CultureInfo.InvariantCulture),
(s.P.Z * 240).ToString("F2", CultureInfo.InvariantCulture), s.C.ToString("F3", CultureInfo.InvariantCulture));
private static void Table(string set, List<(string Kind, NavPoint P, double C)> samples, List<double> legs)
{
Console.WriteLine($" {"kind",-18} {"n",5} {"min",5} " + string.Join(" ", Buckets.Select(b => $"{b,6}")));
foreach (var g in samples.GroupBy(s => s.Kind).OrderBy(g => g.Key))
Line(g.Key, g.Select(s => s.C).ToList());
Line("ALL POINTS", samples.Select(s => s.C).ToList());
Line("legs (least)", legs);
}
private static void Line(string name, List<double> cs)
{
var counts = new int[Buckets.Length];
foreach (double c in cs)
{
int b = 0;
while (b < Edges.Length && c >= Edges[b]) b++;
counts[b]++;
}
double min = cs.Count > 0 ? cs.Min() : 0;
Console.WriteLine($" {name,-18} {cs.Count,5} {min,5:F2} " + string.Join(" ", counts.Select(c => $"{c,6}")));
}
private static double PointClearance(DungeonGeometry geo, NavPoint p) => geo.Clearance(X(p), Y(p), p.Z * 240.0, 3.0);
// The least clearance along a leg, sampled every 0.25 m, leaving out 0.5 m at each end (the
// end points are measured as points; within 0.5 m of a point with 1 m clearance a leg has at
// least 0.5 m, so a lower reading there is the sampler taking a stacked floor's height).
private static double LegClearance(DungeonGeometry geo, NavPoint a, NavPoint b, out double wx, out double wy)
{
wx = X(a); wy = Y(a);
double ax = X(a), ay = Y(a), bx = X(b), by = Y(b), az = a.Z * 240, bz = b.Z * 240;
double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
if (len <= 1.0) return 3.0;
int steps = Math.Max(1, (int)Math.Ceiling(len / 0.25));
double best = 3.0;
double zf = az; // follows the floor (ramps aren't straight between the end points)
for (int i = 0; i <= steps; i++)
{
double t = (double)i / steps;
if (t * len < 0.5 - 1e-9 || t * len > len - 0.5 + 1e-9)
{
// still follow the floor's height through the skipped ends
double sx0 = ax + (bx - ax) * t, sy0 = ay + (by - ay) * t;
if (geo.TryFloorHeight(sx0, sy0, zf, 0.6, out double h0)) zf = h0;
continue;
}
double x = ax + (bx - ax) * t, y = ay + (by - ay) * t;
if (geo.TryFloorHeight(x, y, zf, 0.6, out double h)) zf = h;
else if (geo.TryFloorHeight(x, y, az + (bz - az) * t, 0.6, out h)) zf = h;
double c = geo.Clearance(x, y, zf, 3.0);
if (c < best) { best = c; wx = x; wy = y; }
}
return best;
}
private static NavPoint NP(double x, double y, double z) => new() { EW = DungeonGeometry.WorldToNav(x), NS = DungeonGeometry.WorldToNav(y), Z = z / 240.0 };
private static double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW);
private static double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS);
private static double Yd(NavPoint a, NavPoint b) => Math.Sqrt((a.NS - b.NS) * (a.NS - b.NS) + (a.EW - b.EW) * (a.EW - b.EW)) * 240.0;
private static double TurnDeg(NavPoint a, NavPoint b, NavPoint c)
{
double ux = b.EW - a.EW, uy = b.NS - a.NS, vx = c.EW - b.EW, vy = c.NS - b.NS;
double lu = Math.Sqrt(ux * ux + uy * uy), lv = Math.Sqrt(vx * vx + vy * vy);
if (lu < 1e-9 || lv < 1e-9) return 0;
double cos = Math.Clamp((ux * vx + uy * vy) / (lu * lv), -1, 1);
return Math.Acos(cos) * 180 / Math.PI;
}
// Same test as Program's: every half metre of the leg over some floor polygon near its height.
private static bool LegOnFloor(NavPoint a, NavPoint b, List<DungeonLOS.MapPolygon> floors)
{
double ax = X(a), ay = Y(a), bx = X(b), by = Y(b), za = a.Z * 240.0, zb = b.Z * 240.0;
double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
int steps = Math.Max(1, (int)(len / 0.5));
for (int i = 0; i <= steps; i++)
{
double t = (double)i / steps, x = ax + (bx - ax) * t, y = ay + (by - ay) * t, z = za + (zb - za) * t;
bool ok = false;
foreach (var f in floors)
{
if (!DungeonGeometry.InsidePolygon2D(f.Vertices, x, y)) continue;
double fz = f.Vertices.Average(v => v.Z);
if (z - fz >= -1.5 && z - fz <= 4.5) { ok = true; break; }
}
if (!ok) return false;
}
return true;
}
}

View file

@ -32,6 +32,7 @@ internal static class Program
{
private static int Main(string[] args)
{
if (args.Length > 0 && args[0] == "clear") return Clearance.Run(args.Skip(1).ToArray());
uint lb = 0x6346;
string acDir = @"C:\Turbine\Asheron's Call";
string dumpDir = null;

View file

@ -95,6 +95,13 @@ internal static unsafe class FakeHost
/// <summary>The engine's VTank signal (API v74 GetVTankState flags: 1 = watching, 2 = running);
/// -1 = not installed (an engine before v74). Opt-in: set before Create().</summary>
public static int VTankFlags = -1;
/// <summary>Opt-in (set before Create): the server gates combat paces casts on, GetUseDoneSeq
/// (answering <see cref="UseDoneSeq"/>) and GetCastBusyState (answering <see cref="CastBusy"/>).</summary>
public static bool ServerGates;
/// <summary>The count of server UseDone (0x01C7) events the fake reports.</summary>
public static int UseDoneSeq;
/// <summary>1 while a cast gesture animates (GetCastBusyState), else 0.</summary>
public static int CastBusy;
public static int VTankSeq;
public static int CombatModeValue = 1;
/// <summary>Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The
@ -119,6 +126,15 @@ internal static unsafe class FakeHost
/// <summary>Item id -> wielded location: GetObjectWielderInfo says the player wields it there.</summary>
public static readonly Dictionary<uint, uint> Wielded = new();
private static readonly List<uint> _panelItems = new();
/// <summary>Opt-in (set before Create): CloseContainer (API v76; the host then reports at
/// least v76) and GetGroundContainerId (answering <see cref="GroundContainer"/>).</summary>
public static bool CloseContainerCalls;
/// <summary>Every CloseContainer (container id), in order (opt-in with <see cref="CloseContainerCalls"/>).</summary>
public static readonly List<uint> Closes = new();
/// <summary>The container the client has open (GetGroundContainerId), 0 = none.</summary>
public static uint GroundContainer;
/// <summary>The item selected in the game (GetSelectedItemId); 0 = none.</summary>
public static uint SelectedItem;
// ANSI strings handed back to tested code stay alive for the whole run.
private static readonly Dictionary<string, IntPtr> _ansi = new();
@ -137,9 +153,12 @@ internal static unsafe class FakeHost
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; Turns = 0; Casts.Clear();
Uses.Clear(); IdRequests.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; CombatModeValue = 1;
VTankFlags = -1; VTankSeq = 0; LogCostMicros = 0;
ServerGates = false; UseDoneSeq = 0; CastBusy = 0;
WieldCalls = false; Wields.Clear();
SalvageCalls = false; ExternalMoves.Clear(); SalvageAdds.Clear(); SalvageExecutes.Clear();
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
SelectedItem = 0;
}
/// <summary>
@ -203,6 +222,7 @@ internal static unsafe class FakeHost
api.WieldItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&WieldItem;
}
api.GetObjectWcidFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectWcid;
api.GetSelectedItemIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetSelectedItemId;
api.ReadKnownSpellsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, int>)&ReadKnownSpells;
api.LogFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, void>)&Log;
api.WriteToChatFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int, int>)&WriteToChat;
@ -232,11 +252,22 @@ internal static unsafe class FakeHost
api.GetPlayerBaseVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, uint*, int>)&GetPlayerBaseVitals;
api.GetWorldNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetWorldName;
api.GetAccountNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetAccountName;
if (ServerGates)
{
api.GetUseDoneSeqFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetUseDoneSeq;
api.GetCastBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetCastBusyState;
}
if (VTankFlags >= 0)
{
api.Version = Math.Max(api.Version, 74u);
api.GetVTankStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, int>)&GetVTankState;
}
if (CloseContainerCalls)
{
api.Version = Math.Max(api.Version, 76u);
api.CloseContainerFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&CloseContainer;
api.GetGroundContainerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetGroundContainerId;
}
LastApi = api;
return new RynthCoreHost(api);
}
@ -290,6 +321,12 @@ internal static unsafe class FakeHost
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetUseDoneSeq() => UseDoneSeq;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCastBusyState() => CastBusy;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int WriteToChat(IntPtr text, int type) { Chat.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; }
@ -459,6 +496,9 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetPlayerId() => PlayerIdValue;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetSelectedItemId() => SelectedItem;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SetAutoRun(int on) { AutoRun = on != 0; AutoRunCalls.Add(AutoRun); return 1; }
@ -481,6 +521,12 @@ internal static unsafe class FakeHost
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int WieldItem(uint id, uint mask) { Wields.Add((id, mask)); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int CloseContainer(uint id) { Closes.Add(id); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetGroundContainerId() => GroundContainer;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int MoveItemExternal(uint id, uint target, int amount) { ExternalMoves.Add((id, target, amount)); return 1; }

View file

@ -55,6 +55,8 @@ internal static class Program
ArcWhenClearTests.Register(runner);
UseAtLoginTests.Register(runner);
LearnSpellsTests.Register(runner);
AttackLatencyTests.Register(runner);
LootAddItemTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Attack latency (2026-10-04, "it does a little thinking before it attacks"). Measured from the
// client logs: a caster waited for a busy count AC had already lowered inline at the server's
// UseDone (the busy hook never sees that decrement), up to the 5 s force-clear, after every cast
// and after corpse opens; a killed monster was locked again for one tick from the old scan list;
// and the first cast at a new target waited out the Attack Spell Delay left from the last target
// although the UseDone and gesture gates already hold it. Plus the [CombatLatency] log line.
internal static class AttackLatencyTests
{
private const uint Player = 0x50000E01;
private const uint Lb = 0xA9B40000;
public static void Register(Runner r)
{
r.Add("attack latency: a busy count the server finished (UseDone since it rose, no gesture) is a leftover", BusyLeftover);
r.Add("attack latency: without the engine's UseDone counter the busy count always holds", BusyWithoutServerGates);
r.Add("attack latency: the first cast at a new target skips the Attack Spell Delay only with the server gates", NewTargetInterval);
r.Add("attack latency: a killed monster isn't locked again from the old scan list", NoRelockOfTheDead);
r.Add("attack latency: [CombatLatency] charges each wait, one line per engagement, throttled", LatencyLine);
}
// ── Busy leftovers ────────────────────────────────────────────────────────
private static void BusyLeftover()
{
// The pure rule.
var g = new CombatBusyGate();
g.NoteCount(1, useDoneSeqNow: 5);
Check.False(g.IsStale(1, true, 5, false), "just rose, no UseDone since: real");
Check.True(g.IsStale(1, true, 6, false), "a UseDone since it rose: leftover");
Check.False(g.IsStale(1, true, 6, true), "a gesture still animating: real");
g.NoteCount(2, useDoneSeqNow: 6);
Check.False(g.IsStale(2, true, 6, false), "rose again after that UseDone (a new action): real");
g.NoteCount(1, useDoneSeqNow: 6);
Check.False(g.IsStale(1, true, 6, false), "a hooked decrement doesn't count as the server finishing");
Check.True(g.IsStale(1, true, 7, false), "the next UseDone: leftover");
g.NoteCount(0, useDoneSeqNow: 7);
Check.False(g.IsStale(0, true, 7, false), "zero is never busy");
g.NoteCount(1, useDoneSeqNow: 7);
Check.False(g.IsStale(1, true, 7, false), "a fresh rise from zero: real until its UseDone");
// Through CombatManager and the host.
FakeHost.Reset();
FakeHost.ServerGates = true;
FakeHost.UseDoneSeq = 40;
var c = MakeCombat(new LegacyUiSettings());
c.BusyCount = 1; // a cast went out: the hooked increment
Check.False(c.BusyIsLeftover(), "cast in flight (no UseDone yet): combat waits");
FakeHost.CastBusy = 1;
FakeHost.UseDoneSeq = 41; // the server finished it, AC lowered the field inline
Check.False(c.BusyIsLeftover(), "UseDone in, gesture still animating: combat waits");
FakeHost.CastBusy = 0;
Check.True(c.BusyIsLeftover(), "UseDone in, gesture over: the count is a leftover");
c.BusyCount = 0; // the shared mirror reset (RynthAiPlugin.OnCombatBusyStale)
Check.False(c.BusyIsLeftover(), "reset to 0: nothing to wait for");
c.BusyCount = 1; // a corpse open (UseObject) after that
Check.False(c.BusyIsLeftover(), "a new action after the last UseDone: combat waits");
}
private static void BusyWithoutServerGates()
{
var g = new CombatBusyGate();
g.NoteCount(1, 0);
Check.False(g.IsStale(1, hasUseDoneSeq: false, 0, false), "no UseDone counter: never a leftover");
FakeHost.Reset(); // ServerGates off: an engine without GetUseDoneSeq
var c = MakeCombat(new LegacyUiSettings());
c.BusyCount = 1;
Check.False(c.BusyIsLeftover(), "old engine: the busy count holds as before");
}
// ── Cast interval ─────────────────────────────────────────────────────────
private static void NewTargetInterval()
{
const int Magic = CombatMode.Magic, Melee = CombatMode.Melee, Missile = CombatMode.Missile;
Check.Eq(CombatManager.AttackIntervalMs(Melee, 1500, true, true), 1000.0, "melee: 1000 ms, new target or not");
Check.Eq(CombatManager.AttackIntervalMs(Missile, 1500, true, true), 1000.0, "missile: 1000 ms");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, true, false), 1500.0, "magic, same target: the setting");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 2500, true, false), 2500.0, "magic, same target: a slower setting is kept");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 0, true, false), 1500.0, "magic, setting 0 (old file): 1500");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, true, true), CombatManager.NewTargetCastFloorMs,
"magic, new target, server gates: the short floor (UseDone + gesture hold the cast)");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 1500, false, true), 1500.0,
"magic, new target, no server gates: the setting (it is the only pacing then)");
Check.Eq(CombatManager.AttackIntervalMs(Magic, 250, true, true), 250.0, "a setting under the floor stays as set");
}
// ── No re-lock of a killed monster ────────────────────────────────────────
private static void NoRelockOfTheDead()
{
FakeHost.Reset();
Place(Player, "Me", 96, 96, creature: false);
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
uint a = 0x80000301, b = 0x80000302;
Place(a, "Olthoi Swarm Nymph", 96, 97.5f); // 1.5 m north: the pick
Place(b, "Olthoi Swarm Gardener", 96, 98.0f); // 2.0 m north
var s = new LegacyUiSettings { MonsterRange = 20 };
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { a, b });
var c = new CombatManager(host, s, cache);
c.SetPlayerId(Player);
c.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
c.ScanNearbyTargets();
c.HandleCombatTrigger();
Check.Eq((uint)c.activeTargetId, a, "the closer Nymph is locked");
// The kill notice lands between ticks; the next tick picks again before the scan has
// run again (it runs at most every 50 ms), so the old list is all it has.
c.OnKillNotification("Olthoi Swarm Nymph's perforated corpse falls before you!");
Check.Eq(c.activeTargetId, 0, "the kill drops the Nymph");
Check.False(c.ScannedTargets.Any(t => (uint)t.Id == a), "and takes it out of the current scan list");
c.HandleCombatTrigger();
Check.Eq((uint)c.activeTargetId, b, "the next pick is the Gardener, not the dead Nymph again");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("[CombatTarget] lock") && l.Contains("0x80000301")), 1,
"the Nymph was locked once (before the kill), not again after it");
}
// ── [CombatLatency] ───────────────────────────────────────────────────────
private static void LatencyLine()
{
var t = new CombatLatencyTracker();
Check.False(t.Pending, "nothing pending before a lock");
t.OnLock(1, 1000, killAtMs: 900);
t.OnTick(1, 1033, CombatLatencyTracker.Wait.Stance);
t.OnTick(1, 1066, CombatLatencyTracker.Wait.Busy);
t.OnTick(1, 1100, CombatLatencyTracker.Wait.Interval);
Check.Eq(t.Waited(CombatLatencyTracker.Wait.Busy), 33.0, "busy charged with its tick");
string? line = t.OnAttack(1, 1133, "Melee", "Olthoi Swarm Nymph");
Check.True(line != null, "the first attack logs the engagement");
Check.Eq(line, "[CombatLatency] lock->attack 133 ms (stance 33, face 0, busy 33, cast 0, interval 34, other 33) Melee 'Olthoi Swarm Nymph', kill->attack 233 ms",
"the line: total, each wait, mode, target, time since the kill");
Check.False(t.Pending, "logged once: the next attack at it is not an engagement");
Check.True(t.OnAttack(1, 1200, "Melee", null) == null, "a second attack logs nothing");
t.OnLock(2, 1500);
Check.True(t.OnAttack(2, 1600, "Magic", "B") == null, "a second engagement within 1 s is counted, not logged");
t.OnLock(3, 2600);
string? third = t.OnAttack(3, 2700, "Magic", "C");
Check.True((third ?? "").Contains("lock->attack 100 ms"), "the next one logs");
Check.True((third ?? "").Contains("(+1 engagements not logged)"), "and says one wasn't");
Check.False((third ?? "").Contains("kill->attack"), "a lock that didn't follow a kill has no kill->attack");
t.OnLock(4, 5000);
t.OnTick(5, 5033, CombatLatencyTracker.Wait.Busy); // the target changed without a new lock
Check.False(t.Pending, "another target: the engagement is abandoned");
Check.True(t.OnAttack(4, 5100, "Melee", null) == null, "and logs nothing");
t.OnLock(6, 6000);
t.OnDrop();
Check.True(t.OnAttack(6, 6100, "Melee", null) == null, "dropped before attacking: nothing");
}
// ── Helpers ───────────────────────────────────────────────────────────────
private static CombatManager MakeCombat(LegacyUiSettings s)
{
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, Array.Empty<uint>());
var c = new CombatManager(host, s, cache);
c.SetPlayerId(Player);
return c;
}
private static void Place(uint id, string name, float x, float y, bool creature = true)
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
if (creature) FakeHost.ItemTypes[id] = 0x10;
}
}

View file

@ -0,0 +1,343 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using RynthCore.Loot;
using RynthCore.Loot.Editing;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// "Add to loot profile" from a clicked item (2026-10-04): /ra loot add on the
// selected item, and the Loot Editor bridge's item_preview / item_add (what the
// engine's popup sends), against temp copies of a .utl and a native .json
// profile. Checks the chat line, the file, the reload into the evaluator that
// loots, and that the clicked item is then decided by the new rule.
internal static class LootAddItemTests
{
private const uint Player = 0x50000E01;
private const uint Opal = 0x80271101, Taper = 0x80271102, Coin = 0x80271103;
private const uint ItemTypeGem = 0x800, ItemTypeComponent = 0x1000;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
public static void Register(Runner r)
{
r.Add("loot add: /ra loot add puts 'Keep Black Opal' before the rule that sold it, saves, reloads (.utl)", UtlAddBeforeBroaderRule);
r.Add("loot add: native .json profile, same command, the native evaluator keeps it", NativeAdd);
r.Add("loot add: nothing takes the item -> appended at the end", AppendWhenNothingMatches);
r.Add("loot add: options (sell name, Keep # N, like) and preview leaves the file alone", CommandOptions);
r.Add("loot add: refusals (nothing selected, the same rule twice, no profile)", Refusals);
r.Add("loot add: the popup's item_preview / item_add / item_close through the editor bridge", BridgePopupFlow);
r.Add("loot add: unsaved edits in the Loot Editor block the add (nothing saved behind them)", BridgeRefusesUnderEdits);
}
// ── World and plugin ──────────────────────────────────────────────────────
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new();
public readonly WorldObjectCache Cache;
public Bot()
{
FakeHost.Reset();
FakeHost.Names[Player] = "Tester";
FakeHost.Names[Opal] = "Black Opal";
FakeHost.ItemTypes[Opal] = ItemTypeGem;
FakeHost.Ints[(Opal, 131)] = 16; // MaterialType Black Opal
FakeHost.Ints[(Opal, 105)] = 6; // workmanship
FakeHost.Names[Taper] = "Prismatic Taper";
FakeHost.ItemTypes[Taper] = ItemTypeComponent;
FakeHost.Ints[(Taper, 11)] = 100; // MaxStackSize
FakeHost.Ints[(Taper, 12)] = 37; // StackCount
FakeHost.Names[Coin] = "Pyreal";
var host = FakeHost.Create(Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = FakeHost.MakeCache(host, Player, new[] { Player, Opal, Taper, Coin });
Set("_objectCache", Cache);
Set("_playerId", Player);
Set("_charSkills", new CharacterSkills(host));
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T? Get<T>(string f) => (T?)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P);
public void Ra(string line)
{
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
int eat = 0;
object[] args = { parts[1].ToLowerInvariant(), parts, eat };
typeof(RynthAiPlugin).GetMethod("DispatchRaCommand", Any)!.Invoke(P, args);
}
public string ChatText => string.Join("\n", FakeHost.Chat);
public WorldObject Item(uint id) => Cache[unchecked((int)id)]!;
}
private static string Utl(params string[] lines) => string.Join("\n", lines) + "\n";
// Rule 1 sells every gem, rule 2 keeps pyreals.
private static readonly string SellGems = Utl(
"UTL", "1", "2",
"Sell all gems", "", "0;3;7", "0", "11",
"Keep pyreals", "", "0;1;1", "0", "^Pyreal$", "1");
private static string Temp(string name, string text)
{
string path = Path.Combine(Program.TempRoot, "lootadd-" + Guid.NewGuid().ToString("N")[..8] + "-" + name);
File.WriteAllText(path, text);
return path;
}
// ── .utl ──────────────────────────────────────────────────────────────────
private static void UtlAddBeforeBroaderRule()
{
var bot = new Bot();
string path = Temp("sell-gems.utl", SellGems);
bot.S.CurrentLootPath = path;
object?[] load = { string.Empty, null, null };
Check.True((bool)typeof(RynthAiPlugin).GetMethod("TryLoadLootProfile", Any)!.Invoke(bot.P, load)!, "the profile in use loads");
Check.Eq(bot.Get<VTankLootProfile>("_loadedLootProfile")?.Rules.Count, 2, "profile in use: 2 rules");
var before = VTankLootEvaluator.FirstMatch(bot.Get<VTankLootProfile>("_loadedLootProfile")!, bot.Item(Opal), null, out _);
Check.Eq(before?.Action, VTankLootAction.Sell, "before: the gem rule sells it");
FakeHost.SelectedItem = Opal;
FakeHost.Chat.Clear();
bot.Ra("/ra loot add");
Check.True(FakeHost.Chat.Contains($"[RynthAi] Added loot rule 'Keep Black Opal' to {Path.GetFileName(path)}."),
"chat: [RynthAi] Added loot rule 'Keep Black Opal' to <profile>.\n" + bot.ChatText);
Check.True(bot.ChatText.Contains("just before rule 1 'Sell all gems'"), "chat says where and why");
VTankLootProfile onDisk = VTankLootParser.Load(path);
Check.Eq(onDisk.Rules.Count, 3, "3 rules on disk");
Check.Eq(onDisk.Rules[0].Name, "Keep Black Opal", "inserted first, before the broader gem rule");
Check.Eq(string.Join(" ; ", onDisk.Rules[0].Conditions.Select(c => c.NodeType + ":" + string.Join("|", c.DataLines))),
"7:11 ; 1:^Black Opal$|1", "exact name + class");
Check.Eq(onDisk.Rules[1].Name, "Sell all gems", "the old rules follow, unchanged");
Check.Eq(File.ReadAllText(path + ".bak"), SellGems, ".bak is the original");
VTankLootProfile? live = bot.Get<VTankLootProfile>("_loadedLootProfile");
Check.Eq(live?.Rules.Count, 3, "reloaded at once: the bot loots with 3 rules");
var after = VTankLootEvaluator.FirstMatch(live!, bot.Item(Opal), null, out int idx);
Check.Eq(after?.Name, "Keep Black Opal", "the clicked gem is now decided by the new rule");
Check.Eq(after?.Action, VTankLootAction.Keep, "Keep");
var coin = VTankLootEvaluator.FirstMatch(live!, bot.Item(Coin), null, out _);
Check.Eq(coin?.Name, "Keep pyreals", "other items: same rule as before");
FakeHost.Chat.Clear();
bot.Ra("/ra lootcheck");
Check.True(bot.ChatText.Contains("Black Opal: [Keep] Keep Black Opal"), "/ra lootcheck agrees\n" + bot.ChatText);
}
// ── .json ─────────────────────────────────────────────────────────────────
private static void NativeAdd()
{
var bot = new Bot();
var p = new LootProfile { Name = "native" };
var sell = new LootRule { Name = "Sell gems", Action = LootAction.Sell };
sell.Conditions.Add(new ObjectClassCondition { ObjectClass = AcObjectClass.Gem });
p.Rules.Add(sell);
string path = Path.Combine(Program.TempRoot, "lootadd-native-" + Guid.NewGuid().ToString("N")[..8] + ".json");
p.Save(path);
string original = File.ReadAllText(path);
bot.S.CurrentLootPath = path;
Check.True((bool)typeof(RynthAiPlugin).GetMethod("TryLoadNativeLootProfile", Any)!.Invoke(bot.P, new object?[] { null, null })!, "native profile loads");
FakeHost.SelectedItem = Opal;
FakeHost.Chat.Clear();
bot.Ra("/ra loot add");
Check.True(FakeHost.Chat.Contains($"[RynthAi] Added loot rule 'Keep Black Opal' to {Path.GetFileName(path)}."), "chat line\n" + bot.ChatText);
LootProfile disk = LootProfile.Load(path);
Check.Eq(disk.Rules.Count, 2, "2 rules on disk");
Check.Eq(disk.Rules[0].Name, "Keep Black Opal", "before the gem rule");
Check.Eq(File.ReadAllText(path + ".bak"), original, ".bak is the original");
LootProfile? live = bot.Get<LootProfile>("_nativeLootProfile");
Check.Eq(live?.Rules.Count, 2, "reloaded at once");
var (action, rule) = LootEvaluator.Classify(live!, bot.Item(Opal), null);
Check.Eq(rule?.Name, "Keep Black Opal", "the native evaluator picks the new rule");
Check.Eq(action, LootAction.Keep, "Keep");
}
private static void AppendWhenNothingMatches()
{
var bot = new Bot();
string path = Temp("coins-only.utl", Utl("UTL", "1", "1", "Keep pyreals", "", "0;1;1", "0", "^Pyreal$", "1"));
bot.S.CurrentLootPath = path;
FakeHost.SelectedItem = Opal;
bot.Ra("/ra loot add");
VTankLootProfile disk = VTankLootParser.Load(path);
Check.Eq(disk.Rules.Count, 2, "2 rules");
Check.Eq(disk.Rules[1].Name, "Keep Black Opal", "appended (nothing took the gem)");
Check.True(bot.ChatText.Contains("at the end"), "chat says why\n" + bot.ChatText);
}
private static void CommandOptions()
{
var bot = new Bot();
string path = Temp("options.utl", SellGems);
bot.S.CurrentLootPath = path;
FakeHost.SelectedItem = Taper;
FakeHost.Chat.Clear();
bot.Ra("/ra loot add preview");
Check.Eq(File.ReadAllText(path), SellGems, "preview: file untouched");
Check.False(File.Exists(path + ".bak"), "preview: no save at all");
Check.True(bot.ChatText.Contains("Rule: Keep 100 Prismatic Taper") && bot.ChatText.Contains("Action: Keep # 100"),
"preview: a stack defaults to Keep # one full stack\n" + bot.ChatText);
bot.Ra("/ra loot add 25");
VTankLootProfile disk = VTankLootParser.Load(path);
VTankLootRule kept = disk.Rules.Last();
Check.Eq(kept.Name, "Keep 25 Prismatic Taper", "Keep # 25 by number");
Check.Eq(kept.Action, VTankLootAction.KeepUpTo, "Keep #");
Check.Eq(kept.KeepCount, (int?)25, "count 25");
FakeHost.SelectedItem = Opal;
bot.Ra("/ra loot add sell name");
disk = VTankLootParser.Load(path);
Check.Eq(disk.Rules[0].Name, "Sell Black Opal", "sell, name only (before the gem rule)");
Check.Eq(disk.Rules[0].Conditions.Count, 1, "one condition: the name");
bot.Ra("/ra loot add like");
disk = VTankLootParser.Load(path);
// The gem now hits "Sell Black Opal" first, so the like-rule goes before that.
Check.Eq(disk.Rules[0].Name, "Keep like Black Opal", "like this: before the rule that takes it now");
Check.Eq(string.Join(" ; ", disk.Rules[0].Conditions.Select(c => c.NodeType + ":" + string.Join("|", c.DataLines))),
"7:11 ; 12:16|131 ; 3:6|105", "class + material + workmanship >=");
Check.Eq(disk.Rules.Count, 5, "5 rules");
FakeHost.Chat.Clear();
bot.Ra("/ra loot add bogus");
Check.True(bot.ChatText.Contains("'bogus'?"), "an unknown word is refused");
Check.Eq(VTankLootParser.Load(path).Rules.Count, 5, "and adds nothing");
}
private static void Refusals()
{
var bot = new Bot();
string path = Temp("refuse.utl", SellGems);
bot.S.CurrentLootPath = path;
FakeHost.SelectedItem = 0;
bot.Ra("/ra loot add");
Check.True(bot.ChatText.Contains("Loot rule not added: No item selected"), "nothing selected\n" + bot.ChatText);
Check.Eq(File.ReadAllText(path), SellGems, "untouched");
FakeHost.SelectedItem = Opal;
bot.Ra("/ra loot add");
FakeHost.Chat.Clear();
bot.Ra("/ra loot add");
Check.True(bot.ChatText.Contains("Already there: rule 1 'Keep Black Opal'"), "the same rule twice is refused\n" + bot.ChatText);
Check.Eq(VTankLootParser.Load(path).Rules.Count, 3, "one copy only");
FakeHost.SelectedItem = 0x8027FFFF; // not in the cache
FakeHost.Chat.Clear();
bot.Ra("/ra loot add");
Check.True(bot.ChatText.Contains("doesn't know item"), "unknown item\n" + bot.ChatText);
bot.S.CurrentLootPath = string.Empty;
FakeHost.SelectedItem = Opal;
FakeHost.Chat.Clear();
bot.Ra("/ra loot add");
Check.True(bot.ChatText.Contains("No loot profile selected"), "no profile\n" + bot.ChatText);
bot.S.CurrentLootPath = path.Replace(".utl", "-missing.utl");
FakeHost.Chat.Clear();
bot.Ra("/ra loot add");
Check.True(bot.ChatText.Contains("not found"), "missing profile\n" + bot.ChatText);
Check.False(File.Exists(bot.S.CurrentLootPath), "and not created");
}
// ── The engine's popup, through the bridge ───────────────────────────────
private static LootEditState State(LootEditorBridge b) =>
JsonSerializer.Deserialize(b.StateJson(), LootEditJsonContext.Default.LootEditState)!;
private static void Send(LootEditorBridge b, LootEditCommand c) =>
b.Command(JsonSerializer.Serialize(c, LootEditJsonContext.Default.LootEditCommand));
private static void BridgePopupFlow()
{
var bot = new Bot();
string path = Temp("popup.utl", SellGems);
bot.S.CurrentLootPath = path;
LootEditorBridge b = bot.P.LootEditor;
Check.Eq(State(b).Rules.Count, 2, "editor shows the profile in use");
int rev0 = b.Revision();
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Taper, Seq = 7 } });
Check.True(b.Revision() != rev0, "a preview moves the revision (the engine refetches)");
LootEditState s = State(b);
Check.Eq(s.Revision, (long)b.Revision(), "the state's revision is the one Revision() reports");
LootEditItemDraft? d = s.ItemDraft;
Check.True(d != null && d.Ok, "draft: " + d?.Error);
Check.Eq(d?.Seq, 7, "echoes the popup's seq");
Check.Eq(d?.ItemName, "Prismatic Taper", "item");
Check.Eq(d?.ClassName, "SpellComponent", "class");
Check.True(d?.Stackable == true, "stackable");
Check.Eq(d?.Action, (int)VTankLootAction.KeepUpTo, "default Keep #");
Check.Eq(d?.KeepCount, 100, "one full stack");
Check.Eq(d?.RuleName, "Keep 100 Prismatic Taper", "name");
Check.Eq(d?.InsertAt, 2, "nothing takes it: the end");
Check.Eq(d?.Format, "utl", "format");
Check.True(d?.TargetInUse == true, "target is the profile in use");
Check.True(d?.Preview.Any(l => l.Contains("Class is SpellComponent")) == true, "preview lines");
Check.Eq(File.ReadAllText(path), SellGems, "preview saves nothing");
// The popup changes its mind: Keep 10, own name. Then Add.
Send(b, new LootEditCommand { Op = "item_add", Item = new LootEditItemRequest
{
ItemId = Taper, Seq = 8, Action = (int)VTankLootAction.KeepUpTo, KeepCount = 10, RuleName = "Tapers", Match = (int)LootItemMatch.Name,
} });
s = State(b);
Check.True(s.ItemDraft?.Added == true, "added: " + s.ItemDraft?.Error);
Check.Eq(s.ItemDraft?.Seq, 8, "seq");
Check.True(FakeHost.Chat.Contains($"[RynthAi] Added loot rule 'Tapers' to {Path.GetFileName(path)}."), "chat line\n" + bot.ChatText);
Check.Eq(s.Rules.Count, 3, "the editor's list has it (same session)");
Check.Eq(s.Focus, 2, "and focuses it");
Check.Eq(s.Rules[2].Name, "Tapers", "named as asked");
Check.False(s.Dirty, "saved");
VTankLootRule r = VTankLootParser.Load(path).Rules[2];
Check.True(r.Action == VTankLootAction.KeepUpTo && r.KeepCount == 10 && r.Conditions.Count == 1, "Keep # 10 by name only, on disk");
Check.Eq(bot.Get<VTankLootProfile>("_loadedLootProfile")?.Rules.Count, 3, "RynthAi reloaded it");
Send(b, new LootEditCommand { Op = "item_close" });
Check.True(State(b).ItemDraft == null, "closed: no draft in the state");
// ItemId 0 = the selected item.
FakeHost.SelectedItem = Opal;
Send(b, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { Seq = 9, ToOpenProfile = true } });
Check.Eq(State(b).ItemDraft?.ItemId, Opal, "0 = the selected item, resolved once");
Check.Eq(State(b).ItemDraft?.InsertAt, 0, "before the gem rule");
}
private static void BridgeRefusesUnderEdits()
{
var bot = new Bot();
string path = Temp("edits.utl", SellGems);
bot.S.CurrentLootPath = path;
LootEditorBridge b = bot.P.LootEditor;
_ = State(b);
Send(b, new LootEditCommand { Op = "rename", Index = 1, Value = "half-done", Expect = "Keep pyreals" });
Check.True(State(b).Dirty, "the editor has an unsaved edit");
Send(b, new LootEditCommand { Op = "item_add", Item = new LootEditItemRequest { ItemId = Opal, Seq = 1 } });
LootEditItemDraft? d = State(b).ItemDraft;
Check.True(d != null && !d.Added && d.Error.Contains("unsaved changes"), "refused: " + d?.Error);
Check.True(d != null && d.Preview.Count > 0, "the preview still shows");
Check.Eq(File.ReadAllText(path), SellGems, "nothing saved");
Check.Eq(State(b).Rules[1].Name, "half-done", "the edit is still there, unsaved");
}
}

View file

@ -46,6 +46,10 @@ internal static class LootCorpseTests
r.Add("loot chain: 'My Kills Only' loots your kill and skips another player's", OwnershipModes);
r.Add("loot starvation: a corpse waiting behind far-off combat gets a turn, a close monster keeps combat", LootStarvation);
r.Add("loot logging: a corpse held by combat is logged once, with the reason", HeldByCombatLoggedOnce);
r.Add("corpse close: a finished corpse is closed once (CloseContainer, API v76)", FinishedCorpseClosedOnce);
r.Add("corpse close: an engine without CloseContainer leaves it to the next open (no close)", FinishedCorpseNotClosedOnOldEngine);
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
r.Add("corpse close: stopping the macro mid-loot closes the open corpse, not marked completed", MacroStopClosesCorpse);
}
// ── World set-up ──────────────────────────────────────────────────────────
@ -330,4 +334,110 @@ internal static class LootCorpseTests
int lines = FakeHost.Logs.Count(l => l.Contains($"corpse 0x{Corpse:X8} waits for combat"));
Check.Eq(lines, 1, "one line for the held corpse, not one per tick");
}
// ── Closing the corpse when done (2026-10-04: "when finished looting I don't think the
// corpse closes"). API v76 CloseContainer sends the client's own close packet (0x0195). ──
/// <summary>Claims, opens and starts looting the corpse; the gem's move has been sent.
/// With <paramref name="closeSupported"/> the host has CloseContainer and GetGroundContainerId,
/// and the client reports the corpse open (as the engine does after ViewContents).</summary>
private static Bot OpenCorpseAndSendPickup(bool closeSupported)
{
BaseWorld(corpsePositioned: true);
FakeHost.CloseContainerCalls = closeSupported;
var host = FakeHost.Create(Player);
Check.Eq(host.HasCloseContainer, closeSupported, "the host's CloseContainer support");
var bot = new Bot(host);
bot.Cache.OnCreateObject(Corpse);
bot.Cache.Tick();
bot.Tick(BotActivity.Looting);
Check.True(FakeHost.Uses.Contains(Corpse), "the corpse is opened");
bot.Cache.OnCreateObject(Gem);
bot.Cache.Tick();
if (closeSupported)
FakeHost.GroundContainer = Corpse;
bot.P.OnViewObjectContents(Corpse);
for (int i = 0; i < 100 && !FakeHost.ExternalMoves.Any(m => m.Id == Gem); i++)
{
bot.Tick(BotActivity.Looting);
Thread.Sleep(10);
}
Check.True(FakeHost.ExternalMoves.Contains((Gem, Player, 0)), "the gem's move is sent");
Check.Eq(FakeHost.Closes.Count, 0, "nothing closed while an item is still being looted");
return bot;
}
private static bool Completed(Bot bot) =>
bot.Get<Dictionary<int, long>>("_completedCorpses").ContainsKey(unchecked((int)Corpse));
/// <summary>The gem lands in the pack; ticks until the corpse is marked completed.</summary>
private static void FinishLooting(Bot bot)
{
FakeHost.Containers[Gem] = Player;
for (int i = 0; i < 200 && !Completed(bot); i++)
{
bot.Tick(BotActivity.Looting);
Thread.Sleep(10);
}
Check.True(Completed(bot), "the corpse is completed once its last item is in the pack");
}
private static void FinishedCorpseClosedOnce()
{
var bot = OpenCorpseAndSendPickup(closeSupported: true);
FinishLooting(bot);
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "the finished corpse is closed, once");
Check.Eq(bot.Get<int>("_busyCount"), 0, "the close adds nothing to the busy count");
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the bot no longer holds it open");
// Until the server's answer lands the client still reports it open: no second close.
for (int i = 0; i < 5; i++) bot.Tick(BotActivity.Looting);
Check.Eq(FakeHost.Closes.Count, 1, "no re-close while the client still shows it");
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "a completed corpse is not re-claimed from the client's state");
// The server's CloseGroundContainer: the window goes, StopViewingObjectContents follows.
FakeHost.GroundContainer = 0;
bot.P.OnStopViewingObjectContents(Corpse);
for (int i = 0; i < 5; i++) bot.Tick(BotActivity.Looting);
Check.Eq(FakeHost.Closes.Count, 1, "still one close after the server's answer");
Check.Eq(FakeHost.Uses.Count(u => u == Corpse), 1, "never a UseObject to close it");
}
private static void FinishedCorpseNotClosedOnOldEngine()
{
var bot = OpenCorpseAndSendPickup(closeSupported: false);
FinishLooting(bot);
Check.Eq(FakeHost.Closes.Count, 0, "no CloseContainer on an engine before v76");
Check.Eq(FakeHost.Uses.Count(u => u == Corpse), 1, "and no UseObject to close it either");
}
private static void AbandonedCorpseClosed()
{
var bot = OpenCorpseAndSendPickup(closeSupported: true);
bot.Call("AbandonCurrentCorpse", Environment.TickCount64, "timeout");
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "the abandoned corpse is closed, once");
Check.True(Completed(bot), "an opened corpse that timed out is completed (as before)");
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "and released");
}
private static void MacroStopClosesCorpse()
{
var bot = OpenCorpseAndSendPickup(closeSupported: true);
bot.S.IsMacroRunning = false;
bot.Call("CloseOpenCorpseOnMacroStop");
Check.Eq(string.Join(",", FakeHost.Closes.Select(c => $"{c:X8}")), $"{Corpse:X8}", "the open corpse is closed when the macro stops");
Check.False(Completed(bot), "not completed: a later run can loot what is left");
// Macro off, ticking on: no further close before the server's answer.
for (int i = 0; i < 5; i++) bot.Tick(BotActivity.Idle);
Check.Eq(FakeHost.Closes.Count, 1, "one close");
FakeHost.GroundContainer = 0;
bot.P.OnStopViewingObjectContents(Corpse);
Check.Eq(bot.Get<int>("_openedContainerId"), 0, "the server's answer clears the open corpse");
// No open corpse: nothing to close.
bot.Call("CloseOpenCorpseOnMacroStop");
Check.Eq(FakeHost.Closes.Count, 1, "a stop with no corpse open closes nothing");
}
}

View file

@ -19,7 +19,11 @@ namespace RynthCore.RynthAiHostTests.Tests;
// crossing round the corner;
// - the patrol over such a dungeon puts no point inside the big room and still goes
// through every doorway; a big dead-end room is looked into;
// - ceilings are not floors.
// - ceilings are not floors;
// - every point keeps 1 m from walls and floor edges where the space allows (pushed off a
// wall, centred in a narrow corridor, a doorway point moved back along its centre line,
// a crypt bend, a dead end's look-in point out of its end cap), and a leg cutting an
// inside corner gets a corner.
internal static class PatrolDoorwayTests
{
public static void Register(Runner r)
@ -34,6 +38,13 @@ internal static class PatrolDoorwayTests
r.Add("dungeon patrol: a loop through a big room: no points inside it, every doorway taken", PatrolLoop);
r.Add("dungeon patrol: a big dead-end room is looked into, not skirted", PatrolLooksIntoDeadEndRoom);
r.Add("dungeon floors: a ceiling (facing down) is not a floor", CeilingIsNotFloor);
r.Add("dungeon clearance: walls, floor edges and slopes too steep to stand on bound it; a face high above doesn't", ClearanceMeasure);
r.Add("dungeon clearance: a point next to a wall (or past the floor's edge) is pushed out to 1 m", PushedOffWall);
r.Add("dungeon clearance: a point in a corridor narrower than 2 m ends on its middle line", NarrowCorridorCentred);
r.Add("dungeon doorways: a doorway point near the far wall of a T junction moves back along the centre line", DoorwayPointMovesAlongCentreLine);
r.Add("dungeon doorways: in a short chamfered bend (crypt corner) the points come off the bend's outer wall", ChamferedBend);
r.Add("dungeon patrol: a dead end's look-in point comes out of the end cap onto the floor", DeadEndLookInOnFloor);
r.Add("dungeon legs: a leg cutting an inside corner gets a corner put in", LegAroundInsideCorner);
}
// ── Fixture builder ──────────────────────────────────────────────────────
@ -77,6 +88,15 @@ internal static class PatrolDoorwayTests
public void Wall(uint cell, double x0, double y0, double x1, double y1) => Walls.Add((cell, VerticalQuad(x0, y0, x1, y1)));
/// <summary>A cell whose origin is (ox, oy) and whose floor is the given polygon (counter-clockwise from above).</summary>
public uint CellPoly(double ox, double oy, params (double X, double Y, double Z)[] floor)
{
uint id = _next++;
Graph[id] = new DungeonNavNode { CellId = id, EW = DungeonGeometry.WorldToNav(ox), NS = DungeonGeometry.WorldToNav(oy), Z = 0 };
Floors.Add((id, floor.Select(v => new V3((float)v.X, (float)v.Y, (float)v.Z)).ToArray()));
return id;
}
public DungeonGeometry Geo() => DungeonGeometry.Build(Graph, Portals, Floors, Walls);
}
@ -375,6 +395,161 @@ internal static class PatrolDoorwayTests
Check.True(geo.OnFloorOfAny(new[] { a }, 5, 5, 0), "so nothing is checked against it");
}
// ── Clearance from walls ─────────────────────────────────────────────────
private static double Clear(DungeonGeometry geo, NavPoint p) => geo.Clearance(X(p), Y(p), p.Z * 240.0, 3.0);
private static void ClearanceMeasure()
{
// A 10 x 10 room, a wall along its west side; a steep slope (2 m up over 1.6 m, about 51
// degrees) beyond its east side.
var d = new Dungeon();
uint room = d.Cell(0, 0, 10, 10);
d.Wall(room, 0, 0, 0, 10);
d.Floors.Add((room, new[] { new V3(10f, 0f, 0f), new V3(11.6f, 0f, 2f), new V3(11.6f, 10f, 2f), new V3(10f, 10f, 0f) }));
// A face across the room's north half that starts 2.5 m up (the face above an arch).
d.Walls.Add((room, new[] { new V3(0f, 8f, 2.5f), new V3(10f, 8f, 2.5f), new V3(10f, 8f, 4f), new V3(0f, 8f, 4f) }));
var geo = d.Geo();
Check.Near(geo.Clearance(0.4, 5, 0), 0.4, 0.06, "0.4 m from the west wall");
Check.Near(geo.Clearance(9.3, 5, 0), 0.7, 0.06, "the slope too steep to stand on bounds the floor (0.7 m to its foot)");
Check.Near(geo.Clearance(5, 5, 0), 3.0, 1e-6, "the middle: nothing within 3 m (the face 3 m north is 2.5 m up)");
Check.Near(geo.Clearance(5, 8.2, 0), 1.8, 0.06, "under the high face: the nearest bound is the room's north edge, 1.8 m away");
Check.Eq(geo.Clearance(-0.5, 5, 0), 0.0, "past the floor's edge: 0");
Check.Eq(geo.Clearance(10.8, 5, 1), 0.0, "on the steep slope: 0");
}
private static void PushedOffWall()
{
var d = new Dungeon();
uint room = d.Cell(0, 0, 10, 10);
d.Wall(room, 0, 0, 0, 10);
var geo = d.Geo();
double x = 0.3, y = 5;
double c = geo.PushClear(ref x, ref y, 0, 1.0, 2.0);
Check.True(c >= 0.98, $"pushed to 1 m clearance ({c:F2})");
Check.True(x >= 0.98 && x <= 1.2, $"straight out from the wall, not further than needed (x {x:F2})");
Check.Near(y, 5, 0.15, "along the wall's normal");
// Past the floor's edge (a dead end's cell origin inside its end cap): onto the floor first.
x = -0.5; y = 5;
c = geo.PushClear(ref x, ref y, 0, 1.0, 3.0);
Check.True(c >= 0.98 && x > 0, $"onto the floor with 1 m clearance ({x:F2}, {y:F2}: {c:F2})");
// In the open: left alone.
x = 5; y = 5;
geo.PushClear(ref x, ref y, 0, 1.0, 2.0);
Check.True(x == 5 && y == 5, "a point with room enough is not moved");
}
private static void NarrowCorridorCentred()
{
var d = new Dungeon();
uint corr = d.Cell(0, 0, 20, 1.6);
d.Wall(corr, 0, 0, 20, 0);
d.Wall(corr, 0, 1.6, 20, 1.6);
var geo = d.Geo();
double x = 10, y = 0.3;
double c = geo.PushClear(ref x, ref y, 0, 1.0, 2.0);
Check.Near(y, 0.8, 0.06, $"on the middle line of the 1.6 m corridor (y {y:F2})");
Check.Near(c, 0.8, 0.06, "as clear as the corridor allows");
Check.Near(x, 10, 0.5, "not moved along the corridor");
}
private static void DoorwayPointMovesAlongCentreLine()
{
// A room (x 0..10) opening east into a north-south corridor 4.6 m wide (x 10..14.6), like
// a hive corridor: the 4 m standoff would put the exit point 0.6 m from the far wall.
var d = new Dungeon();
uint room = d.Cell(0, 0, 10, 10);
uint corr = d.Cell(10, -10, 14.6, 20);
d.OpenX(room, corr, 10, 2.35, 7.65);
d.Wall(corr, 14.6, -10, 14.6, 20);
var geo = d.Geo();
var pts = Path(d, geo, 2, 5, 12.3, -8, room, corr);
var exit = pts.First(p => X(p) > 10);
Check.Near(Y(exit), 5, 1e-3, "the exit point stays on the opening's centre line");
Check.Near(X(exit), 13.5, 0.13, $"3.5 m beyond the opening, not 4 (x {X(exit):F2})");
Check.True(Clear(geo, exit) >= 0.98, $"1 m from the far wall ({Clear(geo, exit):F2})");
Check.True(exit.Doorway, "still a doorway point");
Check.Near(X(pts[0]), 6, 1e-3, "the approach in the open room keeps its 4 m");
}
// Rithwic Crypt's corner: a corridor 3.33 m wide comes from the west, a chamfered cell turns
// it north. The chamfer strip is 2.36 m across, so the doorway points' centre lines (y 1.67
// and x 5) run into its outer wall within a metre of the openings.
private static (Dungeon D, uint West, uint Corner, uint North) ChamferDungeon()
{
var d = new Dungeon();
uint west = d.Cell(-10, 0, 0, 3.33);
uint corner = d.CellPoly(2.5, 4.2, (0, 0, 0), (6.67, 6.67, 0), (3.33, 6.67, 0), (0, 3.33, 0));
uint north = d.Cell(3.33, 6.67, 6.67, 16.67);
d.OpenX(west, corner, 0, 0, 3.33);
d.OpenY(corner, north, 6.67, 3.33, 6.67);
d.Wall(corner, 0, 0, 6.67, 6.67); // the bend's outer wall
d.Wall(corner, 0, 3.33, 3.33, 6.67); // its inner wall
d.Wall(west, -10, 0, 0, 0); d.Wall(west, -10, 3.33, 0, 3.33);
d.Wall(north, 3.33, 6.67, 3.33, 16.67); d.Wall(north, 6.67, 6.67, 6.67, 16.67);
return (d, west, corner, north);
}
private static void ChamferedBend()
{
var (d, west, corner, north) = ChamferDungeon();
var geo = d.Geo();
var pts = Path(d, geo, -8, 1.67, 5, 15, west, corner, north);
var inBend = pts.Where(p => X(p) > 0 && Y(p) < 6.67).ToList();
Check.True(inBend.Count >= 1, $"points in the bend ({inBend.Count})");
foreach (var p in pts)
Check.True(Clear(geo, p) >= 0.98, $"({X(p):F2}, {Y(p):F2}) is 1 m from every wall ({Clear(geo, p):F2})");
// Before: the exit point on the west opening's centre line, 1 m in: 0.47 m from the outer wall.
Check.True(geo.Clearance(1, 1.67, 0) < 0.5, "the centre line's best spot was under 0.5 m from the outer wall");
var cells = new[] { west, corner, north };
Check.True(LegsClear(geo, cells, -8, 1.67, pts, 5, 15), "every leg stays on the floor and off the walls");
}
private static void DeadEndLookInOnFloor()
{
// The loop dungeon with a dead end off its east corner: a corridor (x 45.3..53.7) closed by
// a steep end cap (53.7..55.3, 2 m up), its cell origin behind the cap (55.8), as in the
// Olthoi hive. The patrol starts there, so it looks into it.
var (d, _, _, _, _) = LoopDungeon();
uint corner = d.Graph.Values.First(n => Math.Abs(DungeonGeometry.NavToWorld(n.EW) - 42.65) < 0.01 && Math.Abs(DungeonGeometry.NavToWorld(n.NS) - 5) < 0.01).CellId;
uint dead = d.CellPoly(55.8, 5, (45.3, 2.35, 0), (53.7, 2.35, 0), (53.7, 7.65, 0), (45.3, 7.65, 0));
d.Floors.Add((dead, new[] { new V3(53.7f, 7.65f, 0f), new V3(53.7f, 2.35f, 0f), new V3(55.3f, 5f, 2f) }));
d.OpenX(corner, dead, 45.3, 2.35, 7.65);
var geo = d.Geo();
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, dead, null, geo);
var lookIn = route.Points.Where(p => X(p) > 46 && Math.Abs(Y(p) - 5) < 1).ToList();
Check.True(lookIn.Count >= 1, "the patrol walks into the dead end");
Check.False(route.Points.Any(p => X(p) > 53.7), "no point on or behind the end cap (the cell origin is at x 55.8)");
foreach (var p in lookIn) Check.True(Clear(geo, p) >= 0.98, $"look-in point ({X(p):F2}, {Y(p):F2}) 1 m from the cap and walls ({Clear(geo, p):F2})");
}
private static void LegAroundInsideCorner()
{
// An L: a corridor down from the north (x 0..3.33) turning east (y 0..3.33); the inside
// corner at (3.33, 3.33). A leg from the north arm to the east arm cuts through it.
var d = new Dungeon();
uint down = d.Cell(0, 3.33, 3.33, 13.33);
uint turn = d.Cell(0, 0, 3.33, 3.33);
uint across = d.Cell(3.33, 0, 13.33, 3.33);
d.OpenY(turn, down, 3.33, 0, 3.33);
d.OpenX(turn, across, 3.33, 0, 3.33);
d.Wall(down, 3.33, 3.33, 3.33, 13.33);
d.Wall(across, 3.33, 3.33, 13.33, 3.33);
var geo = d.Geo();
NavPoint P(double x, double y) => new() { EW = DungeonGeometry.WorldToNav(x), NS = DungeonGeometry.WorldToNav(y), Z = 0 };
var pts = new List<NavPoint> { P(1.67, 8), P(9, 1.67) };
Check.True(geo.LegClearance(1.67, 8, 0, 9, 1.67, 0, 1.0, 0.5, out _, out _, out _) < 0.3, "the straight leg passes the inside corner closer than 0.3 m");
DungeonPathfinder.KeepLegsOffWalls(geo, pts, closed: false);
Check.True(pts.Count >= 3, $"a corner put in ({pts.Count - 2})");
for (int i = 0; i + 1 < pts.Count; i++)
{
double least = geo.LegClearance(X(pts[i]), Y(pts[i]), 0, X(pts[i + 1]), Y(pts[i + 1]), 0, 1.0, 0.5, out _, out _, out _);
Check.True(least >= 0.6, $"leg {i} keeps 0.6 m from the corner ({least:F2})");
}
}
private static double DistToSegment(double px, double py, double ax, double ay, double bx, double by)
{
double dx = bx - ax, dy = by - ay, len2 = dx * dx + dy * dy;

View file

@ -25,6 +25,7 @@ internal static class VTankLootTests
r.Add("loot vtank: DisabledRule node (9999)", DisabledRuleNode);
r.Add("loot vtank: string value match", StringValueMatch);
r.Add("loot vtank: long keys LE/GE/E/NE and flag, at the boundary", LongKeys);
r.Add("loot vtank: Decal's Type key (0x0D000000) is the WCID - 'loot everything that isn't retail'", WcidKey);
r.Add("loot vtank: double keys LE/GE", DoubleKeys);
r.Add("loot vtank: object class", ObjectClass);
r.Add("loot vtank: value and workmanship requirements", ValueAndWorkmanship);
@ -143,6 +144,27 @@ internal static class VTankLootTests
Check.True(M(item, C(N.LongValKeyGE, " 1000 ", " 19 ")), "surrounding spaces in data lines are accepted");
}
// Tom (2026-10-04): a rule that loots everything not retail by weenie id. Retail WCIDs on
// Aelrynth end at 53488; custom content is above. VTank writes it as LongValKeyGE on Decal's
// synthetic "Type" key, which RynthAi now reads as the WCID through the object cache.
private static void WcidKey()
{
FakeHost.Reset();
var host = FakeHost.Create();
var cache = new WorldObjectCache(host);
const uint Custom = 0x80001001, Retail = 0x80001002;
FakeHost.Wcids[Custom] = 3000105;
FakeHost.Wcids[Retail] = 20646;
var custom = new WorldObject(unchecked((int)Custom), "Driftwarden Greataxe", AcObjectClass.MeleeWeapon) { Cache = cache };
var retail = new WorldObject(unchecked((int)Retail), "Ust", AcObjectClass.Ust) { Cache = cache };
string type = WorldObjectCache.DecalTypeKey.ToString(System.Globalization.CultureInfo.InvariantCulture);
Check.Eq(custom.Values(unchecked((int)WorldObjectCache.DecalTypeKey), 0), 3000105, "the Type key reads the WCID");
Check.True(M(custom, C(N.LongValKeyGE, "53489", type)), "custom WCID 3000105 >= 53489: looted");
Check.False(M(retail, C(N.LongValKeyGE, "53489", type)), "retail WCID 20646: not");
Check.True(M(retail, C(N.LongValKeyE, "20646", type)), "an exact WCID match works too");
}
private static void DoubleKeys()
{
var item = new Item("x").Dbl(29, 1.25);