Snapshot for release 2026.10.6.1 (internal bd2f068)
This commit is contained in:
parent
6847868401
commit
5416e8066a
97 changed files with 8926 additions and 244 deletions
|
|
@ -1117,6 +1117,18 @@ public class BuffManager : IDisposable
|
|||
return;
|
||||
}
|
||||
|
||||
// One server action at a time (2026-10-06, Plugins/Shared/ActionPacer.cs): no kit, potion,
|
||||
// wand, stance change or cast while the server hasn't answered the last one (its UseDone;
|
||||
// a buff's enchantment lands before that). Heals keep their priority (ActionPacer's heal
|
||||
// rules). And not while RynthAi still has the character running: the arbiter's stop goes
|
||||
// out this tick, the cast the next one (a stop mid-windup disturbs the cast).
|
||||
if (!PacerAllows(out string paceWhy))
|
||||
{
|
||||
LastBuffSkipReason = "server answering the last action: " + paceWhy;
|
||||
Hold("server answering the last action", paceWhy);
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't issue a cast while the previous cast GESTURE is still animating.
|
||||
// CanCastNow is the engine's CMotionInterp gesture gate (the REAL cast
|
||||
// gate). AC refuses a cast issued mid-gesture with a server-driven
|
||||
|
|
@ -1135,6 +1147,7 @@ public class BuffManager : IDisposable
|
|||
// everything else still waits for the count to drop.
|
||||
bool gateOpen = CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s));
|
||||
bool busyHolds = BusyCount > 0
|
||||
&& !_pacerLetHealAhead // the pacing let this heal go ahead of an unanswered corpse use (its rules)
|
||||
&& (ActiveHealLine(_vitals.HealthPct, _vitals.StaminaPct, out _, out _).Length == 0 || BusyHoldsHeal());
|
||||
if (!gateOpen || busyHolds)
|
||||
{
|
||||
|
|
@ -1157,6 +1170,14 @@ public class BuffManager : IDisposable
|
|||
return;
|
||||
}
|
||||
|
||||
// Health floor: no buff while health is under a heal line that nothing could heal
|
||||
// (Drakkon, 2026-10-06 04:51: recasting Swift Killer at 19% health, dead 10 s later).
|
||||
if (_vitals.MaxHealth > 0 && HealthUnderAnyLine(_vitals.HealthPct, _vitals.StaminaPct))
|
||||
{
|
||||
Hold("health under a heal line");
|
||||
return;
|
||||
}
|
||||
|
||||
// Mana floor: no buff while mana is under Get Mana At. CheckVitals above already tried
|
||||
// Stamina to Mana and a mana potion; when neither could run (stamina too low, none
|
||||
// carried) buffing used to carry on and run mana to 0. Wait for it instead.
|
||||
|
|
@ -1409,6 +1430,16 @@ public class BuffManager : IDisposable
|
|||
if (!healed) { _vitalWhy = ""; healed = AttemptVitalCast("Heal Self"); }
|
||||
string spellWhy = _vitalWhy;
|
||||
if (!healed) { _vitalWhy = ""; healed = AttemptPotion("HealthPotion"); }
|
||||
// Last resort: the kit Kit Min Success skipped. A low chance beats no heal at all
|
||||
// (Drakkon, 2026-10-06: 29% kit skipped, no spell, no potion, dead 6 s later).
|
||||
if (!healed && kitWhy.EndsWith("under Kit Min Success %", StringComparison.Ordinal))
|
||||
{
|
||||
string potionWhy = _vitalWhy;
|
||||
_vitalWhy = "";
|
||||
healed = AttemptHealthKitUse(ignoreMinSuccess: true);
|
||||
if (healed) _host.Log("[RynthAi] Vitals: no spell or potion could heal; using the kit despite Kit Min Success %.");
|
||||
else _vitalWhy = potionWhy;
|
||||
}
|
||||
if (healed)
|
||||
{
|
||||
_isHealingSelf = true;
|
||||
|
|
@ -1485,6 +1516,7 @@ public class BuffManager : IDisposable
|
|||
if ((DateTime.Now - _lastPendingEmergencyHealAt).TotalMilliseconds < 2500) return;
|
||||
if (IsAwaitingCastResolution() || BusyHoldsHeal() || KitPending()) return;
|
||||
if (!CastGateWatchdog.CanCastNow(_host.CanCastNow, s => _host.Log(s))) return;
|
||||
if (!ActionPacer.MayStart(_host, "Buff", HealNeed.Emergency, out _)) return;
|
||||
if (AttemptHealthKitUse() || AttemptPotion("HealthPotion"))
|
||||
{
|
||||
_lastPendingEmergencyHealAt = DateTime.Now;
|
||||
|
|
@ -1541,6 +1573,18 @@ public class BuffManager : IDisposable
|
|||
return true;
|
||||
}
|
||||
int spellId = FindBestSpellId(baseName, AcSkillType.LifeMagic);
|
||||
// A heal with nothing known at the allowed tiers: the lowest known tier above them.
|
||||
// Vitae can drop Life Magic under a tier line while only higher tiers are known.
|
||||
if (spellId == 0 && baseName is "Heal Self" or "Stamina to Health Self")
|
||||
{
|
||||
spellId = _spellManager.GetSelfSpellIdAboveAllowedTier(baseName, AcSkillType.LifeMagic);
|
||||
if (spellId != 0 && (DateTime.Now - _lastAboveTierLog).TotalSeconds >= 30)
|
||||
{
|
||||
_lastAboveTierLog = DateTime.Now;
|
||||
_host.Log($"[RynthAi] Vitals: no '{baseName}' at the tiers Life Magic allows now; " +
|
||||
$"trying {SpellTableStub.GetById(spellId)?.Name ?? spellId.ToString()} (may fizzle).");
|
||||
}
|
||||
}
|
||||
if (spellId == 0) return VitalNo($"no known '{baseName}' spell at the allowed tiers");
|
||||
// Parked after a hard server refusal (see OnChatWindowText) — the same
|
||||
// per-family cooldown the buff selectors honour.
|
||||
|
|
@ -1566,7 +1610,8 @@ public class BuffManager : IDisposable
|
|||
_pendingSpellId = spellId;
|
||||
_pendingVitalSpellId = spellId; // instant: confirmed by chat, never by the registry
|
||||
_pendingVitalLabel = VitalLabel(baseName);
|
||||
bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId);
|
||||
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff",
|
||||
SpellTableStub.GetById(spellId)?.Name ?? baseName);
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
if (!castOk)
|
||||
{
|
||||
|
|
@ -1726,7 +1771,9 @@ public class BuffManager : IDisposable
|
|||
}
|
||||
private DateTime _lastPotionAt = DateTime.MinValue;
|
||||
|
||||
private bool AttemptHealthKitUse()
|
||||
private DateTime _lastAboveTierLog = DateTime.MinValue;
|
||||
|
||||
private bool AttemptHealthKitUse(bool ignoreMinSuccess = false)
|
||||
{
|
||||
if (_worldObjectCache == null) return false;
|
||||
// VTank's kit options: skip kits in magic mode unless allowed; optionally
|
||||
|
|
@ -1745,10 +1792,10 @@ public class BuffManager : IDisposable
|
|||
if (KitRetryWait(out string kitWait)) return VitalNo(kitWait);
|
||||
// Too likely to fail on what's missing (KitMinSuccessPct): let the spell have it.
|
||||
uint missing = _vitals.MaxHealth > _vitals.CurrentHealth ? _vitals.MaxHealth - _vitals.CurrentHealth : 0;
|
||||
if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %");
|
||||
if (!ignoreMinSuccess && !KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return VitalNo($"{kit.Name} under Kit Min Success %");
|
||||
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode)
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the healing kit");
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
_healWaitKind = "peace mode for the kit";
|
||||
return true; // use the kit next tick, once in peace mode
|
||||
|
|
@ -1781,7 +1828,7 @@ public class BuffManager : IDisposable
|
|||
if (!KitChanceOk(kit.Id, kit.Name ?? "", missing, _settings.PeaceModeForKits)) return false;
|
||||
if (_settings.PeaceModeForKits && mode != CombatMode.NonCombat && _host.HasChangeCombatMode)
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
_host.ChangeCombatModeFor(CombatMode.NonCombat, "Buff", "peace mode for the stamina kit");
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
return true; // use the kit next tick, once in peace mode
|
||||
}
|
||||
|
|
@ -2102,7 +2149,7 @@ public class BuffManager : IDisposable
|
|||
// buffed when it wasn't and never retried the known tier.
|
||||
|
||||
if (diagnose) _host.Log($"[FR] CAST '{buffBaseName}' resolvedSpellId={spellId} (pending now set)");
|
||||
bool castOk = _host.CastSpell((uint)_host.GetPlayerId(), spellId);
|
||||
bool castOk = _host.CastSpellFor((uint)_host.GetPlayerId(), spellId, "Buff", spellInfo?.Name ?? buffBaseName);
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
if (castOk) NoteCastIssued(spellId);
|
||||
if (castOk && buffFamily != 0 && spellInfo != null)
|
||||
|
|
@ -3364,6 +3411,50 @@ public class BuffManager : IDisposable
|
|||
_onCastResolved?.Invoke($"cast '{spellName}'");
|
||||
}
|
||||
|
||||
/// <summary>What a heal needs from the pacing now: none, a heal line, or Emergency Heal At.</summary>
|
||||
internal HealNeed HealNeedNow()
|
||||
{
|
||||
if (_vitals.MaxHealth <= 0) return HealNeed.None;
|
||||
int hp = _vitals.HealthPct;
|
||||
int emergencyAt = _settings.EmergencyHealAt;
|
||||
if (emergencyAt > 0 && hp <= emergencyAt) return HealNeed.Emergency;
|
||||
return HealthUnderAnyLine(hp, _vitals.StaminaPct) ? HealNeed.Heal : HealNeed.None;
|
||||
}
|
||||
|
||||
/// <summary>Times the vitals/buff step waited for the server's answer (tests, status).</summary>
|
||||
internal int PacerHolds { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// The pacing gate of the vitals/buff step (see HeartbeatCore): false while the server is still
|
||||
/// answering the last action (ActionPacer.MayStart, with the heal rules) or while RynthAi still
|
||||
/// has the character running (the arbiter's stop goes out first).
|
||||
/// </summary>
|
||||
private bool _pacerLetHealAhead;
|
||||
|
||||
private bool PacerAllows(out string why)
|
||||
{
|
||||
why = "";
|
||||
_pacerLetHealAhead = false;
|
||||
if (!ActionPacer.Enabled) return true;
|
||||
if (MoveAudit.OwnMovementActive)
|
||||
{
|
||||
why = "the character is still moving (the stop goes out first)";
|
||||
PacerHolds++;
|
||||
return false;
|
||||
}
|
||||
HealNeed need = HealNeedNow();
|
||||
bool outstanding = ActionPacer.Current(_host) != null;
|
||||
if (ActionPacer.MayStart(_host, "Buff", need, out why))
|
||||
{
|
||||
// A heal let ahead of an unanswered action: the busy count still counts that action,
|
||||
// so the busy gate below must not hold the heal again.
|
||||
_pacerLetHealAhead = outstanding && need != HealNeed.None;
|
||||
return true;
|
||||
}
|
||||
PacerHolds++;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Record that a cast just went out, so the next one waits for the
|
||||
/// server to report the action finished rather than a blind interval.</summary>
|
||||
private void NoteCastIssued(int spellId)
|
||||
|
|
@ -3491,6 +3582,7 @@ public class BuffManager : IDisposable
|
|||
var held = _cast.Open;
|
||||
string name = held?.Name ?? "?";
|
||||
double secs = _cast.HeldSeconds;
|
||||
FlightRecorderSignal.Dump(_host, $"held cast nudge: '{name}' {secs:0.0} s");
|
||||
if (!_host.HasSetAutoRun)
|
||||
{
|
||||
_host.Log($"[CastSafe] '{name}' held open {secs:0.0} s after its incantation, but this engine has no SetAutoRun: no nudge.");
|
||||
|
|
@ -3740,9 +3832,9 @@ public class BuffManager : IDisposable
|
|||
// _lastBuffStanceAttempt), while buffing held the bot.
|
||||
int noWandShift = Math.Min(_buffStanceConsecutiveFails, 5);
|
||||
int noWandGateMs = Math.Min(1000 << noWandShift, 30000);
|
||||
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs)
|
||||
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > noWandGateMs
|
||||
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "no wand: Magic mode bare-handed"))
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
NoteStanceRequest();
|
||||
_lastBuffStanceAttempt = DateTime.Now;
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
|
|
@ -3924,9 +4016,9 @@ public class BuffManager : IDisposable
|
|||
if (shift > 5) shift = 5;
|
||||
int gateMs = 1000 << shift; // 1s, 2s, 4s, 8s, 16s, 32s
|
||||
if (gateMs > 30000) gateMs = 30000; // cap at 30s
|
||||
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs)
|
||||
if ((DateTime.Now - _lastBuffStanceAttempt).TotalMilliseconds > gateMs
|
||||
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode"))
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
NoteStanceRequest();
|
||||
_lastBuffStanceAttempt = DateTime.Now;
|
||||
_lastCastAttempt = DateTime.Now;
|
||||
|
|
|
|||
|
|
@ -156,6 +156,8 @@ internal sealed class CastTracker
|
|||
private void Close(Cast c, string kind)
|
||||
{
|
||||
c.Done = true;
|
||||
// The server is in the cast's recoil now: one heal may be queued behind it (ActionPacer).
|
||||
RynthCore.Plugin.Shared.ActionPacer.NoteCastResult();
|
||||
DateTime now = Now;
|
||||
string nudged = c.Nudged ? " (after the movement nudge)" : "";
|
||||
if (c.HasIncantation)
|
||||
|
|
|
|||
|
|
@ -221,6 +221,14 @@ public partial class CombatManager : IDisposable
|
|||
private WeaponSwapGate? _weaponSwapGate;
|
||||
public void SetWeaponSwapGate(WeaponSwapGate gate) => _weaponSwapGate = gate;
|
||||
|
||||
/// <summary>
|
||||
/// True = hold the idle peace-mode swap (PeaceModeWhenIdle) for now. RynthAi answers true while
|
||||
/// looting has work: on ACE a combat-mode change cancels the server's walk/turn to a corpse
|
||||
/// being opened (2026-10-06). Null = never hold.
|
||||
/// </summary>
|
||||
public Func<bool>? HoldIdlePeace { get; set; }
|
||||
private bool _idlePeaceHeldLogged;
|
||||
|
||||
/// <summary>Current combat mode — read live from AC client each access to avoid event-drop drift.</summary>
|
||||
public int CurrentCombatMode =>
|
||||
_host.HasGetCurrentCombatMode ? _host.GetCurrentCombatMode() : CombatMode.NonCombat;
|
||||
|
|
@ -305,7 +313,7 @@ public partial class CombatManager : IDisposable
|
|||
private DateTime _lastSwingEvidenceAt = DateTime.MinValue;
|
||||
private DateTime _lastHitAt = DateTime.MinValue;
|
||||
private DateTime _lastMissAt = DateTime.MinValue;
|
||||
private DateTime _lastKillAt = DateTime.MinValue;
|
||||
private DateTime _lastKillAt = DateTime.MinValue; // stall-watchdog evidence only; metas and the status feed read the plugin's KillClock
|
||||
private string _lastSwingEvidenceKind = "none";
|
||||
|
||||
private readonly CombatStallWatchdog _stallWatch = new();
|
||||
|
|
@ -2314,9 +2322,22 @@ public partial class CombatManager : IDisposable
|
|||
// prevents ChangeCombatMode spam while idling between spawns.
|
||||
if (CurrentCombatMode == CombatMode.NonCombat)
|
||||
_idlePeaceAttempts = 0; // reached peace — the next idle request starts fresh
|
||||
bool peaceHeld = false;
|
||||
if (_settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat
|
||||
&& _scannedTargets.Count == 0 && BusyCount == 0
|
||||
&& DateTime.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode
|
||||
{
|
||||
try { peaceHeld = HoldIdlePeace?.Invoke() == true; } catch { peaceHeld = false; }
|
||||
if (peaceHeld && !_idlePeaceHeldLogged)
|
||||
{
|
||||
_idlePeaceHeldLogged = true;
|
||||
_host.Log($"[EquipDiag] idle peace-mode swap held: looting is working (a mode change would cancel the server's walk/turn to the corpse); it goes out once looting is done.");
|
||||
}
|
||||
}
|
||||
if (!peaceHeld) _idlePeaceHeldLogged = false;
|
||||
if (!peaceHeld && _settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat
|
||||
&& _scannedTargets.Count == 0 && BusyCount == 0
|
||||
&& DateTime.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode
|
||||
{
|
||||
// Defer idle peace-swap while a cast at the just-dropped target is still
|
||||
// resolving: ChangeCombatMode truncates the in-flight gesture → strands
|
||||
|
|
@ -2325,9 +2346,9 @@ public partial class CombatManager : IDisposable
|
|||
// 4 after that up to 15 s. An unbounded ChangeCombatMode stream is the
|
||||
// 2026-05-25 stance-spam crash class; this used to retry every 500 ms forever.
|
||||
double peaceDelayMs = Math.Min(15_000, 500 * Math.Pow(2, Math.Min(5, _idlePeaceAttempts / 4)));
|
||||
if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > peaceDelayMs && !IsCastInFlight())
|
||||
if ((DateTime.Now - _lastPeaceAttempt).TotalMilliseconds > peaceDelayMs && !IsCastInFlight()
|
||||
&& _host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target (Peace Mode When Idle)"))
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
_lastPeaceAttempt = DateTime.Now;
|
||||
_idlePeaceAttempts++;
|
||||
if (_idlePeaceAttempts == 16)
|
||||
|
|
@ -2411,6 +2432,17 @@ public partial class CombatManager : IDisposable
|
|||
if (RunStallWatchdog(targetObj, currentDist))
|
||||
return true;
|
||||
|
||||
// One server action at a time (2026-10-06, Plugins/Shared/ActionPacer.cs): no stance change,
|
||||
// wield, attack or cast while the server is still answering the last action (a kit, a corpse
|
||||
// use, a buff, the last stance change). On ACE a mode change cancels a pending use's walk
|
||||
// and fails a cast in progress; that interleaving began every stuck-use stall on record.
|
||||
if (!ActionPacer.MayStart(_host, "Combat", HealNeed.None, out _))
|
||||
{
|
||||
LastCombatSkipReason = "server-answering"; // D4 record-only
|
||||
_tickWait = CombatLatencyTracker.Wait.Busy;
|
||||
return true;
|
||||
}
|
||||
|
||||
// While a targeted combat cast is still resolving on the server, do NOT re-assert
|
||||
// stance/weapon here: EquipWeaponAndSetStance can emit ChangeCombatMode/UseObject,
|
||||
// motion-replacing actions that truncate the in-flight cast gesture → orphan the cast
|
||||
|
|
@ -2648,7 +2680,9 @@ public partial class CombatManager : IDisposable
|
|||
_returnToPhysicalCombat = true;
|
||||
_host.UseFor((uint)wandId, "Combat", "wield the wand to cast");
|
||||
_lastEquipTime = DateTime.Now; // gate AttackWithMagic until wand is wielded
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
// Held by the pacing until the wield is answered; the wielded branch of
|
||||
// EquipWeaponAndSetStance sends it then (2026-10-06).
|
||||
_host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "debuff: Magic mode after the wand");
|
||||
lastAttackCmd = DateTime.Now;
|
||||
_lastAttackCmdTargetId = activeTargetId;
|
||||
return true;
|
||||
|
|
@ -2813,7 +2847,7 @@ public partial class CombatManager : IDisposable
|
|||
// Same effect on the server as the wand heal: a mode change runs
|
||||
// HandleActionCancelAttack. EquipWeaponAndSetStance flips back after its
|
||||
// stance retry delay (~1 s with the flip backoff reset).
|
||||
_host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
_host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat/Stall", "stall watchdog: toggle the mode", force: true);
|
||||
_stallToggleAt = now;
|
||||
ResetStanceFlipBackoff();
|
||||
lastStanceAttempt = now;
|
||||
|
|
@ -3721,9 +3755,9 @@ public partial class CombatManager : IDisposable
|
|||
ResetStanceFlipBackoff();
|
||||
return true;
|
||||
}
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
|
||||
&& _host.ChangeCombatModeFor(CombatMode.Melee, "Combat", "stance"))
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Melee);
|
||||
lastStanceAttempt = DateTime.Now;
|
||||
NoteStanceFlipSent();
|
||||
}
|
||||
|
|
@ -3931,7 +3965,6 @@ public partial class CombatManager : IDisposable
|
|||
_lastStanceRecoverAt = DateTime.Now;
|
||||
_stanceReEquipAttempts++;
|
||||
_host.Log($"[EquipDiag] STANCE STUCK {stuckMs:0}ms mode={CurrentCombatMode}≠{desiredMode} (wielded reads true) — re-equip attempt {_stanceReEquipAttempts}/{StanceReEquipMaxAttempts} 0x{targetWeaponId:X8}");
|
||||
if (_host.HasForceResetBusyCount) _host.ForceResetBusyCount();
|
||||
_host.UseFor((uint)targetWeaponId, "Combat", "stance stuck: equip again");
|
||||
_lastEquipTime = DateTime.Now;
|
||||
lastStanceAttempt = DateTime.MinValue; // let ChangeCombatMode re-fire next tick
|
||||
|
|
@ -3948,10 +3981,10 @@ public partial class CombatManager : IDisposable
|
|||
_host.WriteToChat($"[RynthAi] Stance wedged: wand wielded but AC won't enter {(desiredMode == CombatMode.Magic ? "Magic" : "combat")} mode after {stuckMs / 1000:0}s. Re-equip stopped (was jamming item actions). Try /ra clearbusy, or relog if it persists.", 2);
|
||||
}
|
||||
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
|
||||
&& _host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
|
||||
{
|
||||
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=true mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource}) — sending ChangeCombatMode"); }
|
||||
_host.ChangeCombatMode(desiredMode);
|
||||
lastStanceAttempt = DateTime.Now;
|
||||
NoteStanceFlipSent();
|
||||
}
|
||||
|
|
@ -3998,9 +4031,9 @@ public partial class CombatManager : IDisposable
|
|||
// mode bare-handed (throttled) and send no wield.
|
||||
if (!allowWield)
|
||||
{
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
|
||||
&& _host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
|
||||
{
|
||||
_host.ChangeCombatMode(desiredMode);
|
||||
lastStanceAttempt = DateTime.Now;
|
||||
NoteStanceFlipSent();
|
||||
}
|
||||
|
|
@ -4035,10 +4068,10 @@ public partial class CombatManager : IDisposable
|
|||
// nothing when the wand genuinely isn't wielded: ACE just denies it, and the
|
||||
// gated UseObject below still does the wielding. Mirrors the non-wand branch,
|
||||
// which has always sent both.
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
|
||||
&& _host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
|
||||
{
|
||||
if (diagNow) _host.Log($"[EquipDiag] hand clear — ChangeCombatMode({desiredMode}) alongside wand equip (mode={CurrentCombatMode})");
|
||||
_host.ChangeCombatMode(desiredMode);
|
||||
lastStanceAttempt = DateTime.Now;
|
||||
NoteStanceFlipSent();
|
||||
}
|
||||
|
|
@ -4092,13 +4125,10 @@ public partial class CombatManager : IDisposable
|
|||
// OnCombatModeChange). Request both a mode change and an equip — these go in the
|
||||
// main hand, which AC swaps in place (no held-slot collision). ChangeCombatMode
|
||||
// succeeds if already wielded (fixes hot-reload next tick); UseObject equips it if not.
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
|
||||
{
|
||||
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); }
|
||||
_host.ChangeCombatMode(desiredMode);
|
||||
lastStanceAttempt = DateTime.Now;
|
||||
NoteStanceFlipSent();
|
||||
}
|
||||
// The wield goes first (2026-10-06): both went out within 3 ms (07:13:16.446/.453), a
|
||||
// mode change on top of an unanswered action. With the pacing on, the mode change waits
|
||||
// for the wield's answer (and once the weapon reads wielded, the wielded branch above
|
||||
// sends it); off, both still go in this tick, as before.
|
||||
if (allowWield && (DateTime.Now - _lastEquipTime).TotalMilliseconds > 2000
|
||||
&& ClearOffhandFor(targetWeaponId, _curOffhandMode) == OffPrep.Ready // a shield off before a two-hander / launcher
|
||||
&& (desiredMode != CombatMode.Missile || PrepareAmmoFor(targetWeaponId) == AmmoPrep.Ready)
|
||||
|
|
@ -4109,6 +4139,13 @@ public partial class CombatManager : IDisposable
|
|||
MarkWieldSent(targetWeaponId, inHand);
|
||||
_lastEquipTime = DateTime.Now;
|
||||
}
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
|
||||
&& _host.ChangeCombatModeFor(desiredMode, "Combat", "stance"))
|
||||
{
|
||||
if (diagNow) { _lastEquipDiagAt = DateTime.Now; _host.Log($"[EquipDiag] wielded=FALSE mode={CurrentCombatMode}→{desiredMode} (weapon=0x{targetWeaponId:X8} '{weaponObj.Name}' src={weaponSource} class={weaponObj.ObjectClass}) — ChangeCombatMode"); }
|
||||
lastStanceAttempt = DateTime.Now;
|
||||
NoteStanceFlipSent();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -4225,9 +4262,9 @@ public partial class CombatManager : IDisposable
|
|||
// for good, even in Magic mode, so a Recall waypoint never cast and sat
|
||||
// out the whole portal timeout.
|
||||
if (CurrentCombatMode == CombatMode.Magic) { ResetStanceFlipBackoff(); return true; }
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
|
||||
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "stance"))
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
lastStanceAttempt = DateTime.Now;
|
||||
NoteStanceFlipSent();
|
||||
}
|
||||
|
|
@ -4244,9 +4281,9 @@ public partial class CombatManager : IDisposable
|
|||
if (alreadyWielded)
|
||||
{
|
||||
if (CurrentCombatMode == CombatMode.Magic) { ResetWandSwapState(); ResetStanceFlipBackoff(); return true; }
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs())
|
||||
if ((DateTime.Now - lastStanceAttempt).TotalMilliseconds > StanceRetryDelayMs()
|
||||
&& _host.ChangeCombatModeFor(CombatMode.Magic, "Combat", "stance"))
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
lastStanceAttempt = DateTime.Now;
|
||||
NoteStanceFlipSent();
|
||||
}
|
||||
|
|
@ -4770,7 +4807,7 @@ public partial class CombatManager : IDisposable
|
|||
|
||||
try
|
||||
{
|
||||
_host.CastSpell((uint)activeTargetId, spellId);
|
||||
_host.CastSpellFor((uint)activeTargetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
|
||||
MarkCombatCastIssued();
|
||||
_lastSpellCast = DateTime.Now;
|
||||
_lastCastWasRing = false;
|
||||
|
|
@ -4823,7 +4860,7 @@ public partial class CombatManager : IDisposable
|
|||
$"shape={ShapeName(castShape)} ring={isRing} warTier={warTier} voidTier={voidTier} target='{target.Name}'");
|
||||
try
|
||||
{
|
||||
_host.CastSpell((uint)activeTargetId, offensiveSpellId);
|
||||
_host.CastSpellFor((uint)activeTargetId, offensiveSpellId, "Combat", SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}");
|
||||
MarkCombatCastIssued();
|
||||
SessionAttackCasts++; // D6: offensive attack-cast tally for the casts-per-kill signal
|
||||
CastsSinceLastKill++; // reset in OnKillNotification when a kill lands
|
||||
|
|
|
|||
126
Plugins/RynthCore.Plugin.RynthAi/Combat/KillClock.cs
Normal file
126
Plugins/RynthCore.Plugin.RynthAi/Combat/KillClock.cs
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// The one "time since our last kill" clock (2026-10-06). Read by the meta expression
|
||||
/// secondssincelastkill[], the "No Kills Within Minutes" meta condition and the status feed's
|
||||
/// secsSinceLastKill.
|
||||
///
|
||||
/// A kill is ACE's KillerNotification (GameEvent 0x01AD), which the server sends only to the
|
||||
/// killer: RynthAiPlugin.OnKillNotification is the only caller of <see cref="RecordKill"/>.
|
||||
/// Death messages in chat ("X died", a fellow's kill) never count.
|
||||
///
|
||||
/// Before the first kill this session the clock counts from the last macro start, or, if the
|
||||
/// macro hasn't been started since login, from login (a plugin load or hot reload counts as a
|
||||
/// login), so a meta can still act on "no kills at all". After that it counts from the later of
|
||||
/// the last kill and the last macro start: restarting the macro starts the count again.
|
||||
///
|
||||
/// Monotonic (Environment.TickCount64, not the wall clock). Writers are the plugin pump thread;
|
||||
/// the status feed reads from its poll thread, so every field is read and written with Interlocked.
|
||||
/// </summary>
|
||||
internal sealed class KillClock
|
||||
{
|
||||
private const long None = long.MinValue;
|
||||
|
||||
private readonly Func<long> _nowMs;
|
||||
private long _sessionStartMs;
|
||||
private long _macroStartMs = None;
|
||||
private long _lastKillMs = None;
|
||||
private int _macroWasRunning;
|
||||
|
||||
/// <param name="nowMs">Monotonic milliseconds; tests pass a fake clock.</param>
|
||||
public KillClock(Func<long>? nowMs = null)
|
||||
{
|
||||
_nowMs = nowMs ?? (static () => Environment.TickCount64);
|
||||
_sessionStartMs = _nowMs();
|
||||
}
|
||||
|
||||
/// <summary>Asked on every read, so a macro start is seen before the first condition after it.
|
||||
/// The plugin also calls <see cref="ObserveMacro"/> every tick.</summary>
|
||||
public Func<bool>? MacroRunning { get; set; }
|
||||
|
||||
/// <summary>Login (and plugin load): no kill yet, the clock counts from now. A macro that is
|
||||
/// already on (start macro on login) counts as started now.</summary>
|
||||
public void SessionStarted()
|
||||
{
|
||||
Interlocked.Exchange(ref _sessionStartMs, _nowMs());
|
||||
Interlocked.Exchange(ref _macroStartMs, None);
|
||||
Interlocked.Exchange(ref _lastKillMs, None);
|
||||
Interlocked.Exchange(ref _macroWasRunning, 0);
|
||||
Observe();
|
||||
}
|
||||
|
||||
/// <summary>Notes a macro start (off to on). Safe to call any number of times.</summary>
|
||||
public void ObserveMacro(bool running)
|
||||
{
|
||||
int prev = Interlocked.Exchange(ref _macroWasRunning, running ? 1 : 0);
|
||||
if (running && prev == 0)
|
||||
Interlocked.Exchange(ref _macroStartMs, _nowMs());
|
||||
}
|
||||
|
||||
/// <summary>We killed something (KillerNotification only).</summary>
|
||||
public void RecordKill() => Interlocked.Exchange(ref _lastKillMs, _nowMs());
|
||||
|
||||
/// <summary>True once we have a kill this session.</summary>
|
||||
public bool HasKill => Interlocked.Read(ref _lastKillMs) != None;
|
||||
|
||||
/// <summary>What the clock counts from: "kill", "macro start" or "login".</summary>
|
||||
public string Since
|
||||
{
|
||||
get
|
||||
{
|
||||
Observe();
|
||||
long kill = Interlocked.Read(ref _lastKillMs), macro = Interlocked.Read(ref _macroStartMs);
|
||||
if (kill != None && kill >= macro) return "kill";
|
||||
return macro != None ? "macro start" : "login";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Milliseconds since our last kill (before the first: since the macro start, or login). Never negative.</summary>
|
||||
public long ElapsedMs()
|
||||
{
|
||||
Observe();
|
||||
// The later of the last kill and the last macro start: a restart after a long pause
|
||||
// starts the count again (Tom, 2026-10-06), so "no kills in 10 min" doesn't fire at once.
|
||||
long from = Math.Max(Interlocked.Read(ref _lastKillMs), Interlocked.Read(ref _macroStartMs));
|
||||
if (from == None) from = Interlocked.Read(ref _sessionStartMs);
|
||||
return Math.Max(0, _nowMs() - from);
|
||||
}
|
||||
|
||||
/// <summary>Whole seconds for secondssincelastkill[].</summary>
|
||||
public long SecondsSinceLastKill() => ElapsedMs() / 1000;
|
||||
|
||||
/// <summary>Whole seconds since an actual kill, or -1 before the first (the status feed's value).</summary>
|
||||
public int SecondsSinceKillOnly()
|
||||
{
|
||||
long kill = Interlocked.Read(ref _lastKillMs);
|
||||
if (kill == None) return -1;
|
||||
return (int)Math.Clamp((_nowMs() - kill) / 1000, 0, int.MaxValue);
|
||||
}
|
||||
|
||||
/// <summary>"No Kills Within Minutes": true when nothing was killed for at least
|
||||
/// <paramref name="minutes"/> minutes (decimals allowed: 0.5 = 30 s).</summary>
|
||||
public bool NoKillsFor(double minutes) => ElapsedMs() >= minutes * 60_000.0;
|
||||
|
||||
/// <summary>The condition's value as typed in the editor or the .af file: minutes, decimals
|
||||
/// allowed ("5", "2.5"; a comma decimal is accepted too). False for empty, negative or not a number.</summary>
|
||||
public static bool TryParseMinutes(string? text, out double minutes)
|
||||
{
|
||||
minutes = 0;
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
string t = text.Trim().Replace(',', '.');
|
||||
if (!double.TryParse(t, System.Globalization.NumberStyles.Float,
|
||||
System.Globalization.CultureInfo.InvariantCulture, out double m)) return false;
|
||||
if (double.IsNaN(m) || double.IsInfinity(m) || m < 0) return false;
|
||||
minutes = m;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Observe()
|
||||
{
|
||||
Func<bool>? probe = MacroRunning;
|
||||
if (probe != null) ObserveMacro(probe());
|
||||
}
|
||||
}
|
||||
|
|
@ -223,7 +223,7 @@ public class MissileCraftingManager
|
|||
_combinesCompleted = 0;
|
||||
_allCombinesDone = false;
|
||||
|
||||
try { _host.ChangeCombatMode(CombatMode.NonCombat); } catch { }
|
||||
try { _host.ChangeCombatModeFor(CombatMode.NonCombat, "Crafting", "missile crafting needs peace mode"); } catch { }
|
||||
|
||||
var headItems = inv.Where(i => recipe.IsHead(i.Name)).ToList();
|
||||
var shaftItems = inv.Where(i => recipe.IsShaft(i.Name)).ToList();
|
||||
|
|
|
|||
|
|
@ -60,6 +60,16 @@ internal sealed class PetManager
|
|||
// get parked so we advance to the next configured essence instead of looping.
|
||||
private readonly Dictionary<int, long> _deviceCooldownUntil = new();
|
||||
|
||||
// The server's word over a stale Structure read (2026-10-05). A read
|
||||
// can say 0 while the server holds a full essence; the server then answers a refill with
|
||||
// "already full" (or refills it and the read still lags), and deciding from the read alone
|
||||
// re-issued the refill every think tick: peace mode and a clap each time, a spirit each time
|
||||
// the refill was real. Essence -> until when its read of 0 is not believed; cleared when a
|
||||
// summon reports "not enough charges".
|
||||
private readonly Dictionary<int, long> _serverSaidFullUntil = new();
|
||||
// Refills issued per essence: how many since the window opened, and when it opened.
|
||||
private readonly Dictionary<int, (int Count, long Since)> _refills = new();
|
||||
|
||||
// Encapsulated Spirit — the fixed retail recharge item (WCID 49485). Detected
|
||||
// by name; it is never itself a summon device.
|
||||
private const string EncapsulatedSpiritName = "Encapsulated Spirit";
|
||||
|
|
@ -69,11 +79,17 @@ internal sealed class PetManager
|
|||
private const long AssumeActiveAfterSummonMs = 10_000;
|
||||
private const long DeviceFailCooldownMs = 30_000;
|
||||
private const long DeviceNoSpiritCooldownMs = 15_000;
|
||||
private const long ServerSaidFullTrustMs = 30 * 60_000;
|
||||
private const long RefillWindowMs = 120_000; // two refills inside this and the
|
||||
private const int RefillsPerWindow = 2; // essence still reads empty:
|
||||
private const long RefillLoopParkMs = 300_000; // park it this long
|
||||
|
||||
private string _playerName = string.Empty;
|
||||
private long _playerNameAt;
|
||||
|
||||
private static long NowMs => Environment.TickCount64;
|
||||
/// <summary>Clock (ms); tests replace it.</summary>
|
||||
internal static Func<long> Clock { get; set; } = static () => Environment.TickCount64;
|
||||
private static long NowMs => Clock();
|
||||
|
||||
public PetManager(RynthCoreHost host, LegacyUiSettings settings,
|
||||
WorldObjectCache objectCache, CombatManager? combat,
|
||||
|
|
@ -159,6 +175,7 @@ internal sealed class PetManager
|
|||
if (text.Contains("enough charges", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_host.Log($"[RynthAi] Pet: essence 0x{(uint)_activeDeviceId:X8} reports empty; will refill.");
|
||||
_serverSaidFullUntil.Remove(_activeDeviceId); // really empty: the read is right again
|
||||
GoIdle();
|
||||
return;
|
||||
}
|
||||
|
|
@ -168,10 +185,13 @@ internal sealed class PetManager
|
|||
if (_state == PetState.Refilling)
|
||||
{
|
||||
// "You add the spirit to the essence." (success) / "This essence is
|
||||
// already full." (our Structure read was stale — also done).
|
||||
if (text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase)
|
||||
|| text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase))
|
||||
// already full." (our Structure read was stale — also done). Either way the
|
||||
// essence is full now, whatever its read says until the next update.
|
||||
bool added = text.Contains("add the spirit to the essence", StringComparison.OrdinalIgnoreCase);
|
||||
bool full = !added && text.Contains("essence is already full", StringComparison.OrdinalIgnoreCase);
|
||||
if (added || full)
|
||||
{
|
||||
OnServerSaidFull(_activeDeviceId, added);
|
||||
GoIdle();
|
||||
}
|
||||
}
|
||||
|
|
@ -203,6 +223,12 @@ internal sealed class PetManager
|
|||
|
||||
int charges = ReadCharges(deviceId); // -1 = unreadable
|
||||
|
||||
// The server called this essence full after the read last changed: the 0 is stale.
|
||||
// Summon as for an unreadable one (an empty essence is refused harmlessly, and that
|
||||
// "not enough charges" ends the trust).
|
||||
if (charges == 0 && ServerSaidFull(deviceId, now))
|
||||
charges = -1;
|
||||
|
||||
if (charges != 0)
|
||||
{
|
||||
// Has charges (or unreadable → attempt; an empty one is rejected
|
||||
|
|
@ -215,11 +241,13 @@ internal sealed class PetManager
|
|||
if (_settings.PetAutoRefill)
|
||||
{
|
||||
int spiritId = FindEncapsulatedSpirit();
|
||||
if (spiritId != 0)
|
||||
if (spiritId != 0 && !RefillLooping(deviceId, now))
|
||||
{
|
||||
IssueRefill(deviceId, spiritId);
|
||||
return;
|
||||
}
|
||||
if (spiritId != 0)
|
||||
continue; // parked by RefillLooping; try the next essence
|
||||
}
|
||||
|
||||
// Out of charges and no spirit (or refill off): park this essence
|
||||
|
|
@ -251,10 +279,57 @@ internal sealed class PetManager
|
|||
_activeDeviceId = deviceId;
|
||||
_activeSpiritId = spiritId;
|
||||
_actionIssuedAt = NowMs;
|
||||
CountRefill(deviceId, _actionIssuedAt);
|
||||
_host.Log($"[RynthAi] Pet: refilling essence 0x{(uint)deviceId:X8} with spirit 0x{(uint)spiritId:X8}.");
|
||||
_host.UseOnFor(unchecked((uint)spiritId), unchecked((uint)deviceId), "Pet", "refill the essence with a spirit");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server said the essence is full ("You add the spirit..." / "...already full"): its
|
||||
/// read of 0 is not believed for a while, and it is re-identified so the read catches up.
|
||||
/// </summary>
|
||||
private void OnServerSaidFull(int deviceId, bool refilled)
|
||||
{
|
||||
if (deviceId == 0) return;
|
||||
_serverSaidFullUntil[deviceId] = NowMs + ServerSaidFullTrustMs;
|
||||
if (_host.HasRequestId) _host.RequestId(unchecked((uint)deviceId));
|
||||
_host.Log(refilled
|
||||
? $"[RynthAi] Pet: refill complete (essence 0x{(uint)deviceId:X8}, server confirmed)."
|
||||
: $"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} is already full (its charge read was stale); summoning from it.");
|
||||
}
|
||||
|
||||
private bool ServerSaidFull(int deviceId, long now)
|
||||
{
|
||||
if (!_serverSaidFullUntil.TryGetValue(deviceId, out long until)) return false;
|
||||
if (now < until) return true;
|
||||
_serverSaidFullUntil.Remove(deviceId);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void CountRefill(int deviceId, long now)
|
||||
{
|
||||
if (_refills.TryGetValue(deviceId, out var r) && now - r.Since < RefillWindowMs)
|
||||
_refills[deviceId] = (r.Count + 1, r.Since);
|
||||
else
|
||||
_refills[deviceId] = (1, now);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True, and the essence parked, when it was refilled <see cref="RefillsPerWindow"/> times
|
||||
/// inside <see cref="RefillWindowMs"/> and still reads empty: another refill would only cost
|
||||
/// a spirit and force peace mode again. An essence holds dozens of summons, so two real
|
||||
/// refills that close together don't happen.
|
||||
/// </summary>
|
||||
private bool RefillLooping(int deviceId, long now)
|
||||
{
|
||||
if (!_refills.TryGetValue(deviceId, out var r) || now - r.Since >= RefillWindowMs || r.Count < RefillsPerWindow)
|
||||
return false;
|
||||
_refills.Remove(deviceId);
|
||||
_deviceCooldownUntil[deviceId] = now + RefillLoopParkMs;
|
||||
_host.Log($"[RynthAi] Pet: essence 0x{(uint)deviceId:X8} was refilled {r.Count}x in {(now - r.Since) / 1000}s and still reads empty; parking it for {RefillLoopParkMs / 60_000} min.");
|
||||
return true;
|
||||
}
|
||||
|
||||
private void GoIdle()
|
||||
{
|
||||
_state = PetState.Idle;
|
||||
|
|
|
|||
|
|
@ -174,6 +174,26 @@ public class SpellManager
|
|||
_ => "I"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The LOWEST known tier of <paramref name="baseSpellName"/> above the buff tier the skill
|
||||
/// allows, 0 when none. For heals when nothing at or under the allowed tier is known: vitae
|
||||
/// can drop Life Magic under a tier line while the character only knows higher tiers, and a
|
||||
/// heal that may fizzle beats none (Drakkon died twice, 2026-10-06).
|
||||
/// </summary>
|
||||
public int GetSelfSpellIdAboveAllowedTier(string baseSpellName, AcSkillType magicSkill)
|
||||
{
|
||||
RefreshKnownSpells();
|
||||
int maxTier = GetHighestBuffSpellTier(magicSkill);
|
||||
string cleanBase = baseSpellName.Replace(" Self", "").Trim();
|
||||
BaseNameAliases.TryGetValue(cleanBase, out string? alias);
|
||||
for (int tier = maxTier + 1; tier <= 8; tier++)
|
||||
{
|
||||
if (TryGetTierId(cleanBase, tier, out int id)) return id;
|
||||
if (alias != null && TryGetTierId(alias, tier, out int idAlias)) return idAlias;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int GetDynamicSelfBuffId(string baseSpellName, AcSkillType magicSkill)
|
||||
{
|
||||
RefreshKnownSpells(); // keep the authoritative inventory current (throttled)
|
||||
|
|
|
|||
|
|
@ -601,17 +601,17 @@ public class WorldObjectCache
|
|||
return;
|
||||
}
|
||||
|
||||
// Non-creature with a position — could be equipped item on 0x8000 range
|
||||
// or static world object; classify by type flags
|
||||
if ((typeFlags & (ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer)) != 0)
|
||||
{
|
||||
// Item with a world position = equipped or ground-dropped
|
||||
cls = ClassifyItem(uid, typeFlags);
|
||||
_inventory.Add(id);
|
||||
_landscape.Remove(id);
|
||||
_byId[id] = Make(id, name, cls);
|
||||
// Non-creature with a position and a known item type: equipped gear, a ground
|
||||
// drop, a chest. It gets the class its type gives and is filed by who has it
|
||||
// (FileTypedObject). Only weapons, armor, casters and containers were taken
|
||||
// here before, all into the inventory: keys, gems, comps, food and the like
|
||||
// stayed Unknown landscape and were re-probed every 2 s for good, and other
|
||||
// players' wielded gear and ground-dropped weapons counted as ours
|
||||
// (2026-10-05). A static object that isn't a chest or a lifestone returns
|
||||
// false and stays Unknown scenery below, hazard check included.
|
||||
AcObjectClass typedCls = ClassifyItem(uid, typeFlags);
|
||||
if (typedCls != AcObjectClass.Unknown && FileTypedObject(uid, id, name, typedCls, typeFlags))
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (uid >= 0x80000000u)
|
||||
{
|
||||
|
|
@ -660,6 +660,77 @@ public class WorldObjectCache
|
|||
}
|
||||
}
|
||||
|
||||
private const uint ItemTypeGear = ItemTypeMeleeWeapon | ItemTypeMissileWeapon | ItemTypeCaster | ItemTypeArmor | ItemTypeContainer;
|
||||
|
||||
private enum Holder { Unknown, Player, OtherWielder, OtherContainer, Nobody }
|
||||
|
||||
/// <summary>
|
||||
/// Who has the object: the player (wielded, in the main pack, or in a side pack), another
|
||||
/// wielder (other players' and NPCs' gear), another container (a corpse, a chest), or
|
||||
/// nobody (it lies on the ground). Unknown when the player isn't known yet or the engine
|
||||
/// can't read the object's ownership. Caller holds _gate.
|
||||
/// </summary>
|
||||
private Holder WhoHas(int id)
|
||||
{
|
||||
if (_playerId == 0 || !TryGetOwnership(id, out int containerId, out int wielderId, out _))
|
||||
return Holder.Unknown;
|
||||
uint container = unchecked((uint)containerId), wielder = unchecked((uint)wielderId);
|
||||
if (wielder == _playerId || container == _playerId) return Holder.Player;
|
||||
if (wielder != 0) return Holder.OtherWielder;
|
||||
if (container == 0) return Holder.Nobody;
|
||||
// Side packs sit in the main pack (AC has no deeper nesting).
|
||||
return TryGetOwnership(containerId, out int outer, out _, out _) && unchecked((uint)outer) == _playerId
|
||||
? Holder.Player : Holder.OtherContainer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Files a positioned non-creature whose item type gave it a real class. Caller holds _gate.
|
||||
/// <list type="bullet">
|
||||
/// <item>A lifestone: landscape.</item>
|
||||
/// <item>Another static object: a chest goes on the landscape; anything else returns false
|
||||
/// and the caller keeps it Unknown scenery (doors, signs, static hotspots).</item>
|
||||
/// <item>A dynamic object the player has: inventory. One another player or an NPC wields:
|
||||
/// neither list (known by id only), so it is not ours, not a ground item on the radar and
|
||||
/// not something a meta can pick up. In another container or loose on the ground: landscape.</item>
|
||||
/// <item>Ownership unreadable: gear goes to the inventory as before, the rest to the landscape.</item>
|
||||
/// </list>
|
||||
/// A non-gear object that lands on the landscape gets the hazard check it had as Unknown
|
||||
/// (a hotspot spawned with a dynamic id and a Misc type is still a hazard).
|
||||
/// </summary>
|
||||
private bool FileTypedObject(uint uid, int id, string name, AcObjectClass cls, uint typeFlags)
|
||||
{
|
||||
bool gear = (typeFlags & ItemTypeGear) != 0;
|
||||
bool toInventory, toLandscape;
|
||||
if (cls == AcObjectClass.Lifestone)
|
||||
{
|
||||
toInventory = false;
|
||||
toLandscape = true;
|
||||
}
|
||||
else if (uid < 0x80000000u)
|
||||
{
|
||||
if ((typeFlags & ItemTypeContainer) == 0) return false;
|
||||
toInventory = false;
|
||||
toLandscape = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Holder holder = WhoHas(id);
|
||||
toInventory = holder == Holder.Player || (holder == Holder.Unknown && gear);
|
||||
toLandscape = !toInventory && holder != Holder.OtherWielder;
|
||||
}
|
||||
|
||||
_classifyRetry.Remove(uid);
|
||||
_reclassifySkipState.Remove(uid);
|
||||
if (toInventory) { if (_inventory.Add(id)) _inventoryDirty = true; }
|
||||
else if (_inventory.Remove(id)) _inventoryDirty = true;
|
||||
if (toLandscape) _landscape.Add(id);
|
||||
else _landscape.Remove(id);
|
||||
_byId[id] = Make(id, name, cls);
|
||||
if (toLandscape && !gear)
|
||||
MaybeRegisterHazard(uid, name);
|
||||
return true;
|
||||
}
|
||||
|
||||
// PublicWeenieDesc._bitfield BF_CORPSE (ObjectDescriptionFlag.Corpse).
|
||||
private const uint BfCorpse = 0x2000;
|
||||
|
||||
|
|
@ -725,6 +796,7 @@ public class WorldObjectCache
|
|||
List<int>? toPromote = null;
|
||||
List<int>? toCorpse = null;
|
||||
List<(int id, string name, AcObjectClass cls)>? statics = null;
|
||||
List<(int Id, uint Flags)>? typed = null; // Unknowns whose item type now gives a class
|
||||
foreach (int id in _landscape)
|
||||
{
|
||||
uint uid = unchecked((uint)id);
|
||||
|
|
@ -754,7 +826,11 @@ public class WorldObjectCache
|
|||
// Bounded to Monster/Unknown so we don't name-query every ground
|
||||
// item each pass; IsCorpseName is specific ("X corpse"/"Corpse of X")
|
||||
// so a live mob cannot be misread as a corpse.
|
||||
if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown)
|
||||
// Container too: a corpse typed before its name or flag was readable is filed as a
|
||||
// landscape Container by FileTypedObject (it used to go to the inventory, which the
|
||||
// inventory pass below re-checks).
|
||||
if ((wo.ObjectClass == AcObjectClass.Monster || wo.ObjectClass == AcObjectClass.Unknown
|
||||
|| wo.ObjectClass == AcObjectClass.Container)
|
||||
&& ((_host.TryGetObjectName(uid, out string maybeCorpse) && IsCorpseName(maybeCorpse))
|
||||
|| HasCorpseFlag(uid)))
|
||||
{
|
||||
|
|
@ -771,14 +847,21 @@ public class WorldObjectCache
|
|||
// immediate signal that doesn't wait on qualities/appraisal). This
|
||||
// second path is what rescues a login mob within 2s if it slipped
|
||||
// to Unknown before its weenie/combat-state was readable.
|
||||
bool isCreature = _host.TryGetItemType(uid, out uint typeFlags)
|
||||
&& (typeFlags & ItemTypeCreature) != 0;
|
||||
bool gotType = _host.TryGetItemType(uid, out uint typeFlags);
|
||||
bool isCreature = gotType && (typeFlags & ItemTypeCreature) != 0;
|
||||
if (!isCreature
|
||||
&& _host.HasObjectIsAttackable
|
||||
&& _host.ObjectIsAttackable(uid))
|
||||
isCreature = true;
|
||||
if (!isCreature)
|
||||
{
|
||||
// Its type arrived after it was classified: file it as the item it is instead
|
||||
// of probing it again every pass. Done after the loop (filing edits _landscape).
|
||||
if (gotType && typeFlags != 0 && ClassifyByItemType(typeFlags) != AcObjectClass.Unknown)
|
||||
{
|
||||
(typed ??= new()).Add((id, typeFlags));
|
||||
continue;
|
||||
}
|
||||
DiagLogReclassifySkip(uid, wo.Name);
|
||||
continue;
|
||||
}
|
||||
|
|
@ -832,10 +915,27 @@ public class WorldObjectCache
|
|||
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: rescued {toCorpse.Count} stale corpse(s) → Corpse");
|
||||
}
|
||||
|
||||
if (typed != null)
|
||||
{
|
||||
int filed = 0, intoInventory = 0;
|
||||
foreach (var (id, flags) in typed)
|
||||
{
|
||||
if (!_byId.TryGetValue(id, out var wo)) continue;
|
||||
uint uid = unchecked((uint)id);
|
||||
AcObjectClass cls = ClassifyItem(uid, flags);
|
||||
if (cls == AcObjectClass.Unknown || !FileTypedObject(uid, id, wo.Name ?? string.Empty, cls, flags)) continue;
|
||||
filed++;
|
||||
if (_inventory.Contains(id)) intoInventory++;
|
||||
}
|
||||
if (filed > 0)
|
||||
_host.Log($"[RynthAi] ReclassifyUnknownDynamics: typed {filed} Unknown object(s) as items ({intoInventory} into the inventory)");
|
||||
}
|
||||
|
||||
// DIAG: heartbeat — Unknown landscape candidates checked but nothing promoted
|
||||
// this pass. Confirms ReclassifyUnknownDynamics is running and engine signals
|
||||
// keep failing for the stuck uids (vs. them never reaching _landscape at all).
|
||||
if (toPromote == null
|
||||
&& typed == null
|
||||
&& _reclassifySkipState.Count > 0
|
||||
&& _reclassifyDiagSummaryCount < MaxReclassifyDiagSummaries)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -104,7 +104,9 @@ public sealed partial class RynthAiPlugin
|
|||
private long _corpseIdsRequestedAt;
|
||||
private bool _corpseApproachTurnsActive;
|
||||
|
||||
private static long CorpseNowMs => Environment.TickCount64;
|
||||
/// <summary>The loot clock (ms); the host tests replace it to run minutes of looting at once.</summary>
|
||||
internal static Func<long> CorpseClock = static () => Environment.TickCount64;
|
||||
private static long CorpseNowMs => CorpseClock();
|
||||
private void LootDiag(string message)
|
||||
{
|
||||
Log(message);
|
||||
|
|
@ -142,8 +144,49 @@ public sealed partial class RynthAiPlugin
|
|||
// busy-zero churn) paced the whole loot grind, and the 2026-06-12 09:33
|
||||
// storm of them latched the variant-2 stance/item deadlock.
|
||||
private const long BUSY_TIMEOUT_COMBAT_URGENT_MS = 5_000;
|
||||
// The engine's count is the one owner (2026-10-06; analysis by Silentkelpie, re-implemented
|
||||
// here): this mirror is fed by the engine's busy events, and the engine now sends one for
|
||||
// every UseDone and every reset it does, so the two agree except for events still on their
|
||||
// way. A disagreement that lasts BusyMirrorFollowMs is settled the engine's way; the old
|
||||
// 5/10 s mirror reset below is only for an engine without GetBusyState.
|
||||
private const long BusyMirrorFollowMs = 1_500;
|
||||
private long _busyMismatchSince;
|
||||
private long _lastBusyFollowLogAt;
|
||||
private int _busyFollowsSinceLog;
|
||||
|
||||
private bool FollowEngineBusyCount()
|
||||
{
|
||||
if (!Host.HasGetBusyState) return false;
|
||||
int engine;
|
||||
try { engine = Host.GetBusyState(); } catch { return false; }
|
||||
long now = CorpseNowMs;
|
||||
if (engine == _busyCount) { _busyMismatchSince = 0; return true; }
|
||||
if (_busyMismatchSince == 0) { _busyMismatchSince = now; return true; }
|
||||
if (now - _busyMismatchSince < BusyMirrorFollowMs) return true;
|
||||
int was = _busyCount;
|
||||
_busyMismatchSince = 0;
|
||||
_busyCount = Math.Max(0, engine);
|
||||
_busyCountLastIncrementAt = 0;
|
||||
_busyCountBecamePositiveAt = _busyCount > 0 ? now : 0;
|
||||
if (_combatManager != null) _combatManager.BusyCount = _busyCount;
|
||||
if (_buffManager != null) _buffManager.BusyCount = _busyCount;
|
||||
_busyFollowsSinceLog++;
|
||||
if (now - _lastBusyFollowLogAt >= 10_000)
|
||||
{
|
||||
Log($"[RynthAi] Busy mirror {was} -> {_busyCount}: following the engine's count ({_busyFollowsSinceLog} in the last {(now - _lastBusyFollowLogAt) / 1000.0:0} s; the client's count is never cleared by RynthAi).");
|
||||
_lastBusyFollowLogAt = now;
|
||||
_busyFollowsSinceLog = 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void CheckBusyTimeout()
|
||||
{
|
||||
if (FollowEngineBusyCount())
|
||||
{
|
||||
PruneCorpseCollections();
|
||||
return;
|
||||
}
|
||||
if (_busyCount > 0 && _busyCountBecamePositiveAt != 0)
|
||||
{
|
||||
long elapsed = CorpseNowMs - _busyCountBecamePositiveAt;
|
||||
|
|
@ -176,10 +219,17 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (elapsed > threshold)
|
||||
{
|
||||
Log($"[RynthAi] Busy count stuck at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}) — force-clearing.");
|
||||
// Reset pending loot item BEFORE zeroing AC's m_cBusy. If we have an
|
||||
// in-flight UseObject, ForceResetBusyCount zeros m_cBusy under it; the
|
||||
// retry in TickPendingCorpsePickup would then hit a freed AC object and crash.
|
||||
// Our mirror only (2026-10-06). AC's m_cBusy is +1 per action the client sends and
|
||||
// -1 per server UseDone (ClientUISystem::Handle_Item::UseDone, inline - which is why
|
||||
// this mirror, fed by the Increment/Decrement hooks, never saw the decrement and
|
||||
// looked "stuck"). Force-clearing AC's count here zeroed the count of actions the
|
||||
// server had not answered yet (each later UseDone then drove it negative: ~190
|
||||
// repairs an hour in the 10-05/10-06 logs) and let the next action out on top of
|
||||
// them. The pacing waits on the server's answers now (ActionPacer); the client's
|
||||
// own count is left to the client and the engine.
|
||||
bool serverWaiting = RynthCore.Plugin.Shared.ActionPacer.Current(Host) != null;
|
||||
Log($"[RynthAi] Busy mirror at {_busyCount} for >{elapsed}ms (combatUrgent={combatUrgent} lootOpenUrgent={lootOpenUrgent} castGesture={castGestureInProgress}" +
|
||||
$"{(serverWaiting ? ", a server action is still unanswered" : "")}) — resetting the mirror only (the client's count is left alone).");
|
||||
ResetCurrentLootItem();
|
||||
_corpseIdsRequested = false;
|
||||
_lastLootActionAt = CorpseNowMs;
|
||||
|
|
@ -188,7 +238,6 @@ public sealed partial class RynthAiPlugin
|
|||
_busyCountBecamePositiveAt = 0;
|
||||
if (_combatManager != null) _combatManager.BusyCount = 0;
|
||||
if (_buffManager != null) _buffManager.BusyCount = 0;
|
||||
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -350,6 +399,8 @@ public sealed partial class RynthAiPlugin
|
|||
}
|
||||
LootDiag($"[RynthAi] Corpse loot: opened container 0x{objectId:X8}.");
|
||||
_consecutiveLootTimeouts = 0; // a successful open proves AC is responsive again
|
||||
_lootWedgeAnnounced = false;
|
||||
ApplyUseRefusalVerdict(_useRefusals.OnOpened(CorpseNowMs), CorpseNowMs);
|
||||
if (switchedTarget)
|
||||
LootDiag($"[RynthAi] Corpse loot: switching active corpse target from 0x{(uint)_targetCorpseId:X8} to 0x{objectId:X8}.");
|
||||
|
||||
|
|
@ -476,7 +527,12 @@ public sealed partial class RynthAiPlugin
|
|||
// timeouts). Stop firing opens into a dead client until the halt window
|
||||
// elapses — hammering it can't recover a server-side lock, only a relog
|
||||
// can. Navigation/combat (non-item-action) still run elsewhere.
|
||||
if (CorpseNowMs < _lootHaltUntil)
|
||||
// The use-refusal watch first: it reads the server's answers to our opens, and while it
|
||||
// has decided the server refuses every use (Stuck) no corpse is claimed or opened until
|
||||
// its back-off ends.
|
||||
long haltNow = CorpseNowMs;
|
||||
TickUseRefusalWatch(haltNow);
|
||||
if (haltNow < _lootHaltUntil || _useRefusals.HoldsOpens(haltNow))
|
||||
return;
|
||||
|
||||
// ── Buffing: halt loot work but retain target so looting resumes immediately ──
|
||||
|
|
@ -613,6 +669,29 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
// An open goes out only once the arbiter has given Looting the tick. A corpse claimed on
|
||||
// the tick a fight ended (Combat still owned it) used to be opened at once, and the
|
||||
// arbiter's nav stop (StopCompletely) and Combat's idle peace-mode swap followed 3-30 ms
|
||||
// later. On ACE both cancel the server's walk/turn to the corpse - a mode change runs
|
||||
// HandleActionCancelAttack -> cancel_moveto - so that open could only fail (2026-10-06
|
||||
// 06:18:44, the first failed open of the day's stall). One tick later the stop goes
|
||||
// out first (PauseNavigationForCorpse) and the open after it.
|
||||
if (_activity != BotActivity.Looting)
|
||||
return;
|
||||
|
||||
// One server action at a time (2026-10-06, ActionPacer): no open while the server is still
|
||||
// answering another action - a kit, a cast, a stance change, or the last open itself (a
|
||||
// re-sent open restarts the server's walk and fails the first one's callback). The claim's
|
||||
// 12 s timeout keeps running (the longest wait here is the 5 s limit on an open).
|
||||
if (!ActionPacer.MayStart(Host, "Loot", HealNeed.None, out _))
|
||||
return;
|
||||
// The last corpse's close is not answered yet (CloseGroundContainer, ~40 ms): a use now makes
|
||||
// the client send its own NoLongerViewingContents for that corpse too (flight recorder
|
||||
// 2026-10-06 07:57:09.801: the engine's close, then the client's, beside the next use).
|
||||
if (_closeSentFor != 0 && _closeSentFor != _targetCorpseId && now - _closeSentAt < CloseAnswerWaitMs
|
||||
&& Host.HasGetGroundContainerId && unchecked((int)Host.GetGroundContainerId()) == _closeSentFor)
|
||||
return;
|
||||
|
||||
// Farther than reach: just use the corpse. The server walks the character to it and turns
|
||||
// it (as a player's double-click does); steering there ourselves looked awkward and
|
||||
// turned slowly (owner, 2026-10-04). Our own movement stays off so it can't cancel that
|
||||
|
|
@ -625,8 +704,8 @@ public sealed partial class RynthAiPlugin
|
|||
if (_lastCorpseOpenAttemptAt == 0 || now - _lastCorpseOpenAttemptAt >= walkMs)
|
||||
{
|
||||
if (_busyCount > 0 && now - _lastCorpseOpenAttemptAt < OpenBusyWaitMaxMs) return;
|
||||
AttemptOpenCorpse(_targetCorpseId);
|
||||
_lastCorpseOpenAttemptAt = now;
|
||||
if (AttemptOpenCorpse(_targetCorpseId))
|
||||
_lastCorpseOpenAttemptAt = now;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
|
@ -651,8 +730,8 @@ public sealed partial class RynthAiPlugin
|
|||
return; // busy — hold the open briefly
|
||||
}
|
||||
_corpseOpenBusyWaitSince = 0;
|
||||
AttemptOpenCorpse(_targetCorpseId);
|
||||
_lastCorpseOpenAttemptAt = now;
|
||||
if (AttemptOpenCorpse(_targetCorpseId))
|
||||
_lastCorpseOpenAttemptAt = now;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1299,6 +1378,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
ChatLine($"[RynthAi] Loot rule: {matchItemName} -> [{matchActionLabel}] {matchRuleLabel}");
|
||||
_currentLootItemId = firstMatchId;
|
||||
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)firstMatchId));
|
||||
Host.SelectItem(unchecked((uint)firstMatchId));
|
||||
LootDiag($"[RynthAi] Corpse loot: picking up 0x{(uint)firstMatchId:X8} '{matchItemName}' from corpse 0x{(uint)corpseId:X8}.");
|
||||
|
||||
|
|
@ -1412,6 +1492,7 @@ public sealed partial class RynthAiPlugin
|
|||
if (_busyCount > 0)
|
||||
return; // Client is busy — don't queue retry
|
||||
|
||||
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(unchecked((uint)_currentLootItemId));
|
||||
Host.SelectItem(unchecked((uint)_currentLootItemId));
|
||||
LootPickupResult retry = SendLootPickup(_currentLootItemId, _currentLootItemName, _openedContainerId);
|
||||
if (retry == LootPickupResult.NoRoom || retry == LootPickupResult.Refused)
|
||||
|
|
@ -1546,6 +1627,11 @@ public sealed partial class RynthAiPlugin
|
|||
if (!settings.IsMacroRunning || !settings.EnableLooting)
|
||||
return false;
|
||||
|
||||
// The server refuses every use (UseRefusalWatch, Stuck): no loot work until the back-off
|
||||
// ends, so the arbiter lets nav and combat run on instead of standing at the corpses.
|
||||
if (_openedContainerId == 0 && _useRefusals.HoldsOpens(CorpseNowMs))
|
||||
return false;
|
||||
|
||||
// Already committed to a body, or mid-loot with the container open.
|
||||
if (_openedContainerId != 0 || _targetCorpseId != 0 || _corpseAutorunActive)
|
||||
{
|
||||
|
|
@ -1993,10 +2079,6 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (_manaStoneManager == null) return false;
|
||||
if (!Host.HasGetObjectIntProperty) return false;
|
||||
// ACE won't drain a wand, staff or orb into a stone, so ManaStoneManager never taps
|
||||
// one (and its pending-drain count skips them, so the quota never filled): every
|
||||
// high-mana wand was looted and kept for good. Drakkon's "Piercing Sceptre", 2026-10-05.
|
||||
if (ManaStoneManager.IsWandLike(item)) return false;
|
||||
|
||||
int threshold = settings.ManaTapMinMana;
|
||||
if (threshold <= 0) return false;
|
||||
|
|
@ -2297,13 +2379,142 @@ public sealed partial class RynthAiPlugin
|
|||
// or a corpse the bot never reached?).
|
||||
private int _lastOpenAttemptCorpseId;
|
||||
|
||||
private void AttemptOpenCorpse(int corpseId)
|
||||
/// <summary>Sends one open. False when the use-refusal watch acted instead (nothing sent).</summary>
|
||||
private bool AttemptOpenCorpse(int corpseId)
|
||||
{
|
||||
long now = CorpseNowMs;
|
||||
bool watch = Host.HasUseDoneSeq;
|
||||
if (watch)
|
||||
{
|
||||
// The previous open, answered with nothing opened, is judged before this one goes out:
|
||||
// a clean stop or a back-off must not land right after a fresh use (it would cancel it).
|
||||
var verdict = _useRefusals.SettleBeforeOpen(now);
|
||||
if (verdict != UseRefusalWatch.Verdict.None)
|
||||
{
|
||||
ApplyUseRefusalVerdict(verdict, now);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
_lastOpenAttemptCorpseId = corpseId;
|
||||
StopCorpseMovement();
|
||||
int seqBefore = watch ? Host.GetUseDoneSeq() : 0;
|
||||
Host.SelectItem(unchecked((uint)corpseId));
|
||||
Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse");
|
||||
bool sent = Host.UseFor(unchecked((uint)corpseId), "Loot", "open the claimed corpse");
|
||||
if (watch && sent)
|
||||
_useRefusals.OnOpenSent(corpseId, now, seqBefore);
|
||||
LootDiag($"[RynthAi] Corpse loot: attempting open for 0x{(uint)corpseId:X8}.");
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Server refuses every use (2026-10-06; Loot/UseRefusalWatch.cs) ─────────────────────
|
||||
private readonly UseRefusalWatch _useRefusals = new();
|
||||
private bool _useStuckAnnounced;
|
||||
private bool _lootWedgeAnnounced;
|
||||
|
||||
/// <summary>Every tick while looting runs: the server's answers to our opens.</summary>
|
||||
private void TickUseRefusalWatch(long now)
|
||||
{
|
||||
if (!Host.HasUseDoneSeq)
|
||||
return;
|
||||
int seq = Host.GetUseDoneSeq();
|
||||
bool haveErr = Host.TryGetLastUseDone(out int lastSeq, out uint err) && lastSeq == seq;
|
||||
ApplyUseRefusalVerdict(_useRefusals.OnTick(now, seq, err, haveErr), now);
|
||||
}
|
||||
|
||||
private void ApplyUseRefusalVerdict(UseRefusalWatch.Verdict verdict, long now)
|
||||
{
|
||||
switch (verdict)
|
||||
{
|
||||
case UseRefusalWatch.Verdict.CleanStopAndRetry:
|
||||
{
|
||||
FlightRecorderSignal.Dump(Host, "use check: corpse opens answered but not opened");
|
||||
Log($"[RynthAi] Use check: {_useRefusals.Refusals} corpse opens in a row were answered by the server but nothing opened ({RefusedList()}) - one clean stop, a {UseRefusalWatch.CleanStopPauseMs} ms pause, then one more try.");
|
||||
Host.SetAutoRunBy("Loot/UseCheck", false);
|
||||
if (Host.HasStopCompletely)
|
||||
Host.StopCompletelyBy("Loot/UseCheck");
|
||||
_corpseAutorunActive = false;
|
||||
_corpseApproachTurnsActive = false;
|
||||
// Face the corpse for the retry. Since 2026-10-04 the bot leaves the turn to the
|
||||
// server; if the server can't turn the character any more, a corpse already in
|
||||
// front may still open (mid-stall, 06:28:19, a use by hand with the macro off
|
||||
// opened one - the only open in those 13 minutes; whether it was faced isn't logged).
|
||||
if (_targetCorpseId != 0 && Host.HasTurnToHeading
|
||||
&& TryGetHeadingToObject(_targetCorpseId, out double faceDeg, out double faceErr, out _)
|
||||
&& faceErr > 2.0)
|
||||
{
|
||||
Host.TurnToHeadingBy("Loot/UseCheck", (float)faceDeg);
|
||||
Log($"[RynthAi] Use check: facing 0x{(uint)_targetCorpseId:X8} ({faceErr:0} deg off) for the retry.");
|
||||
}
|
||||
_lootHaltUntil = Math.Max(_lootHaltUntil, now + UseRefusalWatch.CleanStopPauseMs);
|
||||
_lastCorpseOpenAttemptAt = 0; // the retry goes out as soon as the pause ends
|
||||
if (_targetCorpseId != 0)
|
||||
_corpseTargetSince = now; // and gets a full corpse timeout
|
||||
break;
|
||||
}
|
||||
case UseRefusalWatch.Verdict.DropCorpse:
|
||||
{
|
||||
int id = _useRefusals.LastRefusedCorpse;
|
||||
Log($"[RynthAi] Use check: corpse 0x{(uint)id:X8} is answered but never opens - giving up on it; the next corpse tells whether every use is refused.");
|
||||
if (id != 0 && _targetCorpseId == id && _openedContainerId == 0)
|
||||
AbandonCurrentCorpse(now, "refused");
|
||||
else if (id != 0)
|
||||
_corpseCooldownUntil[id] = now + NeverOpenedAbandonRetryMs;
|
||||
break;
|
||||
}
|
||||
case UseRefusalWatch.Verdict.Stuck:
|
||||
{
|
||||
FlightRecorderSignal.Dump(Host, "use check: server refuses every use");
|
||||
Log($"[RynthAi] Use check: the server answers every use but nothing opens ({_useRefusals.Refusals} refusals on {RefusedList()}), the clean stop and retry didn't help - looting paused {_useRefusals.BackoffMs / 60_000} min, then one corpse is tried again.");
|
||||
if (!_useStuckAnnounced)
|
||||
{
|
||||
_useStuckAnnounced = true;
|
||||
ChatLine($"[RynthAi] The server isn't letting this character use objects; a relog fixes it. Looting is paused and tried again every few minutes.");
|
||||
}
|
||||
ResetCorpseTarget();
|
||||
break;
|
||||
}
|
||||
case UseRefusalWatch.Verdict.StillStuck:
|
||||
Log($"[RynthAi] Use check: still refused - next try in {_useRefusals.BackoffMs / 60_000} min.");
|
||||
ResetCorpseTarget();
|
||||
break;
|
||||
case UseRefusalWatch.Verdict.Recovered:
|
||||
Log("[RynthAi] Use check: a corpse opened - uses work again, looting resumes.");
|
||||
if (_useStuckAnnounced)
|
||||
ChatLine("[RynthAi] Objects open again; looting is back on.");
|
||||
_useStuckAnnounced = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private string RefusedList() =>
|
||||
string.Join(", ", _useRefusals.RefusedCorpses.Select(id => $"0x{(uint)id:X8}"));
|
||||
|
||||
// The arbiter's wantLoot of the current tick (HasLootWork), for LootHoldsIdlePeace.
|
||||
private bool _lastWantLoot;
|
||||
|
||||
/// <summary>
|
||||
/// CombatManager's idle peace-mode swap waits while looting has work: a corpse to claim, a
|
||||
/// claimed or open corpse, or a door/corpse use the server is still answering. On ACE a
|
||||
/// combat-mode change cancels the server's walk/turn to a used corpse (HandleActionCancelAttack
|
||||
/// -> cancel_moveto), so the swap that went out 3 ms after the 06:18:44 open (2026-10-06) made
|
||||
/// it fail; and between kills in a busy spawn it flipped peace/war every few seconds. Opening a
|
||||
/// corpse needs no peace mode; the swap happens once looting is done.
|
||||
/// </summary>
|
||||
private bool LootHoldsIdlePeace() =>
|
||||
_targetCorpseId != 0
|
||||
|| _openedContainerId != 0
|
||||
|| _lastWantLoot
|
||||
|| RynthCore.Plugin.Shared.UseAudit.WorldUseInFlight(Host, out _);
|
||||
|
||||
/// <summary>A fresh session (logout/login): a relog is what clears a server that refuses uses.</summary>
|
||||
private void ResetUseRefusalState()
|
||||
{
|
||||
_useRefusals.Reset();
|
||||
_useStuckAnnounced = false;
|
||||
_lootWedgeAnnounced = false;
|
||||
_consecutiveLootTimeouts = 0;
|
||||
_lootHaltUntil = 0;
|
||||
}
|
||||
|
||||
private void SyncCorpseContainerState()
|
||||
|
|
@ -2542,6 +2753,11 @@ public sealed partial class RynthAiPlugin
|
|||
/// which closes the window and brings OnStopViewingObjectContents. Older engines: nothing
|
||||
/// (the server closes the corpse when the next one is opened, as before).
|
||||
/// </summary>
|
||||
// The last close sent, until the server's CloseGroundContainer answers it (see TickCorpseOpening).
|
||||
private int _closeSentFor;
|
||||
private long _closeSentAt;
|
||||
private const long CloseAnswerWaitMs = 500;
|
||||
|
||||
private void CloseCorpseContainer(int corpseId, string why)
|
||||
{
|
||||
if (corpseId == 0 || !Host.HasCloseContainer)
|
||||
|
|
@ -2553,7 +2769,11 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
|
||||
if (Host.CloseContainer(unchecked((uint)corpseId)))
|
||||
{
|
||||
_closeSentFor = corpseId;
|
||||
_closeSentAt = CorpseNowMs;
|
||||
LootDiag($"[RynthAi] Corpse loot: closing 0x{(uint)corpseId:X8} ({why}).");
|
||||
}
|
||||
else
|
||||
LootDiag($"[RynthAi] Corpse loot: close of 0x{(uint)corpseId:X8} not sent ({why}).");
|
||||
}
|
||||
|
|
@ -2583,7 +2803,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
long ageMs = _corpseTargetSince != 0 ? now - _corpseTargetSince : 0;
|
||||
LootDiag($"[RynthAi] Corpse loot: abandoning corpse 0x{(uint)corpseId:X8} after {ageMs}ms ({reason}).");
|
||||
ChatLine($"[RynthAi] Corpse timeout: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms.");
|
||||
ChatLine($"[RynthAi] Corpse {(reason == "refused" ? "refuses to open" : "timeout")}: giving up on 0x{(uint)corpseId:X8} after {ageMs}ms.");
|
||||
|
||||
// Only a corpse we actually OPENED earns the completed mark (30-min
|
||||
// do-not-touch — its loot is permanently skipped). A never-opened
|
||||
|
|
@ -2655,13 +2875,19 @@ public sealed partial class RynthAiPlugin
|
|||
/// </summary>
|
||||
private void HandleLootWedge(long now)
|
||||
{
|
||||
FlightRecorderSignal.Dump(Host, "loot wedge");
|
||||
_lootHaltUntil = now + LootWedgeHaltMs;
|
||||
_consecutiveLootTimeouts = 0; // re-arm; if still wedged it trips again after the halt
|
||||
|
||||
if (Host.HasCancelAttack) Host.CancelAttack();
|
||||
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
// Peace only when not already in it (2026-10-06): an unneeded request went to the server as
|
||||
// a raw 0x53 anyway, and on ACE a mode change cancels whatever walk/turn is pending. Not
|
||||
// while a server action is unanswered either (ChangeCombatModeFor holds it then).
|
||||
Host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot/Wedge", "loot wedge reset");
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("Loot/Wedge");
|
||||
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
// No ForceResetBusyCount (2026-10-06): AC's busy count is the count of actions the server
|
||||
// has not answered; zeroing it fixed nothing here (the lock is the server's or the
|
||||
// client's item-request gates below) and let the next action out on top of them.
|
||||
// The lock is client-side: AC's pending-item-request slot or attacking
|
||||
// flag (see the engine's ClientActionGates). Open both now.
|
||||
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc unlockactions");
|
||||
|
|
@ -2671,7 +2897,12 @@ public sealed partial class RynthAiPlugin
|
|||
if (_combatManager != null) _combatManager.BusyCount = 0;
|
||||
if (_buffManager != null) _buffManager.BusyCount = 0;
|
||||
|
||||
ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on.");
|
||||
// Once per stall (until a corpse opens): 2026-10-06 it fired 11 times in 13 minutes.
|
||||
if (!_lootWedgeAnnounced)
|
||||
{
|
||||
_lootWedgeAnnounced = true;
|
||||
ChatLine($"[RynthAi] WEDGE: {LootWedgeThreshold} corpse opens timed out — AC item-actions are locked. Halting looting {LootWedgeHaltMs / 1000}s and unlocking. If equip/loot stays stuck, /rc actionstate shows what the client is waiting on.");
|
||||
}
|
||||
Log($"[RynthAi] LOOT WEDGE detected ({LootWedgeThreshold} consecutive open timeouts) — halt {LootWedgeHaltMs}ms + reset fired.");
|
||||
}
|
||||
|
||||
|
|
@ -2707,6 +2938,10 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine($"[RynthAi] Corpse ranges: max={ConvertMetersToYards(maxMeters):F1} yd / {maxMeters:F1} m, min={ConvertMetersToYards(minMeters):F1} yd / {minMeters:F1} m");
|
||||
uint rawOpen = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0;
|
||||
ChatLine($"[RynthAi] Corpse state: target=0x{(uint)_targetCorpseId:X8}, corpse-open=0x{(uint)_openedContainerId:X8}, raw-open=0x{rawOpen:X8}, busy={_busyCount}, inv-update={(_openedContainerInventoryObservedAt != 0 ? 1 : 0)}, completed={_completedCorpses.Count}");
|
||||
long infoNow = CorpseNowMs;
|
||||
ChatLine($"[RynthAi] Use check: {_useRefusals.State}, {_useRefusals.Refusals} refused open(s) since the last open"
|
||||
+ (_useRefusals.HoldsOpens(infoNow) ? $", looting paused {(_useRefusals.BackoffUntil - infoNow) / 1000}s more (the server refuses uses; a relog fixes it)" : "")
|
||||
+ (Host.HasUseDoneSeq ? "" : " (this engine can't report the server's answers: the check is off)"));
|
||||
|
||||
if (TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out double distanceMeters))
|
||||
ChatLine($"[RynthAi] Nearest corpse: {corpse!.Name} (0x{(uint)corpse.Id:X8}) at {ConvertMetersToYards(distanceMeters):F1} yd / {distanceMeters:F1} m");
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ namespace RynthCore.Plugin.RynthAi.CreatureData;
|
|||
/// </summary>
|
||||
internal sealed class CreatureProfileStore
|
||||
{
|
||||
internal const string Folder = @"C:\Games\RynthSuite\RynthAi\CreatureData";
|
||||
internal static readonly string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "CreatureData");
|
||||
private const string FileName = "creatures.json";
|
||||
|
||||
private readonly object _lock = new();
|
||||
|
|
|
|||
|
|
@ -249,7 +249,7 @@ internal static class CreatureWeakness
|
|||
}
|
||||
|
||||
/// <summary>The on-disk copy of the weakness table next to RynthAi (optional; the DLL has one built in).</summary>
|
||||
internal const string WeaknessFile = @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json";
|
||||
internal static readonly string WeaknessFile = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Data", "creature_weakness.json");
|
||||
|
||||
// JSON keys → Elements index (the table spells Lightning "electric").
|
||||
private static readonly (string Key, int Index)[] JsonKeys =
|
||||
|
|
|
|||
|
|
@ -23,7 +23,8 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
internal static class DungeonHazardStore
|
||||
{
|
||||
// Sibling of the existing NavProfiles folder (see LegacyDashboardRenderer._navFolder).
|
||||
private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi\DungeonHazards";
|
||||
// Settable so the host tests point it at their scratch folder.
|
||||
internal static string Folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "DungeonHazards");
|
||||
|
||||
private static string PathFor(uint landblockKey)
|
||||
=> System.IO.Path.Combine(Folder, $"{landblockKey:X4}.txt");
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ namespace RynthCore.Plugin.RynthAi;
|
|||
internal static class DungeonHazardSurfaces
|
||||
{
|
||||
// Sibling of NavProfiles / DungeonHazards (LegacyDashboardRenderer._navFolder family).
|
||||
private static readonly string Folder = @"C:\Games\RynthSuite\RynthAi";
|
||||
private static readonly string Folder = RynthCore.Install.RynthInstallPaths.RynthAiDir;
|
||||
private static readonly string SetPath = System.IO.Path.Combine(Folder, "HazardTextures.txt");
|
||||
|
||||
private static readonly object _gate = new();
|
||||
|
|
|
|||
28
Plugins/RynthCore.Plugin.RynthAi/FlightRecorderSignal.cs
Normal file
28
Plugins/RynthCore.Plugin.RynthAi/FlightRecorderSignal.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
using System;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// Asks the engine's flight recorder (RynthCore Net/FlightRecorder.cs, 2026-10-06) to write its
|
||||
/// buffer: the last minutes of client/server messages and engine markers. Called where RynthAi
|
||||
/// notices a stall (LOOT WEDGE, the use-refusal check, a held-cast nudge), so the dump holds
|
||||
/// the message sequence that led into it. The engine writes at most one automatic dump per
|
||||
/// 10 minutes, so calling this often is harmless. Uses the plugin-command broker (API v64)
|
||||
/// with a name the engine reserves; an engine without the recorder finds no such plugin and
|
||||
/// nothing happens. Never throws.
|
||||
/// </summary>
|
||||
internal static class FlightRecorderSignal
|
||||
{
|
||||
public const string Target = "RynthCore.FlightRecorder";
|
||||
|
||||
public static void Dump(RynthCoreHost host, string reason)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (host.HasSendPluginCommand)
|
||||
host.SendPluginCommand(Target, "dump", "RynthAi " + reason);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
308
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs
Normal file
308
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/ItemInfoText.cs
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using RynthCore.Loot.Editing;
|
||||
using RynthCore.Plugin.RynthAi.CreatureData;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
/// <summary>One item's appraisal values, as <see cref="ItemInfoText"/> reads them.</summary>
|
||||
internal interface IItemInfoSource
|
||||
{
|
||||
/// <summary>The name the client shows ("" when unknown).</summary>
|
||||
string Name { get; }
|
||||
bool TryInt(uint key, out int value);
|
||||
bool TryFloat(uint key, out double value);
|
||||
/// <summary>The item's spells (empty when none or not appraised).</summary>
|
||||
IReadOnlyList<int> SpellIds { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /ra iteminfo's text: one item on one chat line, in the spirit of Mag-Tools' item info
|
||||
/// (name, type, set, armor, ratings, damage and mods, imbues, slayer, tinks, spells by name,
|
||||
/// wield and activation requirements, craft, material, value and burden). A field the
|
||||
/// appraisal doesn't carry is left out. Pure: no host calls, so the host tests feed it a
|
||||
/// fake source.
|
||||
/// </summary>
|
||||
internal static class ItemInfoText
|
||||
{
|
||||
// STypeInt (AC / ACE PropertyInt numbering; the names in Meta/PropertyNames.cs).
|
||||
internal const uint IntItemType = 1, IntEncumbrance = 5, IntStackSize = 12, IntRareId = 17, IntValue = 19,
|
||||
IntArmorLevel = 28, IntBonded = 33, IntDamage = 44, IntDamageType = 45, IntWeaponSkill = 48,
|
||||
IntWeaponTime = 49, IntWorkmanship = 105, IntSpellcraft = 106, IntCurMana = 107, IntMaxMana = 108,
|
||||
IntItemDifficulty = 109, IntAllegianceRankLimit = 110, IntAttuned = 114, IntSkillLevelLimit = 115,
|
||||
IntMaterial = 131, IntWieldReq = 158, IntWieldSkill = 159, IntWieldDiff = 160, IntSlayerType = 166,
|
||||
IntTinks = 171, IntImbued = 179, IntElementalBonus = 204, IntSetId = 265, IntWieldReq2 = 270,
|
||||
IntWieldSkill2 = 271, IntWieldDiff2 = 272, IntItemMaxLevel = 319;
|
||||
|
||||
// STypeFloat (ACE PropertyFloat numbering).
|
||||
internal const uint FloatDamageVariance = 22, FloatMeleeDefense = 29, FloatWeaponOffense = 62, FloatDamageMod = 63,
|
||||
FloatManaConversion = 144, FloatMissileDefense = 149, FloatMagicDefense = 150, FloatElementalDamage = 152;
|
||||
|
||||
/// <summary>Gear ratings (STypeInt 370-389) and their short tags, in print order.</summary>
|
||||
internal static readonly (uint Key, string Tag)[] Ratings =
|
||||
{
|
||||
(370, "D"), (371, "DR"), (372, "C"), (373, "CR"), (374, "CD"), (375, "CDR"),
|
||||
(376, "HB"), (379, "Vit"), (377, "NR"), (378, "LR"), (388, "OP"), (389, "OPR"),
|
||||
(383, "PvP D"), (384, "PvP DR"),
|
||||
};
|
||||
|
||||
// ItemType flags (STypeInt 1), most specific first.
|
||||
private static readonly (uint Flag, string Name)[] Types =
|
||||
{
|
||||
(0x00040000, "Promissory Note"), (0x00080000, "Mana Stone"), (0x00001000, "Spell Component"),
|
||||
(0x00000800, "Gem"), (0x00004000, "Key"), (0x40000000, "Salvage"), (0x20000000, "Tinkering Tool"),
|
||||
(0x00000200, "Container"), (0x00008000, "Caster"), (0x00000100, "Missile Weapon"),
|
||||
(0x00000001, "Melee Weapon"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"),
|
||||
(0x00000020, "Food"), (0x00000040, "Money"), (0x00002000, "Writable"), (0x00000080, "Misc"),
|
||||
};
|
||||
|
||||
// ImbuedEffect flags (STypeInt 179).
|
||||
private static readonly (uint Flag, string Name)[] Imbues =
|
||||
{
|
||||
(0x0001, "Critical Strike"), (0x0002, "Crippling Blow"), (0x0004, "Armor Rending"),
|
||||
(0x0008, "Slash Rending"), (0x0010, "Pierce Rending"), (0x0020, "Bludgeon Rending"),
|
||||
(0x0040, "Acid Rending"), (0x0080, "Cold Rending"), (0x0100, "Lightning Rending"),
|
||||
(0x0200, "Fire Rending"), (0x0400, "Melee Defense"), (0x0800, "Missile Defense"),
|
||||
(0x1000, "Magic Defense"), (0x4000, "Nether Rending"),
|
||||
};
|
||||
|
||||
// Equipment sets (STypeInt 265) whose ids are certain: the loot armor sets and Aetheria.
|
||||
private static readonly Dictionary<int, string> Sets = new()
|
||||
{
|
||||
[13] = "Soldier's", [14] = "Adept's", [15] = "Archer's", [16] = "Defender's", [17] = "Tinker's",
|
||||
[18] = "Crafter's", [19] = "Hearty", [20] = "Dexterous", [21] = "Wise", [22] = "Swift",
|
||||
[23] = "Hardened", [24] = "Reinforced", [25] = "Interlocking", [26] = "Flame Proof",
|
||||
[27] = "Acid Proof", [28] = "Cold Proof", [29] = "Lightning Proof",
|
||||
[35] = "Aetheria: Defense", [36] = "Aetheria: Destruction", [37] = "Aetheria: Fury",
|
||||
[38] = "Aetheria: Growth", [39] = "Aetheria: Vigor",
|
||||
};
|
||||
|
||||
// Attributes and vitals for attribute/vital wield requirements (ACE PropertyAttribute / PropertyAttribute2nd).
|
||||
private static readonly string[] Attributes = { "", "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" };
|
||||
private static readonly string[] Vitals = { "", "Max Health", "Health", "Max Stamina", "Stamina", "Max Mana", "Mana" };
|
||||
|
||||
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
|
||||
|
||||
/// <summary>
|
||||
/// The item on one line. <paramref name="spellName"/> names a spell id (the plugin's
|
||||
/// spell table). <paramref name="identified"/> false adds a note that the server never
|
||||
/// answered the ID, so only what the client already knew is shown.
|
||||
/// </summary>
|
||||
public static string Describe(IItemInfoSource item, Func<int, string> spellName, bool identified = true)
|
||||
{
|
||||
var parts = new List<string>(24);
|
||||
int type = Int(item, IntItemType);
|
||||
|
||||
// Name, with the material in front the way the game names loot ("Gold Ring").
|
||||
string name = item.Name.Trim();
|
||||
int material = Int(item, IntMaterial);
|
||||
string full = WeaponNames.Full(name, material);
|
||||
if (full.Length == 0) full = "(unnamed item)";
|
||||
string typeName = TypeName(type);
|
||||
int stack = Int(item, IntStackSize);
|
||||
var head = new StringBuilder(full);
|
||||
if (stack > 1) head.Append(" x").Append(stack.ToString("N0", Inv));
|
||||
if (typeName.Length > 0) head.Append(" (").Append(typeName).Append(')');
|
||||
parts.Add(head.ToString());
|
||||
|
||||
if (Int(item, IntSetId) is int set and > 0)
|
||||
parts.Add((Sets.TryGetValue(set, out string? setName) ? setName : "Set " + set) + " Set");
|
||||
|
||||
if (item.TryInt(IntArmorLevel, out int al) && (al > 0 || (type & 0x2) != 0))
|
||||
parts.Add("AL " + al.ToString(Inv));
|
||||
|
||||
string ratings = RatingText(item);
|
||||
if (ratings.Length > 0) parts.Add(ratings);
|
||||
|
||||
AddWeapon(item, type, parts);
|
||||
|
||||
string imbues = ImbueText(Int(item, IntImbued));
|
||||
if (imbues.Length > 0) parts.Add(imbues);
|
||||
|
||||
if (Int(item, IntSlayerType) is int slayer and > 0)
|
||||
parts.Add(CreatureTypeNames.Name(slayer) + " Slayer");
|
||||
|
||||
if (item.TryInt(IntTinks, out int tinks) && tinks > 0)
|
||||
parts.Add("Tinks " + tinks.ToString(Inv));
|
||||
|
||||
string spells = SpellText(item.SpellIds, spellName);
|
||||
if (spells.Length > 0) parts.Add(spells);
|
||||
|
||||
string wield = WieldText(item, IntWieldReq, IntWieldSkill, IntWieldDiff);
|
||||
if (wield.Length > 0) parts.Add(wield);
|
||||
string wield2 = WieldText(item, IntWieldReq2, IntWieldSkill2, IntWieldDiff2);
|
||||
if (wield2.Length > 0) parts.Add(wield2);
|
||||
|
||||
if (Int(item, IntSkillLevelLimit) is int skillLimit and > 0) parts.Add("Skill " + skillLimit.ToString(Inv) + " to activate");
|
||||
if (Int(item, IntAllegianceRankLimit) is int rank and > 0) parts.Add("Rank " + rank.ToString(Inv));
|
||||
if (Int(item, IntItemDifficulty) is int diff and > 0) parts.Add("Diff " + diff.ToString(Inv));
|
||||
if (Int(item, IntSpellcraft) is int spellcraft and > 0) parts.Add("Spellcraft " + spellcraft.ToString(Inv));
|
||||
if (item.TryInt(IntMaxMana, out int maxMana) && maxMana > 0)
|
||||
parts.Add("Mana " + (item.TryInt(IntCurMana, out int cur) ? cur.ToString(Inv) + "/" : "") + maxMana.ToString(Inv));
|
||||
if (Int(item, IntItemMaxLevel) is int maxLevel and > 0) parts.Add("Max Level " + maxLevel.ToString(Inv));
|
||||
|
||||
if (item.TryInt(IntWorkmanship, out int craft) && craft > 0) parts.Add("Craft " + craft.ToString(Inv));
|
||||
string matName = WeaponNames.Material(material);
|
||||
if (matName.Length > 0) parts.Add("Mat " + matName);
|
||||
|
||||
if (Int(item, IntBonded) == 1) parts.Add("Bonded");
|
||||
if (Int(item, IntAttuned) == 1) parts.Add("Attuned");
|
||||
if (Int(item, IntRareId) is int rare and > 0) parts.Add("Rare #" + rare.ToString(Inv));
|
||||
|
||||
if (item.TryInt(IntValue, out int value)) parts.Add("Value " + value.ToString("N0", Inv));
|
||||
if (item.TryInt(IntEncumbrance, out int burden)) parts.Add("BU " + burden.ToString("N0", Inv));
|
||||
|
||||
if (!identified) parts.Add("(not identified: no reply from the server)");
|
||||
return string.Join(", ", parts);
|
||||
}
|
||||
|
||||
private static int Int(IItemInfoSource item, uint key) => item.TryInt(key, out int v) ? v : 0;
|
||||
|
||||
/// <summary>The item's kind from its ItemType flags ("" when none is set).</summary>
|
||||
internal static string TypeName(int itemType)
|
||||
{
|
||||
uint t = unchecked((uint)itemType);
|
||||
foreach (var (flag, n) in Types)
|
||||
if ((t & flag) != 0) return n;
|
||||
return "";
|
||||
}
|
||||
|
||||
/// <summary>"[D3 CD2 CDR1]" for the gear ratings that are set; "" for none.</summary>
|
||||
internal static string RatingText(IItemInfoSource item)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (var (key, tag) in Ratings)
|
||||
{
|
||||
if (!item.TryInt(key, out int r) || r <= 0) continue;
|
||||
sb.Append(sb.Length == 0 ? "[" : " ").Append(tag).Append(r.ToString(Inv));
|
||||
}
|
||||
return sb.Length == 0 ? "" : sb.Append(']').ToString();
|
||||
}
|
||||
|
||||
private static void AddWeapon(IItemInfoSource item, int type, List<string> parts)
|
||||
{
|
||||
uint t = unchecked((uint)type);
|
||||
bool melee = (t & 0x1) != 0, missile = (t & 0x100) != 0, caster = (t & 0x8000) != 0;
|
||||
bool weapon = melee || missile || caster;
|
||||
|
||||
if (Int(item, IntWeaponSkill) is int skill and > 0 && weapon)
|
||||
parts.Add(SkillName(skill));
|
||||
|
||||
int dmgType = Int(item, IntDamageType);
|
||||
if (item.TryInt(IntDamage, out int max) && max > 0)
|
||||
{
|
||||
string dmg = "Dmg " + max.ToString(Inv);
|
||||
if (item.TryFloat(FloatDamageVariance, out double variance) && variance > 0 && variance < 1)
|
||||
{
|
||||
int min = (int)Math.Round(max * (1.0 - variance), MidpointRounding.AwayFromZero);
|
||||
dmg = $"Dmg {min.ToString(Inv)}-{max.ToString(Inv)}";
|
||||
}
|
||||
string element = DamageTypeName(dmgType);
|
||||
if (element.Length > 0) dmg += " " + element;
|
||||
parts.Add(dmg);
|
||||
}
|
||||
else if (weapon && dmgType > 0)
|
||||
{
|
||||
string element = DamageTypeName(dmgType);
|
||||
if (element.Length > 0) parts.Add(element);
|
||||
}
|
||||
if (Int(item, IntElementalBonus) is int elemBonus and > 0) parts.Add("+" + elemBonus.ToString(Inv) + " elemental dmg");
|
||||
if (weapon && item.TryInt(IntWeaponTime, out int speed) && speed > 0) parts.Add("Speed " + speed.ToString(Inv));
|
||||
|
||||
// Modifiers: 1.18 = +18%. Missile launchers' damage mod and casters' elemental mod too.
|
||||
var mods = new List<string>(6);
|
||||
AddPercent(item, FloatWeaponOffense, "atk", mods, weapon);
|
||||
if (missile) AddPercent(item, FloatDamageMod, "dmg", mods, true);
|
||||
if (caster) AddPercent(item, FloatElementalDamage, "vs monsters", mods, true);
|
||||
AddPercent(item, FloatMeleeDefense, "md", mods, weapon);
|
||||
AddPercent(item, FloatMissileDefense, "mid", mods, weapon);
|
||||
AddPercent(item, FloatMagicDefense, "mgd", mods, weapon);
|
||||
AddPercent(item, FloatManaConversion, "mana c", mods, true);
|
||||
if (mods.Count > 0) parts.Add("(" + string.Join(", ", mods) + ")");
|
||||
}
|
||||
|
||||
private static void AddPercent(IItemInfoSource item, uint key, string label, List<string> mods, bool allowed)
|
||||
{
|
||||
if (!allowed || !item.TryFloat(key, out double v) || double.IsNaN(v)) return;
|
||||
// Multipliers (attack, defense, damage) are stored as 1.xx; mana conversion as 0.xx.
|
||||
double pct = key == FloatManaConversion ? v * 100.0 : (v - 1.0) * 100.0;
|
||||
int rounded = (int)Math.Round(pct, MidpointRounding.AwayFromZero);
|
||||
if (rounded == 0) return;
|
||||
mods.Add((rounded > 0 ? "+" : "") + rounded.ToString(Inv) + "% " + label);
|
||||
}
|
||||
|
||||
/// <summary>"Crippling Blow, Fire Rending" for the imbue flags; "" for none.</summary>
|
||||
internal static string ImbueText(int flags)
|
||||
{
|
||||
if (flags == 0) return "";
|
||||
uint f = unchecked((uint)flags);
|
||||
var names = new List<string>(2);
|
||||
foreach (var (flag, n) in Imbues)
|
||||
if ((f & flag) != 0) names.Add(n);
|
||||
return string.Join(", ", names);
|
||||
}
|
||||
|
||||
/// <summary>"Spells: A, B, C" by name, in the item's order, each once; "" for none.</summary>
|
||||
internal static string SpellText(IReadOnlyList<int> spellIds, Func<int, string> spellName)
|
||||
{
|
||||
if (spellIds.Count == 0) return "";
|
||||
var seen = new HashSet<int>();
|
||||
var names = new List<string>(spellIds.Count);
|
||||
foreach (int id in spellIds)
|
||||
{
|
||||
if (id <= 0 || !seen.Add(id)) continue;
|
||||
string n = spellName(id);
|
||||
names.Add(string.IsNullOrWhiteSpace(n) ? "spell " + id.ToString(Inv) : n);
|
||||
}
|
||||
return names.Count == 0 ? "" : "Spells: " + string.Join(", ", names);
|
||||
}
|
||||
|
||||
/// <summary>One wield requirement ("Wield Lvl 180", "Heavy Weapons 375 to wield"); "" for none.</summary>
|
||||
internal static string WieldText(IItemInfoSource item, uint reqKey, uint skillKey, uint diffKey)
|
||||
{
|
||||
int req = Int(item, reqKey);
|
||||
if (req <= 0) return "";
|
||||
int skill = Int(item, skillKey);
|
||||
int diff = Int(item, diffKey);
|
||||
string d = diff.ToString(Inv);
|
||||
return req switch
|
||||
{
|
||||
1 => $"{SkillName(skill)} {d} to wield",
|
||||
2 => $"Base {SkillName(skill)} {d} to wield",
|
||||
3 => $"{Pick(Attributes, skill, "Attribute")} {d} to wield",
|
||||
4 => $"Base {Pick(Attributes, skill, "Attribute")} {d} to wield",
|
||||
5 => $"{Pick(Vitals, skill, "Vital")} {d} to wield",
|
||||
6 => $"Base {Pick(Vitals, skill, "Vital")} {d} to wield",
|
||||
7 => $"Wield Lvl {d}",
|
||||
8 => $"{(diff >= 3 ? "Specialized" : "Trained")} {SkillName(skill)} to wield",
|
||||
12 => $"Heritage {d} to wield",
|
||||
_ => $"Wield requirement {req.ToString(Inv)} ({skill.ToString(Inv)}, {d})",
|
||||
};
|
||||
}
|
||||
|
||||
private static string Pick(string[] names, int i, string fallback) =>
|
||||
i > 0 && i < names.Length ? names[i] : $"{fallback} {i.ToString(Inv)}";
|
||||
|
||||
/// <summary>AC's skill name for a skill id ("skill N" when unknown).</summary>
|
||||
internal static string SkillName(int id)
|
||||
{
|
||||
foreach (var (sid, n) in LootRuleText.Skills)
|
||||
if (sid == id) return n;
|
||||
return "skill " + id.ToString(Inv);
|
||||
}
|
||||
|
||||
/// <summary>The damage type's name ("Slashing/Piercing" etc.); "" for none.</summary>
|
||||
internal static string DamageTypeName(int flags)
|
||||
{
|
||||
if (flags <= 0) return "";
|
||||
foreach (var (id, n) in LootRuleText.DamageTypes)
|
||||
if (id == flags) return n;
|
||||
// Other combinations: the single flags joined.
|
||||
var names = new List<string>(3);
|
||||
foreach (var (id, n) in LootRuleText.DamageTypes)
|
||||
if (id > 0 && (id & (id - 1)) == 0 && (flags & id) != 0) names.Add(n);
|
||||
return string.Join("/", names);
|
||||
}
|
||||
}
|
||||
27
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs
Normal file
27
Plugins/RynthCore.Plugin.RynthAi/ItemInfo/SelfSelect.cs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
|
||||
/// <summary>
|
||||
/// Items RynthAi selects by itself (the looter picking an item up, a meta's selectitem), so the
|
||||
/// selection-change handler can tell them from the player's own clicks: Item Info on select
|
||||
/// prints only for the player's. <see cref="Mark"/> goes right before Host.SelectItem.
|
||||
/// </summary>
|
||||
internal static class SelfSelect
|
||||
{
|
||||
/// <summary>A selection change this soon after <see cref="Mark"/>, for the same id, is ours.</summary>
|
||||
internal const long WindowMs = 2000;
|
||||
|
||||
internal static Func<long> Clock = () => Environment.TickCount64;
|
||||
|
||||
private static uint _id;
|
||||
private static long _at;
|
||||
|
||||
internal static void Mark(uint id)
|
||||
{
|
||||
_at = Clock();
|
||||
_id = id;
|
||||
}
|
||||
|
||||
internal static bool IsOurs(uint id) => id != 0 && id == _id && Clock() - _at <= WindowMs;
|
||||
}
|
||||
|
|
@ -13,6 +13,7 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
private string _newBlacklistName = "";
|
||||
|
||||
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
|
||||
private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" };
|
||||
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
|
||||
|
||||
public LegacyAdvancedSettingsUi(LegacyUiSettings settings)
|
||||
|
|
@ -564,7 +565,7 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.InputFloat("Nav point reach (yd)", ref _settings.FollowNavMin, 0.1f, 1.0f, "%.1f");
|
||||
_settings.FollowNavMin = LegacyUiSettings.ClampFollowNavMin(_settings.FollowNavMin);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Follow stops this close to its leader; the nav marker ring shows it.");
|
||||
ImGui.SetTooltip("How close to get to each nav point before moving on to the next (yards). VTank calls it Follow/Nav Min Distance. Up to 2 nav walks right up to each point before turning (tight dungeons); bigger values round corners. Follow stops this close to its leader; the nav marker ring shows it.");
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Text("Nav Marker Display");
|
||||
|
|
@ -584,6 +585,11 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.Checkbox("Show Terrain Passability", ref _settings.ShowTerrainPassability);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Highlight impassable terrain triangles in red.");
|
||||
ImGui.SetNextItemWidth(160);
|
||||
ImGui.Combo("Waypoint Labels", ref _settings.NavLabelMode, NavLabelModeNames, NavLabelModeNames.Length);
|
||||
ImGui.Checkbox("Guide Line", ref _settings.NavGuideLine);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("A line from your character to the waypoint nav is heading for.");
|
||||
|
||||
ImGui.Spacing();
|
||||
ImGui.Separator();
|
||||
|
|
@ -654,7 +660,7 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.InputFloat("Lookahead (yd)", ref _settings.NavLookaheadYards, 0.5f, 1f, "%.1f");
|
||||
if (_settings.NavLookaheadYards < 0f) _settings.NavLookaheadYards = 0f;
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint).");
|
||||
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to round corners. The nav point reach limits it to 2 yd per yard of reach over 1 yd (no rounding up to a 2 yd reach), never more than this. 0 = off (aim straight at each waypoint).");
|
||||
|
||||
ImGui.SetNextItemWidth(80);
|
||||
ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f");
|
||||
|
|
@ -767,6 +773,9 @@ internal sealed class LegacyAdvancedSettingsUi
|
|||
ImGui.Checkbox("Recover My Corpse", ref _settings.LootOwnCorpse);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("When your own corpse (\"Corpse of <you>\") is within loot range, open it and take\nevery item on it, whatever the loot profile and Loot From say.");
|
||||
ImGui.Checkbox("Item Info On Select", ref _settings.ItemInfoOnSelect);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("Selecting an item prints its details to chat (/ra iteminfo).");
|
||||
ImGui.Checkbox("Travel Back To My Corpse", ref _settings.TravelToOwnCorpse);
|
||||
if (ImGui.IsItemHovered())
|
||||
ImGui.SetTooltip("After a death, travel back to where you died with RynthNav (outdoors only),\nfighting on the way, recover the corpse, then carry on. Needs the macro running.");
|
||||
|
|
|
|||
|
|
@ -60,16 +60,16 @@ internal sealed class LegacyDashboardRenderer
|
|||
// escaped the snapshot poll's reverse-P/Invoke boundary it fail-fasted the
|
||||
// NativeAOT runtime. Copy-under-lock on read; lock the Clear+AddRange swap.
|
||||
private readonly object _profileListsLock = new();
|
||||
private readonly string _navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
|
||||
private readonly string _lootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
private readonly string _metaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
|
||||
private readonly string _navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
private readonly string _lootFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
private readonly string _metaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
|
||||
// Profiles are kept per server: SettingsProfiles\<server>\<character> and
|
||||
// MonsterProfiles\<server>\<character>.json, the server being the world name
|
||||
// the server sends at login. Before 2026-09-28 every server shared
|
||||
// SettingsProfiles\ACEmulator, so the same character name on two servers
|
||||
// shared one profile; that folder is still used when no name is known.
|
||||
private const string ProfilesBase = @"C:\Games\RynthSuite\RynthAi\SettingsProfiles";
|
||||
private const string MonstersBase = @"C:\Games\RynthSuite\RynthAi\MonsterProfiles";
|
||||
private static readonly string ProfilesBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "SettingsProfiles");
|
||||
private static readonly string MonstersBase = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MonsterProfiles");
|
||||
private const string LegacyServerFolder = "ACEmulator";
|
||||
private string _serverFolder = LegacyServerFolder;
|
||||
private string _settingsRoot => Path.Combine(ProfilesBase, _serverFolder);
|
||||
|
|
@ -113,7 +113,8 @@ internal sealed class LegacyDashboardRenderer
|
|||
private DateTime _sessionStartUtc = DateTime.UtcNow;
|
||||
private long _sessionKills; // Interlocked: incremented on the pump thread, read in the snapshot
|
||||
private double _killsPerHour;
|
||||
private long _lastKillTicks; // DateTime.UtcNow.Ticks of the last kill (0 = none yet this session)
|
||||
/// <summary>The plugin's kill clock (secsSinceLastKill); set once at plugin init.</summary>
|
||||
internal KillClock? KillClock { get; set; }
|
||||
// volatile: written on the pump thread (SetFreeSlots/SetComponentCounts), read on the snapshot-poll
|
||||
// thread (BuildSnapshotJson). x86 int writes are atomic but give no visibility guarantee — without
|
||||
// volatile the reader can see a stale value indefinitely. (_sessionKills uses Interlocked for the same reason.)
|
||||
|
|
@ -1009,6 +1010,8 @@ internal sealed class LegacyDashboardRenderer
|
|||
NavHeightOffset = s.NavHeightOffset,
|
||||
NavSlopeSink = s.NavSlopeSink,
|
||||
ShowTerrainPassability = s.ShowTerrainPassability,
|
||||
NavLabelMode = NavLabelModes.Clamp(s.NavLabelMode),
|
||||
NavGuideLine = s.NavGuideLine,
|
||||
OpenDoors = s.OpenDoors,
|
||||
OpenDoorRange = s.OpenDoorRange,
|
||||
AutoUnlockDoors = s.AutoUnlockDoors,
|
||||
|
|
@ -1056,6 +1059,7 @@ internal sealed class LegacyDashboardRenderer
|
|||
LootOwnership = s.LootOwnership,
|
||||
LootOwnCorpse = s.LootOwnCorpse,
|
||||
TravelToOwnCorpse = s.TravelToOwnCorpse,
|
||||
ItemInfoOnSelect = s.ItemInfoOnSelect,
|
||||
EnableAutostack = s.EnableAutostack,
|
||||
ReadUnknownScrolls = s.ReadUnknownScrolls,
|
||||
EnableCombineSalvage = s.EnableCombineSalvage,
|
||||
|
|
@ -1212,6 +1216,8 @@ internal sealed class LegacyDashboardRenderer
|
|||
s.NavHeightOffset = p.NavHeightOffset;
|
||||
s.NavSlopeSink = p.NavSlopeSink;
|
||||
s.ShowTerrainPassability = p.ShowTerrainPassability;
|
||||
if (p.NavLabelMode >= 0) s.NavLabelMode = NavLabelModes.Clamp(p.NavLabelMode);
|
||||
if (p.NavGuideLine is bool guideLine) s.NavGuideLine = guideLine;
|
||||
s.OpenDoors = p.OpenDoors;
|
||||
s.OpenDoorRange = p.OpenDoorRange;
|
||||
s.AutoUnlockDoors = p.AutoUnlockDoors;
|
||||
|
|
@ -1256,6 +1262,7 @@ internal sealed class LegacyDashboardRenderer
|
|||
s.LootOwnership = p.LootOwnership;
|
||||
if (p.LootOwnCorpse is bool lootOwn) s.LootOwnCorpse = lootOwn; // absent = unchanged
|
||||
if (p.TravelToOwnCorpse is bool travelOwn) s.TravelToOwnCorpse = travelOwn; // absent = unchanged
|
||||
if (p.ItemInfoOnSelect is bool infoOnSelect) s.ItemInfoOnSelect = infoOnSelect; // absent = unchanged
|
||||
s.EnableAutostack = p.EnableAutostack;
|
||||
s.ReadUnknownScrolls = p.ReadUnknownScrolls;
|
||||
s.EnableCombineSalvage = p.EnableCombineSalvage;
|
||||
|
|
@ -1657,6 +1664,7 @@ internal sealed class LegacyDashboardRenderer
|
|||
dst.LootOwnership = tmp.LootOwnership;
|
||||
dst.LootOwnCorpse = tmp.LootOwnCorpse;
|
||||
dst.TravelToOwnCorpse = tmp.TravelToOwnCorpse;
|
||||
dst.ItemInfoOnSelect = tmp.ItemInfoOnSelect;
|
||||
dst.LootOnlyRareCorpses = tmp.LootOnlyRareCorpses;
|
||||
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
|
||||
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
|
||||
|
|
@ -1759,6 +1767,8 @@ internal sealed class LegacyDashboardRenderer
|
|||
dst.PatrolOnLogin = tmp.PatrolOnLogin;
|
||||
dst.YieldToVTank = tmp.YieldToVTank;
|
||||
dst.ShowTerrainPassability = tmp.ShowTerrainPassability;
|
||||
dst.NavLabelMode = NavLabelModes.Clamp(tmp.NavLabelMode);
|
||||
dst.NavGuideLine = tmp.NavGuideLine;
|
||||
dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs;
|
||||
dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs;
|
||||
dst.AttackSpellIntervalMs = tmp.AttackSpellIntervalMs;
|
||||
|
|
@ -1891,15 +1901,13 @@ internal sealed class LegacyDashboardRenderer
|
|||
{
|
||||
_sessionStartUtc = DateTime.UtcNow;
|
||||
System.Threading.Interlocked.Exchange(ref _sessionKills, 0);
|
||||
System.Threading.Interlocked.Exchange(ref _lastKillTicks, 0);
|
||||
}
|
||||
|
||||
/// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour
|
||||
/// and the "time since last kill" liveness signal.
|
||||
/// Called from the plugin's OnKillNotification (pump thread) for each kill — feeds kills/hour.
|
||||
/// The "time since last kill" signal is the plugin's KillClock.
|
||||
public void RecordKill()
|
||||
{
|
||||
System.Threading.Interlocked.Increment(ref _sessionKills);
|
||||
System.Threading.Interlocked.Exchange(ref _lastKillTicks, DateTime.UtcNow.Ticks);
|
||||
}
|
||||
|
||||
/// Pushed from the plugin tick (it owns the inventory cache) — main-pack empty slots. -1 = unknown.
|
||||
|
|
@ -2087,6 +2095,30 @@ internal sealed class LegacyDashboardRenderer
|
|||
_selectedNavIdx = sel;
|
||||
}
|
||||
|
||||
private DateTime _navFolderStamp;
|
||||
private long _nextNavFolderCheckMs;
|
||||
|
||||
/// <summary>
|
||||
/// Lists NavProfiles again when the folder changed since the last look (a route saved there by
|
||||
/// RynthNav's "save as nav route", or a file copied in), so the Nav picker shows it without a
|
||||
/// relog. One folder time check every 3 s. Plugin tick.
|
||||
/// </summary>
|
||||
public void TickNavFolder()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (now < _nextNavFolderCheckMs) return;
|
||||
_nextNavFolderCheckMs = now + 3000;
|
||||
try
|
||||
{
|
||||
DateTime stamp = Directory.Exists(_navFolder) ? Directory.GetLastWriteTimeUtc(_navFolder) : DateTime.MinValue;
|
||||
if (stamp == _navFolderStamp) return;
|
||||
bool first = _navFolderStamp == default;
|
||||
_navFolderStamp = stamp;
|
||||
if (!first) RefreshNavFiles();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>Save button and /ra nav save [name]. Returns the chat line.</summary>
|
||||
public string SaveRoute(string? name)
|
||||
{
|
||||
|
|
@ -2519,11 +2551,8 @@ internal sealed class LegacyDashboardRenderer
|
|||
// (kill counter + inventory cache); the rest of the player stats are engine top-level.
|
||||
AppendFloat(sb, "killsPerHour", (float)_killsPerHour); sb.Append(',');
|
||||
AppendInt(sb, "sessionKills", (int)System.Threading.Interlocked.Read(ref _sessionKills)); sb.Append(',');
|
||||
long lastKillTicks = System.Threading.Interlocked.Read(ref _lastKillTicks);
|
||||
int secsSinceLastKill = lastKillTicks == 0
|
||||
? -1
|
||||
: (int)Math.Clamp((DateTime.UtcNow - new DateTime(lastKillTicks, DateTimeKind.Utc)).TotalSeconds, 0, int.MaxValue);
|
||||
AppendInt(sb, "secsSinceLastKill", secsSinceLastKill); sb.Append(',');
|
||||
// -1 before the first kill this session (the plugin's KillClock, reset at login).
|
||||
AppendInt(sb, "secsSinceLastKill", KillClock?.SecondsSinceKillOnly() ?? -1); sb.Append(',');
|
||||
AppendInt(sb, "freeSlots", _freeSlots); sb.Append(',');
|
||||
// D2 three-tier target telemetry + D6 attack-cast/kill ratio (orphan early-warning).
|
||||
AppendInt(sb, "scanTotal", _scanTotal); sb.Append(',');
|
||||
|
|
@ -2732,7 +2761,7 @@ internal sealed class LegacyDashboardRenderer
|
|||
|
||||
// ── Meta bridge ───────────────────────────────────────────────────────────
|
||||
|
||||
private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
|
||||
private static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
|
||||
|
||||
// Result of the last set_source, reported in BuildMetaJson (under MetaRulesLock).
|
||||
private long _metaApplySeq;
|
||||
|
|
@ -2993,11 +3022,10 @@ internal sealed class LegacyDashboardRenderer
|
|||
break;
|
||||
|
||||
case "update_rule":
|
||||
if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count)
|
||||
{
|
||||
_settings.MetaRules[cmd.Index] = DtoToMetaRule(cmd.Rule);
|
||||
// The engine's editor saves every change (2026-10-05): keep the running rule's
|
||||
// latch (no re-fire) and the fields the panel can't send (MetaRuleEdits).
|
||||
if (cmd.Rule != null && MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule)))
|
||||
TryAutoSaveMetaCmd();
|
||||
}
|
||||
break;
|
||||
|
||||
case "delete_rule":
|
||||
|
|
@ -3028,7 +3056,9 @@ internal sealed class LegacyDashboardRenderer
|
|||
case "duplicate_rule":
|
||||
if (cmd.Rule != null && cmd.Index >= 0 && cmd.Index < _settings.MetaRules.Count)
|
||||
{
|
||||
_settings.MetaRules.Insert(cmd.Index + 1, DtoToMetaRule(cmd.Rule));
|
||||
var copy = DtoToMetaRule(cmd.Rule);
|
||||
MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours
|
||||
_settings.MetaRules.Insert(cmd.Index + 1, copy);
|
||||
TryAutoSaveMetaCmd();
|
||||
}
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ internal sealed class LegacyMetaUi
|
|||
private string _statusMessage = "";
|
||||
private DateTime _statusTime = DateTime.MinValue;
|
||||
|
||||
private static readonly string MetaFolder = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
|
||||
private static readonly string MetaFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
|
||||
|
||||
/// <summary>Warnings from the most recent LoadMacroFile, so the Avalonia
|
||||
/// bridge can surface them too (it doesn't see the LoadedMeta).</summary>
|
||||
|
|
@ -698,6 +698,9 @@ internal sealed class LegacyMetaUi
|
|||
case MetaConditionType.VitaePHE:
|
||||
condHint = "Vitae penalty % (e.g. 5)";
|
||||
break;
|
||||
case MetaConditionType.NoKillsWithinMinutes:
|
||||
condHint = "Minutes without a kill (e.g. 5 or 2.5)";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ public sealed class LegacyUiSettings
|
|||
public float NavResumeTurnAngle = 10f;
|
||||
public float NavDeadZone = 4f;
|
||||
public float NavSweepMult = 2.5f;
|
||||
public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off)
|
||||
public float NavLookaheadYards = 4.0f; // most the aim point is blended toward the next waypoint (0 = off); the nav point reach scales it down (NavigationEngine.CornerLookaheadYards)
|
||||
public float NavShortcutYards = 1.0f; // on arrival, skip waypoints only while the straight run to a later one stays within this of every skipped point (0 = visit every point)
|
||||
public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate
|
||||
public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate)
|
||||
|
|
@ -167,6 +167,11 @@ public sealed class LegacyUiSettings
|
|||
public float NavHeightOffset = 0.05f;
|
||||
public float NavSlopeSink = 1.5f;
|
||||
public bool ShowTerrainPassability = true;
|
||||
// Nav3D extras, both off by default: labels over the route's waypoints (NavLabelModes:
|
||||
// 0 off, 1 numbers, 2 numbers and what happens there) and a line from the character to
|
||||
// the waypoint nav is heading for.
|
||||
public int NavLabelMode;
|
||||
public bool NavGuideLine;
|
||||
public double MaxMonRange = 12.0;
|
||||
public bool SummonPets;
|
||||
public int CustomPetRange = 5;
|
||||
|
|
@ -196,6 +201,11 @@ public sealed class LegacyUiSettings
|
|||
/// on the way as usual, recover the corpse, then carry on. Off by default.
|
||||
/// </summary>
|
||||
public bool TravelToOwnCorpse;
|
||||
/// <summary>
|
||||
/// Selecting an item prints its details to chat (/ra iteminfo, Mag-Tools style),
|
||||
/// identifying it first when needed. Items RynthAi selects itself are skipped. On by default.
|
||||
/// </summary>
|
||||
public bool ItemInfoOnSelect = true;
|
||||
public bool LootOnlyRareCorpses;
|
||||
public bool PeaceModeWhenIdle = true;
|
||||
public bool RebuffWhenIdle;
|
||||
|
|
@ -828,6 +838,9 @@ public sealed class SettingsBridgePayload
|
|||
public float NavHeightOffset { get; set; }
|
||||
public float NavSlopeSink { get; set; }
|
||||
public bool ShowTerrainPassability { get; set; }
|
||||
// Absent from an older engine: -1 / null keep the plugin's value.
|
||||
public int NavLabelMode { get; set; } = -1;
|
||||
public bool? NavGuideLine { get; set; }
|
||||
public bool OpenDoors { get; set; }
|
||||
public float OpenDoorRange { get; set; }
|
||||
public bool AutoUnlockDoors { get; set; }
|
||||
|
|
@ -882,6 +895,7 @@ public sealed class SettingsBridgePayload
|
|||
// and its save must leave them alone.
|
||||
public bool? LootOwnCorpse { get; set; }
|
||||
public bool? TravelToOwnCorpse { get; set; }
|
||||
public bool? ItemInfoOnSelect { get; set; }
|
||||
public bool EnableAutostack { get; set; }
|
||||
public bool ReadUnknownScrolls { get; set; } = true; // absent from an older engine: keep the default
|
||||
public bool EnableCombineSalvage { get; set; }
|
||||
|
|
@ -953,7 +967,11 @@ public enum MetaConditionType
|
|||
MainManaLE,
|
||||
MainManaPHE,
|
||||
MainStamLE,
|
||||
VitaePHE
|
||||
VitaePHE,
|
||||
/// <summary>RynthAi only (2026-10-06): no kill for at least N minutes (ConditionData = minutes,
|
||||
/// decimals allowed). Appended last: the value is the wire / JSON number, and an older RynthAi
|
||||
/// that reads it treats the unknown number (and the .af keyword NoKillsInMins) as never true.</summary>
|
||||
NoKillsWithinMinutes
|
||||
}
|
||||
|
||||
public enum MetaActionType
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ namespace RynthCore.Plugin.RynthAi.Loot;
|
|||
/// </summary>
|
||||
internal sealed class LootEditorBridge
|
||||
{
|
||||
public const string LootFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
public static readonly string LootFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
|
||||
private readonly object _sync = new();
|
||||
private readonly LootEditSession _session = new();
|
||||
|
|
|
|||
189
Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
Normal file
189
Plugins/RynthCore.Plugin.RynthAi/Loot/UseRefusalWatch.cs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
// ============================================================================
|
||||
// RynthAi - Loot/UseRefusalWatch.cs
|
||||
// Notices when the server answers every corpse open but nothing opens.
|
||||
//
|
||||
// Why (2026-10-06, Drakkon on DreamWeave): from 06:18:44 every use of a corpse
|
||||
// or door got the server's "use done" (UseDone, no error) about one round trip
|
||||
// after it was sent, and nothing opened. Fighting, healing kits and spells kept
|
||||
// working. Macro off, walking, jumping and /rc unlockactions changed nothing; a
|
||||
// relog fixed it at once, for the very same corpses. The bot hammered corpses
|
||||
// for 13 minutes: 33 abandons, 11 "LOOT WEDGE" resets, a chat line each.
|
||||
//
|
||||
// What this does: each corpse open is remembered with the server's UseDone
|
||||
// count at the time. A UseDone that arrives after it with no error, with no
|
||||
// corpse opening within AnswerGraceMs, is a refusal. A successful open of any
|
||||
// corpse clears everything.
|
||||
// - RefusalsBeforeRetry refusals in a row: stop all movement once, pause a
|
||||
// moment, try once more (CleanStopAndRetry).
|
||||
// - The retry refused too, with refusals on two different corpses since the
|
||||
// last open: the server refuses every use. Say so once and back off
|
||||
// (Stuck), then try one corpse every BackoffMs (doubling, capped). Each
|
||||
// probe that is refused again is StillStuck (log only); one that opens is
|
||||
// Recovered.
|
||||
// - The retry refused but only one corpse has ever refused: that corpse can't
|
||||
// be opened (its loot rights, say). Give up on it (DropCorpse); the next
|
||||
// corpse's first refusal decides.
|
||||
//
|
||||
// A UseDone with an error (0x1D "too busy", ...) says nothing either way, and
|
||||
// an open the server never answers is left to the corpse timeout as before.
|
||||
// No game calls here: the controller acts on the verdicts.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Loot;
|
||||
|
||||
internal sealed class UseRefusalWatch
|
||||
{
|
||||
/// <summary>After the server's answer, a corpse that opens does so within a few frames.</summary>
|
||||
public const long AnswerGraceMs = 1500;
|
||||
/// <summary>An open the server hasn't answered after this long is forgotten (the corpse timeout handles it).</summary>
|
||||
public const long UnansweredForgetMs = 15_000;
|
||||
public const int RefusalsBeforeRetry = 3;
|
||||
/// <summary>The pause after the clean stop, before the one retry.</summary>
|
||||
public const long CleanStopPauseMs = 1500;
|
||||
public const long FirstBackoffMs = 5 * 60_000;
|
||||
public const long MaxBackoffMs = 20 * 60_000;
|
||||
|
||||
public enum Phase { Normal, Retrying, Stuck }
|
||||
|
||||
public enum Verdict
|
||||
{
|
||||
None,
|
||||
/// <summary>Several refusals in a row: stop all movement, pause CleanStopPauseMs, try once more.</summary>
|
||||
CleanStopAndRetry,
|
||||
/// <summary>The retry was refused but only this corpse ever refused: give up on it.</summary>
|
||||
DropCorpse,
|
||||
/// <summary>The server refuses every use: tell the player once, back off until BackoffUntil.</summary>
|
||||
Stuck,
|
||||
/// <summary>A probe after the back-off was refused too: back off again (longer), quietly.</summary>
|
||||
StillStuck,
|
||||
/// <summary>A corpse opened after Stuck: uses work again.</summary>
|
||||
Recovered,
|
||||
}
|
||||
|
||||
public Phase State { get; private set; } = Phase.Normal;
|
||||
public int Refusals { get; private set; }
|
||||
public long BackoffUntil { get; private set; }
|
||||
public long BackoffMs { get; private set; }
|
||||
/// <summary>The corpses refused since the last successful open.</summary>
|
||||
public IReadOnlyCollection<int> RefusedCorpses => _refused;
|
||||
/// <summary>The corpse of the last refusal (what a verdict is about).</summary>
|
||||
public int LastRefusedCorpse { get; private set; }
|
||||
|
||||
private readonly HashSet<int> _refused = new();
|
||||
private bool _pending;
|
||||
private int _pendingId;
|
||||
private long _sentAt;
|
||||
private int _seqAtSend;
|
||||
private long _answeredAt;
|
||||
|
||||
/// <summary>While Stuck: no opens until the back-off ends (then one probe).</summary>
|
||||
public bool HoldsOpens(long now) => State == Phase.Stuck && now < BackoffUntil;
|
||||
|
||||
/// <summary>Call before sending the next open: the previous one, answered with nothing opened,
|
||||
/// counts as refused now (the next attempt came before its grace ran out). A verdict other than
|
||||
/// None means: act on it and don't send this open.</summary>
|
||||
public Verdict SettleBeforeOpen(long now)
|
||||
{
|
||||
if (!_pending || _answeredAt == 0)
|
||||
return Verdict.None;
|
||||
_pending = false;
|
||||
return Refused(_pendingId, now);
|
||||
}
|
||||
|
||||
/// <summary>An open of <paramref name="corpseId"/> went out; <paramref name="useDoneSeq"/> is the
|
||||
/// server UseDone count read just before it was sent.</summary>
|
||||
public void OnOpenSent(int corpseId, long now, int useDoneSeq)
|
||||
{
|
||||
_pending = true;
|
||||
_pendingId = corpseId;
|
||||
_sentAt = now;
|
||||
_seqAtSend = useDoneSeq;
|
||||
_answeredAt = 0;
|
||||
}
|
||||
|
||||
/// <summary>Every tick: <paramref name="useDoneSeq"/> is the server UseDone count now,
|
||||
/// <paramref name="lastError"/> the error of the latest one when the engine can say
|
||||
/// (<paramref name="haveLastError"/>).</summary>
|
||||
public Verdict OnTick(long now, int useDoneSeq, uint lastError, bool haveLastError)
|
||||
{
|
||||
if (!_pending)
|
||||
return Verdict.None;
|
||||
|
||||
if (_answeredAt == 0)
|
||||
{
|
||||
if (useDoneSeq != _seqAtSend)
|
||||
{
|
||||
if (haveLastError && lastError != 0)
|
||||
{
|
||||
_pending = false; // "too busy" or another error: says nothing about refusals
|
||||
return Verdict.None;
|
||||
}
|
||||
_answeredAt = now;
|
||||
}
|
||||
else if (now - _sentAt >= UnansweredForgetMs)
|
||||
{
|
||||
_pending = false;
|
||||
}
|
||||
return Verdict.None;
|
||||
}
|
||||
|
||||
if (now - _answeredAt < AnswerGraceMs)
|
||||
return Verdict.None;
|
||||
|
||||
_pending = false;
|
||||
return Refused(_pendingId, now);
|
||||
}
|
||||
|
||||
/// <summary>A corpse opened (the server sent its contents): uses work.</summary>
|
||||
public Verdict OnOpened(long now)
|
||||
{
|
||||
bool wasStuck = State == Phase.Stuck;
|
||||
Reset();
|
||||
return wasStuck ? Verdict.Recovered : Verdict.None;
|
||||
}
|
||||
|
||||
/// <summary>Back to normal: a relog, a login, a successful open.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
State = Phase.Normal;
|
||||
Refusals = 0;
|
||||
BackoffUntil = 0;
|
||||
BackoffMs = 0;
|
||||
LastRefusedCorpse = 0;
|
||||
_refused.Clear();
|
||||
_pending = false;
|
||||
_answeredAt = 0;
|
||||
}
|
||||
|
||||
private Verdict Refused(int corpseId, long now)
|
||||
{
|
||||
_refused.Add(corpseId);
|
||||
LastRefusedCorpse = corpseId;
|
||||
Refusals++;
|
||||
|
||||
switch (State)
|
||||
{
|
||||
case Phase.Normal:
|
||||
if (Refusals < RefusalsBeforeRetry)
|
||||
return Verdict.None;
|
||||
State = Phase.Retrying;
|
||||
return Verdict.CleanStopAndRetry;
|
||||
|
||||
case Phase.Retrying:
|
||||
if (_refused.Count < 2)
|
||||
return Verdict.DropCorpse; // stay Retrying: the next corpse's refusal decides
|
||||
State = Phase.Stuck;
|
||||
BackoffMs = FirstBackoffMs;
|
||||
BackoffUntil = now + BackoffMs;
|
||||
return Verdict.Stuck;
|
||||
|
||||
default: // Stuck: a probe after the back-off
|
||||
BackoffMs = Math.Min(MaxBackoffMs, Math.Max(FirstBackoffMs, BackoffMs * 2));
|
||||
BackoffUntil = now + BackoffMs;
|
||||
return Verdict.StillStuck;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -289,7 +289,7 @@ public sealed partial class RynthAiPlugin
|
|||
|
||||
if (cm == 0) { ChatLine($"[RynthAi] Unknown combat mode: {mode}"); return true; }
|
||||
|
||||
Host.ChangeCombatMode(cm);
|
||||
Host.ChangeCombatModeFor(cm, "Command", "/mt combat", force: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -379,7 +379,7 @@ public sealed partial class RynthAiPlugin
|
|||
targetId = Host.GetPlayerId();
|
||||
}
|
||||
|
||||
Host.CastSpell(targetId, spellId);
|
||||
Host.CastSpellFor(targetId, spellId, "Command", $"spell {spellId} (/mt cast)", asked: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -418,7 +418,6 @@ internal sealed class ManaStoneManager
|
|||
if (item == null) continue;
|
||||
if (IsManaStone(item)) continue;
|
||||
if (!IsOwnedByPlayer(item, playerId)) continue;
|
||||
if (IsWandLike(item)) continue; // wands are never tap targets — keep this in sync with FindTapTarget
|
||||
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until) continue;
|
||||
if (_host.TryGetObjectIntProperty(unchecked((uint)item.Id), (uint)AcIntProperty.WieldedSlot, out int wield)
|
||||
&& wield != 0) continue;
|
||||
|
|
@ -649,13 +648,9 @@ internal sealed class ManaStoneManager
|
|||
if (IsManaStone(item)) continue;
|
||||
if (!IsOwnedByPlayer(item, playerId)) continue;
|
||||
|
||||
// Never tap a casting implement (wand/staff/orb). ACE refuses to
|
||||
// drain mana out of these into a stone, so the tap can never complete
|
||||
// and the loop spins forever (each attempt cancels movement + bumps
|
||||
// busy). This is most often the character's OWN casting wand mis-read
|
||||
// as a loose item — WieldedSlot can read 0 from a stale cache, so the
|
||||
// equipped-skip below misses it. Mirrors CombatManager.IsWandObject.
|
||||
if (IsWandLike(item)) continue;
|
||||
// Wands, staves and orbs drain like any other item (ACE's ManaStone only refuses
|
||||
// retained items). Only items looted for Mana Tap are candidates, and the wielded /
|
||||
// listed-item / loot-kept checks below protect the character's own casters.
|
||||
|
||||
// Skip items that recently failed to drain.
|
||||
if (_tapTargetCooldownUntil.TryGetValue(item.Id, out long until) && now < until)
|
||||
|
|
@ -682,11 +677,9 @@ internal sealed class ManaStoneManager
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for casting implements (wand/staff/orb). ACE will not drain mana out
|
||||
/// of these into a mana stone, so they must never be selected as a tap target
|
||||
/// — otherwise the tap can never complete and loops forever. ObjectClass alone
|
||||
/// is unreliable for unappraised items, so we fall back to the name, matching
|
||||
/// CombatManager/BuffManager.IsWandObject.
|
||||
/// True for casting implements (wand/staff/orb). They drain like any other item;
|
||||
/// this is only a classifier. ObjectClass alone is unreliable for unappraised items,
|
||||
/// so we fall back to the name, matching CombatManager/BuffManager.IsWandObject.
|
||||
/// </summary>
|
||||
internal static bool IsWandLike(WorldObject item)
|
||||
=> item.ObjectClass == AcObjectClass.WandStaffOrb || IsWandName(item.Name);
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ internal static class DungeonMapBake
|
|||
private const int MaxDim = 8192; // the agent refuses bigger rasters
|
||||
|
||||
/// <summary>Where plans go. A test points this at its own folder.</summary>
|
||||
internal static string CacheDir { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
|
||||
internal static string CacheDir { get; set; } = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "Maps");
|
||||
|
||||
// Pixel colours, as the old DungeonMapTexture (and DungeonMapUi's former ImGui colours).
|
||||
private static uint Argb(float r, float g, float b, float a) =>
|
||||
|
|
|
|||
|
|
@ -476,6 +476,8 @@ internal static class AfFileParser
|
|||
case MetaConditionType.MainManaPHE:
|
||||
case MetaConditionType.MainStamLE:
|
||||
case MetaConditionType.VitaePHE:
|
||||
// RynthAi only: NoKillsInMins 5 (minutes, decimals allowed).
|
||||
case MetaConditionType.NoKillsWithinMinutes:
|
||||
// These use bare numbers (no braces): e.g. MainSlotsLE 4, BlockE F6820033
|
||||
rule.ConditionData = ExtractBareOrBrace(rest);
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -139,6 +139,9 @@ internal static class AfFileWriter
|
|||
case MetaConditionType.MainManaPHE:
|
||||
case MetaConditionType.MainStamLE:
|
||||
case MetaConditionType.VitaePHE:
|
||||
// RynthAi only (NoKillsInMins 5): metaf can't compile it to a .met, and an older
|
||||
// RynthAi loads it as Never with an "unknown condition keyword" warning.
|
||||
case MetaConditionType.NoKillsWithinMinutes:
|
||||
// Bare values (no braces): MainSlotsLE 4, MainHealthLE 50
|
||||
writer.Write($"{keyword} {data}");
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ internal sealed class ExpressionEngine
|
|||
// The three data paths are settable only so offline tests can point them at a scratch
|
||||
// folder before anything reads or writes them; the plugin never changes them.
|
||||
internal static string ItemGiverDir { get; set; }
|
||||
= Path.Combine(@"C:\Games\RynthSuite\RynthAi", "ItemGiver");
|
||||
= Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ItemGiver");
|
||||
|
||||
/// <summary>Millisecond tick for delayexec and the var-flush throttle. Tests swap it for a
|
||||
/// fake clock; the plugin never changes it.</summary>
|
||||
|
|
@ -107,8 +107,8 @@ internal sealed class ExpressionEngine
|
|||
private long _lastVarFlushMs;
|
||||
private string? _pvarPathCached;
|
||||
private const long VarFlushIntervalMs = 2000;
|
||||
internal static string PvarsDir { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "pvars");
|
||||
internal static string GvarsPath { get; set; } = Path.Combine(@"C:\Games\RynthSuite\RynthAi", "gvars.txt");
|
||||
internal static string PvarsDir { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "pvars");
|
||||
internal static string GvarsPath { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "gvars.txt");
|
||||
private Dictionary<string, (Func<string> Get, Action<string> Set)>? _settingsMap;
|
||||
|
||||
public IReadOnlyDictionary<string, string> Variables => _variables;
|
||||
|
|
@ -156,6 +156,11 @@ internal sealed class ExpressionEngine
|
|||
private CreatureProfileStore? _creatureStore;
|
||||
public void SetCreatureStore(CreatureProfileStore? store) => _creatureStore = store;
|
||||
|
||||
// secondssincelastkill[]: the plugin's kill clock. Null (not wired) reads as 0, i.e.
|
||||
// "just killed", so a "no kills for a while" test never holds by mistake.
|
||||
private KillClock? _killClock;
|
||||
public void SetKillClock(KillClock? clock) => _killClock = clock;
|
||||
|
||||
// ── Backward-compat shim ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Executes an expression for its side effects. Always returns true.</summary>
|
||||
|
|
@ -327,6 +332,8 @@ internal sealed class ExpressionEngine
|
|||
"getdatetimelocal" => DateTime.Now.ToString(A(0)),
|
||||
"getdatetimeutc" => DateTime.UtcNow.ToString(A(0)),
|
||||
"getunixtime" => DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
// Whole seconds since our last kill; before the first, since the macro start (or login).
|
||||
"secondssincelastkill" => (_killClock?.SecondsSinceLastKill() ?? 0).ToString(CultureInfo.InvariantCulture),
|
||||
|
||||
// ── World object queries ──────────────────────────────────────────
|
||||
"wobjectfindnearestbytemplatetype" => EvalWobjectFindNearestByTemplateType(A(0)),
|
||||
|
|
@ -2412,6 +2419,7 @@ internal sealed class ExpressionEngine
|
|||
{
|
||||
if (!TryParseWobjectHandle(arg, out uint uid, out _) || uid == 0) return "0";
|
||||
if (!_host.HasSelectItem) return "0";
|
||||
RynthCore.Plugin.RynthAi.ItemInfo.SelfSelect.Mark(uid);
|
||||
_host.SelectItem(uid);
|
||||
return "0";
|
||||
}
|
||||
|
|
@ -2440,7 +2448,7 @@ internal sealed class ExpressionEngine
|
|||
|
||||
if (!EnsureMagicModeForCast()) return "0";
|
||||
|
||||
_host.CastSpell(targetId, spellId);
|
||||
_host.CastSpellFor(targetId, spellId, "Meta", $"spell {spellId} (meta)", asked: true);
|
||||
return "1";
|
||||
}
|
||||
|
||||
|
|
@ -2486,7 +2494,7 @@ internal sealed class ExpressionEngine
|
|||
if (!_host.HasGetCurrentCombatMode)
|
||||
{
|
||||
// Can't read mode — best-effort flip and bail.
|
||||
if (_host.HasChangeCombatMode) _host.ChangeCombatMode(CombatMode.Magic);
|
||||
if (_host.HasChangeCombatMode) _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -2509,7 +2517,7 @@ internal sealed class ExpressionEngine
|
|||
if (wandId == 0 || !_host.HasUseObject)
|
||||
{
|
||||
// No wand (or no UseObject) — try bare-handed magic.
|
||||
if (_host.HasChangeCombatMode) _host.ChangeCombatMode(CombatMode.Magic);
|
||||
if (_host.HasChangeCombatMode) _host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -2613,7 +2621,7 @@ internal sealed class ExpressionEngine
|
|||
if (_host.HasChangeCombatMode
|
||||
&& (now - _castStanceLastFlipAt).TotalMilliseconds > CastStanceFlipGateMs)
|
||||
{
|
||||
_host.ChangeCombatMode(CombatMode.Magic);
|
||||
_host.ChangeCombatModeFor(CombatMode.Magic, "Meta", "meta cast: Magic mode", force: true);
|
||||
_castStanceLastFlipAt = now;
|
||||
}
|
||||
return false;
|
||||
|
|
@ -2717,7 +2725,7 @@ internal sealed class ExpressionEngine
|
|||
if (targetId == 0) targetId = _host.GetPlayerId();
|
||||
if (targetId == 0) return "2";
|
||||
|
||||
_host.CastSpell(targetId, spellId);
|
||||
_host.CastSpellFor(targetId, spellId, "Meta", $"spell {spellId} (meta)", asked: true);
|
||||
return "1";
|
||||
}
|
||||
|
||||
|
|
@ -2867,7 +2875,11 @@ internal sealed class ExpressionEngine
|
|||
_ => 0,
|
||||
};
|
||||
if (mode == 0) return "0";
|
||||
return _host.ChangeCombatMode(mode) ? "1" : "0";
|
||||
if (!_host.HasChangeCombatMode) return "0";
|
||||
int seq = _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
|
||||
bool ok = _host.ChangeCombatMode(mode);
|
||||
if (ok) ActionPacer.Begin(_host, PacedKind.CombatMode, 0, ActionPacer.ModeName(mode), "RynthAi/Meta (asked)", seq, mode);
|
||||
return ok ? "1" : "0";
|
||||
}
|
||||
|
||||
private string EvalGetBusyState()
|
||||
|
|
@ -3307,6 +3319,7 @@ internal sealed class ExpressionEngine
|
|||
["StopLootingWhenPackFull"] = (() => B(s.StopLootingWhenPackFull), v => s.StopLootingWhenPackFull = ToDouble(v) != 0),
|
||||
["LootOwnCorpse"] = (() => B(s.LootOwnCorpse), v => s.LootOwnCorpse = ToDouble(v) != 0),
|
||||
["TravelToOwnCorpse"] = (() => B(s.TravelToOwnCorpse), v => s.TravelToOwnCorpse = ToDouble(v) != 0),
|
||||
["ItemInfoOnSelect"] = (() => B(s.ItemInfoOnSelect), v => s.ItemInfoOnSelect = ToDouble(v) != 0),
|
||||
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
|
||||
["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0),
|
||||
["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0),
|
||||
|
|
@ -3371,6 +3384,8 @@ internal sealed class ExpressionEngine
|
|||
["MaxMonRange"] = (() => D(s.MaxMonRange), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.MaxMonRange = d; }),
|
||||
["NavRingThickness"] = (() => F(s.NavRingThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavRingThickness = f; }),
|
||||
["NavLineThickness"] = (() => F(s.NavLineThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavLineThickness = f; }),
|
||||
["NavLabelMode"] = (() => I(s.NavLabelMode), v => { if (int.TryParse(v, out int i)) s.NavLabelMode = NavLabelModes.Clamp(i); }),
|
||||
["NavGuideLine"] = (() => B(s.NavGuideLine), v => s.NavGuideLine = ToDouble(v) != 0),
|
||||
["CurrentNavPath"] = (() => s.CurrentNavPath, v => s.CurrentNavPath = v),
|
||||
["CurrentLootPath"] = (() => s.CurrentLootPath, v => s.CurrentLootPath = v),
|
||||
["CurrentMetaPath"] = (() => s.CurrentMetaPath, v => s.CurrentMetaPath = v),
|
||||
|
|
|
|||
|
|
@ -728,6 +728,19 @@ getunixtime[]
|
|||
Example: setvar[t, getunixtime[]] → snapshot a timestamp
|
||||
Example: getunixtime[] - getvar[t] > 60 → true if 60s have elapsed
|
||||
|
||||
secondssincelastkill[]
|
||||
Returns the whole number of seconds since your character's last kill.
|
||||
Only kills credited to you count (the server's "you killed it" notice);
|
||||
deaths you only see in chat, and your fellows' kills, do not.
|
||||
Before your first kill this session it counts from when the macro was last
|
||||
started, or from login (or a RynthAi reload) if the macro hasn't been started
|
||||
since, so a meta can still react when nothing has been killed at all.
|
||||
After a kill it is always the time since that kill, also across a macro stop/start.
|
||||
The meta condition "No Kills Within Minutes" (.af: NoKillsInMins 5) uses the same clock.
|
||||
Test in chat: /ra mexec secondssincelastkill[]
|
||||
Example: secondssincelastkill[] → e.g. "42"
|
||||
Example: secondssincelastkill[] >= 300 → true after 5 minutes without a kill
|
||||
|
||||
getaccounthash[]
|
||||
Returns a lowercase MD5 hex string of the current account name.
|
||||
Returns "" (empty string) if the account name is not yet available.
|
||||
|
|
|
|||
|
|
@ -144,6 +144,15 @@ internal sealed class MetaManager
|
|||
_expressions?.SetCreatureStore(store);
|
||||
}
|
||||
|
||||
// The plugin's kill clock (secondssincelastkill[], No Kills Within Minutes). Without one
|
||||
// (never in the plugin) the condition is false and the function says 0: fail closed.
|
||||
private KillClock? _killClock;
|
||||
public void SetKillClock(KillClock? clock)
|
||||
{
|
||||
_killClock = clock;
|
||||
_expressions?.SetKillClock(clock);
|
||||
}
|
||||
|
||||
public void SetPlayerId(uint id)
|
||||
{
|
||||
_playerId = id;
|
||||
|
|
@ -200,6 +209,7 @@ internal sealed class MetaManager
|
|||
engine.SetQuestTracker(_questTracker);
|
||||
engine.SetSettings(_settings);
|
||||
engine.SetCreatureStore(_creatureStore);
|
||||
engine.SetKillClock(_killClock);
|
||||
return engine;
|
||||
}
|
||||
|
||||
|
|
@ -727,6 +737,14 @@ internal sealed class MetaManager
|
|||
case MetaConditionType.NeedToBuff:
|
||||
return _buffManager != null && _buffManager.NeedsAnyBuff();
|
||||
|
||||
// ── No kills within N minutes (RynthAi only) ──────────────────────
|
||||
// The secondssincelastkill[] clock: our last kill (KillerNotification), or before
|
||||
// the first one the last macro start / login. Bad or missing minutes never hold.
|
||||
case MetaConditionType.NoKillsWithinMinutes:
|
||||
return _killClock != null
|
||||
&& KillClock.TryParseMinutes(rule.ConditionData, out double noKillMins)
|
||||
&& _killClock.NoKillsFor(noKillMins);
|
||||
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -892,7 +910,7 @@ internal sealed class MetaManager
|
|||
}
|
||||
|
||||
// Fallback: a standalone .nav file in NavProfiles.
|
||||
string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
|
||||
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
string fullPath = Path.Combine(navFolder, routeName + ".nav");
|
||||
if (File.Exists(fullPath))
|
||||
{
|
||||
|
|
@ -1091,7 +1109,7 @@ internal sealed class MetaManager
|
|||
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
string name = string.Join(" ", parts, 3, parts.Length - 3);
|
||||
string metaDir = @"C:\Games\RynthSuite\RynthAi\MetaFiles";
|
||||
string metaDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "MetaFiles");
|
||||
string afPath = Path.Combine(metaDir, name + ".af");
|
||||
string metPath = Path.Combine(metaDir, name + ".met");
|
||||
|
||||
|
|
@ -1155,7 +1173,7 @@ internal sealed class MetaManager
|
|||
string path = name;
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
string stem = name.EndsWith(".utl", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
|
||||
? name : name + ".utl";
|
||||
string candidate = Path.Combine(folder, stem);
|
||||
|
|
|
|||
52
Plugins/RynthCore.Plugin.RynthAi/Meta/MetaRuleEdits.cs
Normal file
52
Plugins/RynthCore.Plugin.RynthAi/Meta/MetaRuleEdits.cs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi.Meta;
|
||||
|
||||
/// <summary>
|
||||
/// How a rule edited in the Meta panel replaces the running one (update_rule / duplicate_rule).
|
||||
///
|
||||
/// The engine's Meta editor saves every change on its own since 2026-10-05 (debounced), so an
|
||||
/// update must not disturb a meta that is running:
|
||||
/// - the rule keeps its runtime latch (HasFired) and LastFiredAt. A fresh MetaRule had
|
||||
/// HasFired = false, so every save of a rule in the current state fired it again
|
||||
/// (an IF Always DO EmbedNav rule restarted its route from point 0 on each save);
|
||||
/// - the panel's DTO has no CallReturnState (CallState's return state) or ChatColors
|
||||
/// (ChatCapture's chat types), so an update used to drop both from VTank-imported rules.
|
||||
/// They are kept while the rule still has that action / condition.
|
||||
/// Nothing here touches the current state, the state clocks, the watchdog or the call stack.
|
||||
/// </summary>
|
||||
internal static class MetaRuleEdits
|
||||
{
|
||||
/// <summary>Puts <paramref name="edited"/> at <paramref name="index"/>, keeping the old rule's
|
||||
/// runtime latch and the fields the panel can't send. False when the index is out of range.</summary>
|
||||
public static bool Replace(List<MetaRule> rules, int index, MetaRule edited)
|
||||
{
|
||||
if (index < 0 || index >= rules.Count) return false;
|
||||
MetaRule old = rules[index];
|
||||
KeepHidden(old, edited);
|
||||
edited.HasFired = old.HasFired;
|
||||
edited.LastFiredAt = old.LastFiredAt;
|
||||
rules[index] = edited;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Copies CallReturnState / ChatColors from <paramref name="from"/> into an edited copy
|
||||
/// that still has the same action / condition and carries none of its own; children by position.</summary>
|
||||
public static void KeepHidden(MetaRule from, MetaRule to)
|
||||
{
|
||||
if (to.Action == MetaActionType.CallMetaState && from.Action == MetaActionType.CallMetaState
|
||||
&& string.IsNullOrEmpty(to.CallReturnState))
|
||||
to.CallReturnState = from.CallReturnState;
|
||||
if (to.Condition == MetaConditionType.ChatMessageCapture && from.Condition == MetaConditionType.ChatMessageCapture
|
||||
&& string.IsNullOrEmpty(to.ChatColors))
|
||||
to.ChatColors = from.ChatColors;
|
||||
|
||||
if (from.Children != null && to.Children != null)
|
||||
for (int i = 0; i < from.Children.Count && i < to.Children.Count; i++)
|
||||
KeepHidden(from.Children[i], to.Children[i]);
|
||||
if (from.ActionChildren != null && to.ActionChildren != null)
|
||||
for (int i = 0; i < from.ActionChildren.Count && i < to.ActionChildren.Count; i++)
|
||||
KeepHidden(from.ActionChildren[i], to.ActionChildren[i]);
|
||||
}
|
||||
}
|
||||
|
|
@ -72,6 +72,8 @@ internal static class MetaSchema
|
|||
new(MetaConditionType.MainManaPHE, "MainManaPHE", "Main Mana % >="),
|
||||
new(MetaConditionType.MainStamLE, "MainStamLE", "Main Stam <="),
|
||||
new(MetaConditionType.VitaePHE, "VitaePHE", "Vitae % >="),
|
||||
// RynthAi only: VTank and metaf have no such condition (see AfFileWriter).
|
||||
new(MetaConditionType.NoKillsWithinMinutes, "NoKillsInMins", "No Kills Within Minutes"),
|
||||
};
|
||||
|
||||
// Index == (int)MetaActionType.
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.Numerics;
|
|||
using ImGuiNET;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
|
|
@ -249,6 +250,13 @@ internal sealed class NavMarkerRenderer
|
|||
int n = route.Points.Count;
|
||||
bool circular = route.RouteType == NavRouteType.Circular;
|
||||
|
||||
// ── Waypoint labels and guide line (both off by default) ─────
|
||||
// Worked out from the route here, on the plugin tick, into an immutable frame; the
|
||||
// emit steps read only that frame. The guide goes in first so the route's lines can't
|
||||
// crowd it out of the engine's line buffer; the labels go in last (pass 4).
|
||||
NavOverlayFrame overlay = BuildOverlay(route, px, py, pz, playerNS, playerEW, heightOffset);
|
||||
NavOverlay.EmitGuide(overlay, _sink ??= new HostNav3DSink(_host), lineThick);
|
||||
|
||||
// ── Pass 1: Submit rings ─────────────────────────────────────
|
||||
// Arrays are indexed by window slot k (0..count), not absolute route
|
||||
// index — the absolute index can run far past count on a long route.
|
||||
|
|
@ -339,6 +347,68 @@ internal sealed class NavMarkerRenderer
|
|||
_host.Nav3DAddRing(pwx, pwy, pwz, ringRadius, ringThick * 1.4f, ColorPortal3D);
|
||||
_host.Nav3DAddLine(px, pwy, py, pwx, pwy, pwz, lineThick, ColorPortal3D);
|
||||
}
|
||||
|
||||
// ── Pass 4: waypoint labels (filled strokes, Nav3D triangles) ─
|
||||
if (overlay.Labels.Count > 0 && _host.HasNav3DTriangle)
|
||||
NavOverlay.EmitLabels(overlay, _sink);
|
||||
}
|
||||
|
||||
// ── Labels and guide line ────────────────────────────────────────
|
||||
private NavOverlay.RouteText? _labelText;
|
||||
private INav3DSink? _sink;
|
||||
|
||||
/// <summary>
|
||||
/// The tick's labels and guide line from the route and the two settings (Navigation ▸
|
||||
/// Waypoint Labels / Guide Line). Plugin tick only; returns an immutable frame.
|
||||
/// </summary>
|
||||
internal NavOverlayFrame BuildOverlay(NavRouteParser route, float px, float py, float pz,
|
||||
double playerNS, double playerEW, float heightOffset)
|
||||
{
|
||||
int mode = NavLabelModes.Clamp(_settings.NavLabelMode);
|
||||
bool guideOn = _settings.NavGuideLine;
|
||||
if (mode == NavLabelModes.Off && !guideOn)
|
||||
{
|
||||
_labelText = null;
|
||||
return NavOverlayFrame.Empty;
|
||||
}
|
||||
|
||||
var points = route.Points;
|
||||
int n = points.Count;
|
||||
NavOverlay.RouteText? text = null;
|
||||
if (mode != NavLabelModes.Off)
|
||||
{
|
||||
// Rebuilt only when the route, its length or the mode change (an edit in place keeps
|
||||
// the count: the Nav panel's edits replace the route or change its length).
|
||||
text = _labelText;
|
||||
if (text == null || !ReferenceEquals(text.Route, route) || text.Count != n || text.Mode != mode)
|
||||
_labelText = text = NavOverlay.BuildText(route, points, mode, SpellDatabase.GetSpellNameOrId);
|
||||
}
|
||||
else _labelText = null;
|
||||
|
||||
int active = _settings.ActiveNavIndex;
|
||||
bool guide = guideOn && active >= 0 && active < n && HasGroundCoords(points[active].Type);
|
||||
|
||||
(float X, float Y, float Z) WorldOf(int i)
|
||||
{
|
||||
var pt = points[i];
|
||||
return (px + (float)((pt.EW - playerEW) * 240.0),
|
||||
ResolveMarkerWorldY(route, i, heightOffset),
|
||||
py + (float)((pt.NS - playerNS) * 240.0));
|
||||
}
|
||||
|
||||
// D3D frame: X = EW, Y = height, Z = NS; the player's height is pose z.
|
||||
return NavOverlay.BuildFrame(text, guide, active, WorldOf, px, pz, py, heightOffset);
|
||||
}
|
||||
|
||||
/// <summary>The engine's Nav3D buffer.</summary>
|
||||
private sealed class HostNav3DSink : INav3DSink
|
||||
{
|
||||
private readonly RynthCoreHost _host;
|
||||
public HostNav3DSink(RynthCoreHost host) => _host = host;
|
||||
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
=> _host.Nav3DAddLine(x1, y1, z1, x2, y2, z2, thickness, colorArgb);
|
||||
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb)
|
||||
=> _host.Nav3DAddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, colorArgb);
|
||||
}
|
||||
|
||||
private void PrepareFloorCache(NavRouteParser route)
|
||||
|
|
|
|||
234
Plugins/RynthCore.Plugin.RynthAi/NavOverlay.cs
Normal file
234
Plugins/RynthCore.Plugin.RynthAi/NavOverlay.cs
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>Settings ▸ Navigation ▸ "Waypoint Labels" (LegacyUiSettings.NavLabelMode).</summary>
|
||||
internal static class NavLabelModes
|
||||
{
|
||||
public const int Off = 0, Numbers = 1, Names = 2;
|
||||
public static int Clamp(int mode) => mode is >= Off and <= Names ? mode : Off;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One tick's waypoint labels and guide line, worked out from the route on the plugin tick and
|
||||
/// then never changed: the emit step reads only this, never the route's lists. Positions are in
|
||||
/// the Nav3D frame NavMarkerRenderer uses (X = east metres, Y = height, Z = north metres, in
|
||||
/// the player's landblock).
|
||||
/// </summary>
|
||||
internal sealed class NavOverlayFrame
|
||||
{
|
||||
public static readonly NavOverlayFrame Empty = new(Array.Empty<NavLabel>(), null, 0f, 0f, 0f);
|
||||
|
||||
public NavOverlayFrame(NavLabel[] labels, NavGuide? guide, float playerX, float playerY, float playerZ)
|
||||
{
|
||||
Labels = labels;
|
||||
Guide = guide;
|
||||
PlayerX = playerX;
|
||||
PlayerY = playerY;
|
||||
PlayerZ = playerZ;
|
||||
}
|
||||
|
||||
public IReadOnlyList<NavLabel> Labels { get; }
|
||||
public NavGuide? Guide { get; }
|
||||
public float PlayerX { get; }
|
||||
public float PlayerY { get; }
|
||||
public float PlayerZ { get; }
|
||||
}
|
||||
|
||||
/// <summary>One text line over a waypoint. Row 0 sits just above the ring; higher rows stack above it.</summary>
|
||||
internal sealed record NavLabel(float X, float Y, float Z, string Text, int Row, uint Color);
|
||||
|
||||
/// <summary>The line from the character's feet to the waypoint nav is heading for.</summary>
|
||||
internal sealed record NavGuide(float X1, float Y1, float Z1, float X2, float Y2, float Z2, uint Color);
|
||||
|
||||
/// <summary>
|
||||
/// Waypoint labels (numbers, or numbers and what happens there) and the guide line for the Nav3D
|
||||
/// markers (Silentkelpie's rynth PR #1 idea, done on our pump-thread Nav3D path). Both are off by
|
||||
/// default. Labels are drawn as filled strokes (Nav3D triangles) on an upright plane turned toward
|
||||
/// the character, sized up with distance so far labels stay readable; the guide is one Nav3D line.
|
||||
/// </summary>
|
||||
internal static class NavOverlay
|
||||
{
|
||||
/// <summary>Labels further than this from the character are left out (metres).</summary>
|
||||
public const float LabelRange = 60f;
|
||||
/// <summary>At most this many label lines a tick, nearest first (the active point's always first).</summary>
|
||||
public const int MaxLabelLines = 24;
|
||||
/// <summary>At most this many action lines stacked over one point.</summary>
|
||||
public const int MaxActionLines = 3;
|
||||
/// <summary>Triangle budget for all labels together (the engine keeps 8192 a tick for every plugin).</summary>
|
||||
public const int MaxLabelTriangles = 1600;
|
||||
public const int MaxLabelChars = 22;
|
||||
|
||||
public const uint LabelColor = 0xFFE6FFFF; // near white, a cyan touch like the rings
|
||||
public const uint ActiveLabelColor = 0xFFFF6A6A;
|
||||
public const uint ActionLabelColor = 0xFFFFC040;
|
||||
public const uint GuideColor = 0xFFFFD21E;
|
||||
|
||||
private const float GuideLift = 0.05f;
|
||||
private const float MaxGuideLength = 500f;
|
||||
|
||||
// ── Text per route (rebuilt when the route or the mode changes) ──────
|
||||
|
||||
/// <summary>
|
||||
/// Label text for every route point, built once per route and mode: <c>Own[i]</c> for a point
|
||||
/// with ground coordinates (null otherwise), and the action lines ("13 RECALL ...") hung on
|
||||
/// the ground point before them (the point where nav does them).
|
||||
/// </summary>
|
||||
internal sealed class RouteText
|
||||
{
|
||||
public readonly object Route;
|
||||
public readonly int Count, Mode;
|
||||
public readonly string?[] Own;
|
||||
public readonly string[]?[] Actions;
|
||||
|
||||
public RouteText(object route, int count, int mode, string?[] own, string[]?[] actions)
|
||||
{
|
||||
Route = route; Count = count; Mode = mode; Own = own; Actions = actions;
|
||||
}
|
||||
}
|
||||
|
||||
public static RouteText BuildText(object route, IReadOnlyList<NavPoint> points, int mode, Func<int, string> spellName)
|
||||
{
|
||||
int n = points.Count;
|
||||
var own = new string?[n];
|
||||
var actions = new string[]?[n];
|
||||
var pending = new List<string>();
|
||||
int lastGround = -1;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
NavPoint p = points[i];
|
||||
if (HasGroundCoords(p.Type))
|
||||
{
|
||||
own[i] = mode == NavLabelModes.Names ? Fit(GroundName(i, p)) : i.ToString();
|
||||
lastGround = i;
|
||||
continue;
|
||||
}
|
||||
if (mode != NavLabelModes.Names || lastGround < 0) continue;
|
||||
var list = actions[lastGround] ??= Array.Empty<string>();
|
||||
if (list.Length < MaxActionLines)
|
||||
actions[lastGround] = Append(list, Fit(ActionName(i, p, spellName)));
|
||||
else if (list.Length == MaxActionLines)
|
||||
actions[lastGround] = Append(list, "...");
|
||||
}
|
||||
return new RouteText(route, n, mode, own, actions);
|
||||
}
|
||||
|
||||
private static string[] Append(string[] a, string s)
|
||||
{
|
||||
var b = new string[a.Length + 1];
|
||||
Array.Copy(a, b, a.Length);
|
||||
b[a.Length] = s;
|
||||
return b;
|
||||
}
|
||||
|
||||
private static bool HasGroundCoords(NavPointType t) => NavRouteParser.IsPlainWaypoint(t) || t == NavPointType.Jump;
|
||||
|
||||
private static string GroundName(int i, NavPoint p) => p.Type switch
|
||||
{
|
||||
NavPointType.Checkpoint => $"{i} CHECKPOINT",
|
||||
NavPointType.Jump => $"{i} JUMP",
|
||||
_ => i.ToString(),
|
||||
};
|
||||
|
||||
private static string ActionName(int i, NavPoint p, Func<int, string> spellName) => p.Type switch
|
||||
{
|
||||
NavPointType.Recall => $"{i} {spellName(p.SpellId)}",
|
||||
NavPointType.Pause => $"{i} PAUSE {Math.Max(0, p.PauseTimeMs) / 1000.0:0.#}S",
|
||||
NavPointType.Chat => $"{i} CHAT {p.ChatCommand}",
|
||||
NavPointType.OpenVendor => $"{i} VENDOR {p.TargetName}",
|
||||
NavPointType.PortalNPC => $"{i} PORTAL {p.TargetName}",
|
||||
NavPointType.Npc => $"{i} NPC {p.TargetName}",
|
||||
_ => $"{i} {p.Type}",
|
||||
};
|
||||
|
||||
private static string Fit(string s)
|
||||
{
|
||||
s = s.Trim().ToUpperInvariant();
|
||||
return s.Length > MaxLabelChars ? s[..(MaxLabelChars - 2)] + ".." : s;
|
||||
}
|
||||
|
||||
// ── The frame (plugin tick) ───────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Builds the tick's overlay from <paramref name="text"/> (null: no labels) and the waypoints'
|
||||
/// positions (<paramref name="worldOf"/>, only asked for points that have ground coordinates).
|
||||
/// <paramref name="active"/> is the point nav is heading for; <paramref name="guide"/> draws the
|
||||
/// line to it (the caller passes false when that point has no ground coordinates). Plugin tick only.
|
||||
/// </summary>
|
||||
public static NavOverlayFrame BuildFrame(RouteText? text, bool guide, int active,
|
||||
Func<int, (float X, float Y, float Z)> worldOf, float playerX, float playerY, float playerZ, float lift)
|
||||
{
|
||||
NavGuide? g = null;
|
||||
if (guide && active >= 0)
|
||||
{
|
||||
var (ax, ay, az) = worldOf(active);
|
||||
float dx = ax - playerX, dz = az - playerZ;
|
||||
if (dx * dx + dz * dz <= MaxGuideLength * MaxGuideLength)
|
||||
g = new NavGuide(playerX, playerY + lift + GuideLift, playerZ, ax, ay, az, GuideColor);
|
||||
}
|
||||
|
||||
if (text == null || text.Mode == NavLabelModes.Off)
|
||||
return g == null ? NavOverlayFrame.Empty : new NavOverlayFrame(Array.Empty<NavLabel>(), g, playerX, playerY, playerZ);
|
||||
|
||||
// Ground points in range, nearest first; the active point first of all.
|
||||
var near = new List<(float D2, int I, float X, float Y, float Z)>();
|
||||
float range2 = LabelRange * LabelRange;
|
||||
for (int i = 0; i < text.Count; i++)
|
||||
{
|
||||
if (text.Own[i] == null) continue;
|
||||
var (x, y, z) = worldOf(i);
|
||||
float dx = x - playerX, dz = z - playerZ;
|
||||
float d2 = dx * dx + dz * dz;
|
||||
if (d2 > range2) continue;
|
||||
near.Add((i == active ? -1f : d2, i, x, y, z));
|
||||
}
|
||||
near.Sort((a, b) => a.D2.CompareTo(b.D2));
|
||||
|
||||
var labels = new List<NavLabel>(Math.Min(MaxLabelLines, near.Count * 2));
|
||||
foreach (var (_, i, x, y, z) in near)
|
||||
{
|
||||
if (labels.Count >= MaxLabelLines) break;
|
||||
labels.Add(new NavLabel(x, y, z, text.Own[i]!, 0, i == active ? ActiveLabelColor : LabelColor));
|
||||
string[]? acts = text.Actions[i];
|
||||
if (acts == null) continue;
|
||||
for (int k = 0; k < acts.Length && labels.Count < MaxLabelLines; k++)
|
||||
labels.Add(new NavLabel(x, y, z, acts[k], k + 1, ActionLabelColor));
|
||||
}
|
||||
return new NavOverlayFrame(labels.ToArray(), g, playerX, playerY, playerZ);
|
||||
}
|
||||
|
||||
// ── Emit (plugin tick, into the Nav3D buffer) ──────────────────────
|
||||
|
||||
/// <summary>The guide line, if the frame has one: submitted before the route's lines so a full line buffer never drops it.</summary>
|
||||
public static void EmitGuide(NavOverlayFrame frame, INav3DSink sink, float thickness)
|
||||
{
|
||||
NavGuide? g = frame.Guide;
|
||||
if (g != null)
|
||||
sink.Line(g.X1, g.Y1, g.Z1, g.X2, g.Y2, g.Z2, thickness, g.Color);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Each label as filled strokes (triangles). Returns the number of triangles used (at most
|
||||
/// <see cref="MaxLabelTriangles"/>).
|
||||
/// </summary>
|
||||
public static int EmitLabels(NavOverlayFrame frame, INav3DSink sink)
|
||||
{
|
||||
int tris = 0;
|
||||
foreach (NavLabel l in frame.Labels)
|
||||
{
|
||||
if (!EmitLabel(l, frame.PlayerX, frame.PlayerZ, sink, ref tris)) break;
|
||||
}
|
||||
return tris;
|
||||
}
|
||||
|
||||
/// <summary>The line height (m) for a label this far from the character.</summary>
|
||||
internal static float LineHeight(float distance) => Nav3DText.LineHeight(distance);
|
||||
|
||||
// The text itself is drawn by the shared Nav3DText (Plugins/Shared/Nav3DText.cs), which
|
||||
// RynthNav's path markers use too.
|
||||
private static bool EmitLabel(NavLabel l, float playerX, float playerZ, INav3DSink sink, ref int tris)
|
||||
=> Nav3DText.Emit(l.X, l.Y, l.Z, l.Text, l.Row, l.Color, playerX, playerZ, sink, ref tris, MaxLabelTriangles);
|
||||
}
|
||||
|
|
@ -75,7 +75,16 @@ internal sealed class NavigationEngine
|
|||
private bool _inPause;
|
||||
private int _pauseIdx = -1; // the Pause waypoint _pauseUntil belongs to
|
||||
private long _pauseUntil;
|
||||
private double _prevDist = double.MaxValue;
|
||||
// Closest the character has come to the current waypoint since it became the target (or
|
||||
// since a pause / escape / teleport reset it). It used to hold only the previous tick's
|
||||
// distance, so a "sweep pass" needed the distance to grow 0.3 yd in ONE 33 ms tick (over
|
||||
// 9 yd/s straight away from the point): just past a point the distance grows slowly, the
|
||||
// pass was never seen, and nav turned round and walked back to the point (2026-10-05).
|
||||
private double _closestDist = double.MaxValue;
|
||||
// Where the character stood when it started on the current waypoint (NaN = take it on the
|
||||
// next steering tick). With the waypoint it gives the way the route arrives at the point,
|
||||
// for the pass-through rule (PassedThrough).
|
||||
private double _legStartNs = double.NaN, _legStartEw = double.NaN;
|
||||
|
||||
// ── Portal/Recall state machine ──────────────────────────────────────────
|
||||
private enum PortalState
|
||||
|
|
@ -147,7 +156,7 @@ internal sealed class NavigationEngine
|
|||
public int Doorways;
|
||||
public long StartedAt;
|
||||
public long DeadlineAt;
|
||||
public double PrevDist = double.MaxValue;
|
||||
public double ClosestDist = double.MaxValue; // closest to the current detour point so far
|
||||
public bool Paused; // nav was stopped (combat, loot, buff, door) mid-detour
|
||||
public long PausedAt;
|
||||
public double PausedNs = double.NaN, PausedEw = double.NaN;
|
||||
|
|
@ -244,10 +253,39 @@ internal sealed class NavigationEngine
|
|||
private double ReachFor(NavPoint p) => p.Doorway ? Math.Min(ArrivalYards, DoorwayReachYd) : ArrivalYards;
|
||||
private double SweepFor(NavPoint p) => ReachFor(p) * (p.Doorway ? Math.Min(SweepMult, DoorwaySweepMult) : SweepMult);
|
||||
|
||||
// Lookahead: within this distance of a waypoint, blend the aim point toward
|
||||
// the next one so corners are cut smoothly. 0 = off (aim straight at each
|
||||
// waypoint). Tunable in Advanced ▸ Navigation ▸ Steering.
|
||||
private double LookaheadYards => Math.Max(0.0, _settings.NavLookaheadYards);
|
||||
// Lookahead (corner rounding): within this distance of a waypoint, blend the aim point
|
||||
// toward the next one so corners are rounded. It used to be the Lookahead setting alone
|
||||
// (4 yd), whatever the nav point reach: at a 1 yd reach the aim was already 75% of the way
|
||||
// down the next leg when the character got to 1 yd, so it cut the corner, never got within
|
||||
// the reach, and ran into the wall at the corner (2026-10-05). Now the reach decides how
|
||||
// much rounding there is: none at or under CornerRoundFreeReachYd, then CornerRoundPerReachYd
|
||||
// per yard of reach above it, never more than the Lookahead setting (Advanced > Navigation >
|
||||
// Steering; 0 = off). Blending only matters where it starts outside the reach, so there is
|
||||
// none up to a 2 yd reach (the 1.5 yd default gives 1 yd, inside it); it reaches the 4 yd
|
||||
// setting at a 3 yd reach, so 3-5 yd round corners as before. Doorway points never blend.
|
||||
internal const double CornerRoundFreeReachYd = 1.0, CornerRoundPerReachYd = 2.0;
|
||||
internal static double CornerLookaheadYards(double lookaheadSetting, double reachYd)
|
||||
=> Math.Clamp(CornerRoundPerReachYd * (reachYd - CornerRoundFreeReachYd), 0.0, Math.Max(0.0, lookaheadSetting));
|
||||
private double LookaheadYards => CornerLookaheadYards(_settings.NavLookaheadYards, ArrivalYards);
|
||||
|
||||
// Pass-through: a plain waypoint the character has gone past (it is beyond the point along
|
||||
// the way it came, and no farther to the side than the sweep radius) counts as reached,
|
||||
// so nav doesn't turn round to walk back to it. "Beyond along the way it came" means the
|
||||
// point is behind the character: a corner cut toward the next point never qualifies.
|
||||
// Doorway points keep their own tight reach and sweep and never use it.
|
||||
private const double PassMinLegYd = 1.0; // shorter approach: no reliable direction
|
||||
private bool PassedThrough(NavPoint pt, double ns, double ew)
|
||||
{
|
||||
if (pt.Doorway || double.IsNaN(_legStartNs)) return false;
|
||||
double ux = (pt.NS - _legStartNs) * 240.0, uy = (pt.EW - _legStartEw) * 240.0;
|
||||
double len = Math.Sqrt(ux * ux + uy * uy);
|
||||
if (len < PassMinLegYd) return false;
|
||||
ux /= len; uy /= len;
|
||||
double ax = (ns - pt.NS) * 240.0, ay = (ew - pt.EW) * 240.0;
|
||||
double along = ax * ux + ay * uy;
|
||||
double side = Math.Abs(ax * uy - ay * ux);
|
||||
return along > 0.0 && side <= SweepFor(pt);
|
||||
}
|
||||
|
||||
|
||||
// Mode 0 heading servo: cap the heading change we command per tick so the
|
||||
|
|
@ -411,7 +449,7 @@ internal sealed class NavigationEngine
|
|||
{
|
||||
_lastRoute = route;
|
||||
_inPause = false;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_linearDir = 1;
|
||||
_watchdogNs = double.NaN;
|
||||
_watchdogEw = double.NaN;
|
||||
|
|
@ -462,7 +500,7 @@ internal sealed class NavigationEngine
|
|||
_watchdogNs = double.NaN;
|
||||
_watchdogEw = double.NaN;
|
||||
_watchdogNext = Now + (long)WatchdogMs;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_globalSettling = false;
|
||||
ResetRecovery("teleported");
|
||||
}
|
||||
|
|
@ -582,7 +620,7 @@ internal sealed class NavigationEngine
|
|||
if (dist < ReachFor(pt))
|
||||
{
|
||||
_host.Log($"Nav: arrived at [{idx}] dist={dist:F1}yd → advancing");
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
// Advance before the jump: the Jumper pauses nav and later restores what it
|
||||
// saw, so jumping first turned a finished Once route back on (re-run from [0]).
|
||||
|
|
@ -591,17 +629,33 @@ internal sealed class NavigationEngine
|
|||
return;
|
||||
}
|
||||
|
||||
// Closest-approach detection — prevents circling.
|
||||
// Matches old NavigationManager exactly.
|
||||
if (_prevDist < SweepFor(pt) && dist > _prevDist + 0.3)
|
||||
// First tick on this waypoint (or after a pause / escape / teleport): remember where
|
||||
// the approach starts, for the pass-through rule.
|
||||
if (_closestDist == double.MaxValue) { _legStartNs = ns; _legStartEw = ew; }
|
||||
|
||||
// Went past it: the point is behind, close enough to the side. Counts as reached
|
||||
// instead of turning round to walk back to it.
|
||||
if (PassedThrough(pt, ns, ew))
|
||||
{
|
||||
_host.Log($"Nav: sweep-pass [{idx}] prev={_prevDist:F1} now={dist:F1}yd → advancing");
|
||||
_prevDist = double.MaxValue;
|
||||
_host.Log($"Nav: passed [{idx}] dist={dist:F1}yd → advancing");
|
||||
_closestDist = double.MaxValue;
|
||||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
Advance(route);
|
||||
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
|
||||
return;
|
||||
}
|
||||
_prevDist = dist;
|
||||
|
||||
// Closest-approach detection — prevents circling: within the sweep radius, then
|
||||
// 0.3 yd farther out than the closest it came.
|
||||
if (_closestDist < SweepFor(pt) && dist > _closestDist + 0.3)
|
||||
{
|
||||
_host.Log($"Nav: sweep-pass [{idx}] closest={_closestDist:F1} now={dist:F1}yd → advancing");
|
||||
_closestDist = double.MaxValue;
|
||||
Advance(route);
|
||||
if (pt.Type == NavPointType.Jump) FireJump(pt, idx);
|
||||
return;
|
||||
}
|
||||
_closestDist = Math.Min(_closestDist, dist);
|
||||
|
||||
SteerToWaypoint(idx, pt, route, ns, ew, dist);
|
||||
}
|
||||
|
|
@ -622,7 +676,7 @@ internal sealed class NavigationEngine
|
|||
// closest-approach reading from before the pause says nothing about where we
|
||||
// are now; kept, the first tick back reads the displacement as a sweep-pass
|
||||
// and advances past a waypoint that was never reached.
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_stopRequestedAt = long.MaxValue;
|
||||
// A detour survives the pause: it re-plans on the way back if the pause
|
||||
// moved us. Whatever moved us, being far off the route afterwards is not
|
||||
|
|
@ -689,7 +743,7 @@ internal sealed class NavigationEngine
|
|||
|
||||
_host.Log($"Nav: macro start — {how} waypoint [{best}] ({Math.Sqrt(Sq(route.Points[best].NS - ns) + Sq(route.Points[best].EW - ew)) * 240.0:F0}yd) instead of [{cur}]");
|
||||
_settings.ActiveNavIndex = best;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_stuckCount = 0;
|
||||
_watchdogNs = double.NaN;
|
||||
_watchdogEw = double.NaN;
|
||||
|
|
@ -747,7 +801,7 @@ internal sealed class NavigationEngine
|
|||
_linearDir = 1;
|
||||
_stuckCount = 0;
|
||||
_recoveryKind = RecoveryKind.Jump;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_watchdogNs = double.NaN;
|
||||
_watchdogEw = double.NaN;
|
||||
_hasGoodHeading = false;
|
||||
|
|
@ -1146,7 +1200,7 @@ internal sealed class NavigationEngine
|
|||
private void Advance(NavRouteParser route)
|
||||
{
|
||||
int oldIdx = _settings.ActiveNavIndex;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_portalState = PortalState.None;
|
||||
// Reaching a waypoint is progress: the next snag gets a fresh detour budget.
|
||||
_detourAttempts = 0;
|
||||
|
|
@ -1238,7 +1292,7 @@ internal sealed class NavigationEngine
|
|||
/// current route's iteration direction. Used by the dense-waypoint
|
||||
/// skip loop in <see cref="Advance"/>. Mirrors the single-step logic
|
||||
/// in the main switch; factored out so the skip loop can call it
|
||||
/// without re-clearing _prevDist / _portalState.
|
||||
/// without re-clearing _closestDist / _portalState.
|
||||
/// </summary>
|
||||
private void AdvanceOneIndex(NavRouteParser route)
|
||||
{
|
||||
|
|
@ -1352,7 +1406,7 @@ internal sealed class NavigationEngine
|
|||
private void HoldAtCampRoute(int idx, double dist, NavRouteParser route)
|
||||
{
|
||||
if (_isMovingForward || _isTurning) StopMovement();
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
UpdateStatusLine(idx, dist, route, 0.0);
|
||||
if (!_campHoldAnnounced)
|
||||
{
|
||||
|
|
@ -1448,7 +1502,7 @@ internal sealed class NavigationEngine
|
|||
_host.Log($"Nav: no player id — cannot fire recall {pt.SpellId}");
|
||||
return;
|
||||
}
|
||||
_host.CastSpell(target, pt.SpellId);
|
||||
_host.CastSpellFor(target, pt.SpellId, "Nav", $"recall spell {pt.SpellId}");
|
||||
_host.Log($"Nav: CastSpell(recall {pt.SpellId}) on player 0x{target:X8}");
|
||||
}
|
||||
|
||||
|
|
@ -2229,7 +2283,7 @@ internal sealed class NavigationEngine
|
|||
// The escape moves us off the approach line, so the closest-approach
|
||||
// tracker's last reading is meaningless — reset it or the next steer
|
||||
// tick reads the retreat as a sweep-pass and advances the index.
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
}
|
||||
|
||||
// ══════════════════════════════════════════════════════════════════════════
|
||||
|
|
@ -2577,7 +2631,7 @@ internal sealed class NavigationEngine
|
|||
|
||||
StopMovement();
|
||||
_inRecovery = false;
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
_settings.NavIsStuck = true;
|
||||
return true;
|
||||
}
|
||||
|
|
@ -2604,7 +2658,7 @@ internal sealed class NavigationEngine
|
|||
+ $"reached {Math.Min(d.Index, d.Points.Count)}/{d.Points.Count}, door requests {d.DoorRequestCount}, re-plans {d.Replans}, "
|
||||
+ $"{(Now - d.StartedAt) / 1000.0:F1}s - result: {result}");
|
||||
|
||||
_prevDist = double.MaxValue;
|
||||
_closestDist = double.MaxValue;
|
||||
if (!_inRecovery) _settings.NavIsStuck = false;
|
||||
}
|
||||
|
||||
|
|
@ -2635,7 +2689,7 @@ internal sealed class NavigationEngine
|
|||
// against the deadline; if the pause moved us, plan again from here.
|
||||
d.Paused = false;
|
||||
d.DeadlineAt += Now - d.PausedAt;
|
||||
d.PrevDist = double.MaxValue;
|
||||
d.ClosestDist = double.MaxValue;
|
||||
double moved = double.IsNaN(d.PausedNs) ? 0.0 : NavYd(ns - d.PausedNs, ew - d.PausedEw);
|
||||
if (moved > DetourReplanMovedYd && !ReplanDetour(route, d, moved)) return;
|
||||
}
|
||||
|
|
@ -2650,10 +2704,10 @@ internal sealed class NavigationEngine
|
|||
|
||||
var p = d.Points[d.Index];
|
||||
double dist = NavYd(p.NS - ns, p.EW - ew);
|
||||
if (dist < ReachFor(p) || (d.PrevDist < SweepFor(p) && dist > d.PrevDist + 0.3))
|
||||
if (dist < ReachFor(p) || (d.ClosestDist < SweepFor(p) && dist > d.ClosestDist + 0.3))
|
||||
{
|
||||
d.Index++;
|
||||
d.PrevDist = double.MaxValue;
|
||||
d.ClosestDist = double.MaxValue;
|
||||
if (d.Index >= d.Points.Count)
|
||||
{
|
||||
// Back on the route: resume at the rejoin waypoint; normal nav walks the last leg.
|
||||
|
|
@ -2662,7 +2716,7 @@ internal sealed class NavigationEngine
|
|||
}
|
||||
return;
|
||||
}
|
||||
d.PrevDist = dist;
|
||||
d.ClosestDist = Math.Min(d.ClosestDist, dist);
|
||||
|
||||
// Aim point: blend toward the following point near arrival, but less than the
|
||||
// route does (doorways are narrow).
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ internal sealed class RadarWallRenderer
|
|||
private readonly bool[] _inside = new bool[MaxPolyVerts];
|
||||
|
||||
private static readonly string ExploredDir =
|
||||
@"C:\Games\RynthSuite\RynthAi\ExploredDungeons";
|
||||
System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ExploredDungeons");
|
||||
|
||||
public RadarWallRenderer(RynthCoreHost host, LegacyUiSettings settings)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra attackable — check if target is attackable");
|
||||
ChatLine("[RynthAi] /ra wielded — show wielded items");
|
||||
ChatLine("[RynthAi] /ra dumpprops [0xId] — every property of the selection (else yourself)");
|
||||
ChatLine("[RynthAi] /ra iteminfo [name] — the selected (or named) item's details, Mag-Tools style");
|
||||
ChatLine("[RynthAi] /ra mexec <expr> — evaluate meta expression");
|
||||
ChatLine("[RynthAi] /ra listvars — show session variables");
|
||||
ChatLine("[RynthAi] /ra listpvars — show persistent variables");
|
||||
|
|
@ -68,6 +69,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] /ra hazard add|del|list|near — mark current cell as lava/acid so patrol avoids it");
|
||||
ChatLine("[RynthAi] /ra jump[swzxc] [heading] [holdtime] — jump with optional face/direction (s=run w=fwd x=back z=strafeL c=strafeR)");
|
||||
ChatLine("[RynthAi] /ra corpseinfo — show corpse range/open diagnostics");
|
||||
ChatLine("[RynthAi] /ra pace — what the server is still answering (one action at a time)");
|
||||
ChatLine("[RynthAi] /ra owncorpse [go|stop] — where your corpse is; travel back to it, or stop");
|
||||
ChatLine("[RynthAi] /ra corpsecheck — explain whether a corpse would be looted");
|
||||
ChatLine("[RynthAi] /ra corpseopen — force the nearest corpse open flow");
|
||||
|
|
@ -240,7 +242,7 @@ public sealed partial class RynthAiPlugin
|
|||
return;
|
||||
}
|
||||
|
||||
bool ok = Host.CastSpell(_currentTargetId, spellId);
|
||||
bool ok = Host.CastSpellFor(_currentTargetId, spellId, "Command", $"spell {spellId} (/ra cast)", asked: true);
|
||||
ChatLine($"[RynthAi] CastSpell(target=0x{_currentTargetId:X8}, spell={spellId}) => {ok}");
|
||||
}
|
||||
|
||||
|
|
@ -2148,6 +2150,8 @@ public sealed partial class RynthAiPlugin
|
|||
private void HandleClearBusyCommand()
|
||||
{
|
||||
int before = Host.HasGetBusyState ? Host.GetBusyState() : -1;
|
||||
// You asked for it: forget what the pacing waits on too (ActionPacer).
|
||||
RynthCore.Plugin.Shared.ActionPacer.Forget("/ra clearbusy");
|
||||
if (Host.HasForceResetBusyCount)
|
||||
Host.ForceResetBusyCount();
|
||||
if (Host.HasStopCompletely)
|
||||
|
|
@ -2171,9 +2175,10 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
int before = Host.HasGetBusyState ? Host.GetBusyState() : -1;
|
||||
ChatLine("[RynthAi] PANIC — full AC state reset");
|
||||
RynthCore.Plugin.Shared.ActionPacer.Forget("/ra panic");
|
||||
|
||||
if (Host.HasCancelAttack) Host.CancelAttack();
|
||||
if (Host.HasChangeCombatMode) Host.ChangeCombatMode(CombatMode.NonCombat);
|
||||
if (Host.HasChangeCombatMode) Host.ChangeCombatModeFor(CombatMode.NonCombat, "Command", "/ra panic", force: true);
|
||||
if (Host.HasStopCompletely) Host.StopCompletelyBy("Command");
|
||||
if (Host.HasForceResetBusyCount) Host.ForceResetBusyCount();
|
||||
// The item-action lock itself is not the busy count: AC refuses every use,
|
||||
|
|
@ -2612,7 +2617,7 @@ public sealed partial class RynthAiPlugin
|
|||
string playerPart = argStr.Substring(toIdx + 4).Trim();
|
||||
|
||||
// Resolve profile path — bare name resolved from ItemGiver dir, .utl extension added if needed
|
||||
const string itemGiverDir = @"C:\Games\RynthSuite\RynthAi\ItemGiver";
|
||||
string itemGiverDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "ItemGiver");
|
||||
string profilePath = System.IO.Path.IsPathRooted(profileArg)
|
||||
? profileArg
|
||||
: System.IO.Path.Combine(itemGiverDir, profileArg);
|
||||
|
|
@ -2975,7 +2980,7 @@ public sealed partial class RynthAiPlugin
|
|||
sb.Append("\"routes\":[");
|
||||
try
|
||||
{
|
||||
const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
|
||||
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
if (System.IO.Directory.Exists(navFolder))
|
||||
{
|
||||
var files = System.IO.Directory.GetFiles(navFolder, "*.nav");
|
||||
|
|
|
|||
189
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs
Normal file
189
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.ItemInfo.cs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
/// <summary>
|
||||
/// /ra iteminfo [name]: a selected (or named) item's details on one chat line, Mag-Tools
|
||||
/// style (ItemInfo/ItemInfoText). An item the client hasn't appraised is identified first
|
||||
/// and printed when the appraisal arrives, or after <see cref="ItemInfoTimeoutMs"/> with
|
||||
/// what the client has. Partial class of RynthAiPlugin.
|
||||
///
|
||||
/// Threads: the command only queues its argument; <see cref="TickItemInfo"/> on the plugin
|
||||
/// tick does every host read, the ID request and the print. Nothing is drawn.
|
||||
/// </summary>
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
internal const long ItemInfoTimeoutMs = 5000;
|
||||
|
||||
/// <summary>Test seam: the clock the ID timeout runs on.</summary>
|
||||
internal static Func<long> ItemInfoClock = () => Environment.TickCount64;
|
||||
|
||||
private readonly ConcurrentQueue<string> _itemInfoRequests = new();
|
||||
// One item waiting for its appraisal at a time (tick thread only); a newer request replaces it.
|
||||
private uint _itemInfoPendingId;
|
||||
private long _itemInfoDeadline;
|
||||
|
||||
/// <summary>/ra iteminfo [item name]. Queued for the next tick.</summary>
|
||||
private void HandleItemInfoCommand(string[] parts)
|
||||
{
|
||||
string arg = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty;
|
||||
if (arg.Equals("help", StringComparison.OrdinalIgnoreCase) || arg == "?")
|
||||
{
|
||||
ChatLine("[RynthAi] /ra iteminfo - the selected item's details (identifies it first when needed).");
|
||||
ChatLine("[RynthAi] /ra iteminfo <name> - the first item in your inventory with that name (else one whose name contains it).");
|
||||
return;
|
||||
}
|
||||
if (_itemInfoRequests.Count < 8) _itemInfoRequests.Enqueue(arg);
|
||||
}
|
||||
|
||||
/// <summary>Plugin tick: starts queued requests, prints an item once its ID lands or times out.</summary>
|
||||
private void TickItemInfo()
|
||||
{
|
||||
while (_itemInfoRequests.TryDequeue(out string? arg))
|
||||
StartItemInfo(arg);
|
||||
|
||||
uint selected = System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, 0);
|
||||
if (selected != 0)
|
||||
StartItemInfoFor(selected, quiet: true);
|
||||
|
||||
uint pending = _itemInfoPendingId;
|
||||
if (pending == 0) return;
|
||||
bool appraised = !Host.HasHasAppraisalData || Host.HasAppraisalData(pending);
|
||||
if (appraised || ItemInfoClock() >= _itemInfoDeadline)
|
||||
{
|
||||
_itemInfoPendingId = 0;
|
||||
PrintItemInfo(pending, identified: appraised);
|
||||
}
|
||||
}
|
||||
|
||||
private void StartItemInfo(string arg)
|
||||
{
|
||||
uint id;
|
||||
if (arg.Length == 0)
|
||||
{
|
||||
id = Host.HasGetSelectedItemId ? Host.GetSelectedItemId() : 0;
|
||||
if (id == 0)
|
||||
{
|
||||
ChatLine("[RynthAi] Item info: nothing selected. Select an item, or /ra iteminfo <name>.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
id = FindInventoryItemByName(arg);
|
||||
if (id == 0)
|
||||
{
|
||||
ChatLine($"[RynthAi] Item info: no \"{arg}\" in your inventory.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
StartItemInfoFor(id, quiet: false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prints <paramref name="id"/> now when it's appraised, else asks for its ID and prints when
|
||||
/// it lands. <paramref name="quiet"/> (Item Info On Select): no "identifying" chatter.
|
||||
/// </summary>
|
||||
private void StartItemInfoFor(uint id, bool quiet)
|
||||
{
|
||||
if (!Host.HasHasAppraisalData || Host.HasAppraisalData(id))
|
||||
{
|
||||
if (_itemInfoPendingId == id) _itemInfoPendingId = 0;
|
||||
PrintItemInfo(id, identified: true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!quiet && _itemInfoPendingId != 0 && _itemInfoPendingId != id)
|
||||
ChatLine($"[RynthAi] Item info: stopped waiting for {ObjectNameOr(_itemInfoPendingId)}.");
|
||||
if (Host.HasRequestId) Host.RequestId(id);
|
||||
_itemInfoPendingId = id;
|
||||
_itemInfoDeadline = ItemInfoClock() + ItemInfoTimeoutMs;
|
||||
if (!quiet) ChatLine($"[RynthAi] Item info: identifying {ObjectNameOr(id)}...");
|
||||
}
|
||||
|
||||
// Item Info On Select: the item the player just selected, for the next tick (0 = none).
|
||||
private uint _itemInfoSelectId;
|
||||
|
||||
/// <summary>
|
||||
/// Selection change (OnSelectedTargetChange): queues Item Info for an item the player
|
||||
/// selected. Skips non-items and RynthAi's own selections (the looter, metas).
|
||||
/// </summary>
|
||||
private void QueueItemInfoOnSelect(uint id, WorldObject? obj)
|
||||
{
|
||||
if (id == 0 || _dashboard?.Settings is not { ItemInfoOnSelect: true }) return;
|
||||
if (obj == null || !IsLootableClass(obj.ObjectClass)) return;
|
||||
if (SelfSelect.IsOurs(id)) return;
|
||||
System.Threading.Interlocked.Exchange(ref _itemInfoSelectId, id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An inventory item (carried or worn) whose name is <paramref name="name"/>, ignoring case;
|
||||
/// else the first whose name contains it. 0 when none.
|
||||
/// </summary>
|
||||
private uint FindInventoryItemByName(string name)
|
||||
{
|
||||
if (_objectCache == null) return 0;
|
||||
uint partial = 0;
|
||||
foreach (WorldObject wo in _objectCache.GetInventory())
|
||||
{
|
||||
if (wo.Name.Length == 0) continue;
|
||||
if (wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) return unchecked((uint)wo.Id);
|
||||
if (partial == 0 && wo.Name.Contains(name, StringComparison.OrdinalIgnoreCase)) partial = unchecked((uint)wo.Id);
|
||||
}
|
||||
return partial;
|
||||
}
|
||||
|
||||
private string ObjectNameOr(uint id) =>
|
||||
Host.TryGetObjectName(id, out string n) && n.Length > 0 ? n : $"0x{id:X8}";
|
||||
|
||||
private void PrintItemInfo(uint id, bool identified)
|
||||
{
|
||||
var source = new HostItemInfoSource(Host, id);
|
||||
ChatLine("[RynthAi] " + ItemInfoText.Describe(source, SpellDatabase.GetSpellName, identified));
|
||||
}
|
||||
|
||||
/// <summary>The live appraisal through the host (tick thread).</summary>
|
||||
private sealed class HostItemInfoSource : IItemInfoSource
|
||||
{
|
||||
private readonly RynthCoreHost _host;
|
||||
private readonly uint _id;
|
||||
|
||||
public HostItemInfoSource(RynthCoreHost host, uint id)
|
||||
{
|
||||
_host = host;
|
||||
_id = id;
|
||||
Name = host.TryGetObjectName(id, out string n) ? n : string.Empty;
|
||||
SpellIds = ReadSpells(host, id);
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
public IReadOnlyList<int> SpellIds { get; }
|
||||
|
||||
public bool TryInt(uint key, out int value)
|
||||
{
|
||||
value = 0;
|
||||
return _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(_id, key, out value);
|
||||
}
|
||||
|
||||
public bool TryFloat(uint key, out double value)
|
||||
{
|
||||
value = 0;
|
||||
return _host.TryGetObjectDoubleProperty(_id, key, out value);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<int> ReadSpells(RynthCoreHost host, uint id)
|
||||
{
|
||||
if (!host.HasGetObjectSpellIds) return Array.Empty<int>();
|
||||
var buf = new uint[64];
|
||||
int n = host.GetObjectSpellIds(id, buf, buf.Length);
|
||||
if (n <= 0) return Array.Empty<int>();
|
||||
var list = new List<int>(n);
|
||||
for (int i = 0; i < n && i < buf.Length; i++) list.Add(unchecked((int)buf[i]));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
66
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs
Normal file
66
Plugins/RynthCore.Plugin.RynthAi/RynthAiPlugin.Pacing.cs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
using System;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthAi;
|
||||
|
||||
// ============================================================================
|
||||
// RynthAi's side of the action pacing (Plugins/Shared/ActionPacer.cs, 2026-10-06).
|
||||
// Every use / use-on RynthAi sends is recorded as the server action it waits on;
|
||||
// casts and mode changes record themselves (CastSpellFor / ChangeCombatModeFor).
|
||||
// The managers that only see a busy count (inventory, salvage, mana stones, pets)
|
||||
// get PacedBusy: the count, plus one while a server action is unanswered.
|
||||
// ============================================================================
|
||||
public sealed partial class RynthAiPlugin
|
||||
{
|
||||
/// <summary>UseAudit.AfterSend: a use or use-on went out - record it as the action the server is answering.</summary>
|
||||
private static void RecordUseForPacing(RynthCoreHost host, UseAudit.SentUse use)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The salvage panel (a UST use) opens on the client; the server answered only 7 of 18
|
||||
// of them with a UseDone in the 10-05/10-06 logs, so it is not waited on.
|
||||
if (use.Subsystem == "Salvage" || use.What.Contains("'Ust'", StringComparison.OrdinalIgnoreCase))
|
||||
return;
|
||||
PacedKind kind;
|
||||
uint player = host.HasGetPlayerId ? host.GetPlayerId() : 0;
|
||||
if (use.TargetId != 0)
|
||||
{
|
||||
// Something on a target: on yourself (kit, stone, food) it is an item use; on a
|
||||
// door/corpse or anything else in the world the server walks there first.
|
||||
kind = use.TargetId == player
|
||||
? PacedKind.ItemUse
|
||||
: ActionPacer.ClassifyUse(host, use.TargetId, use.DoorOrCorpse);
|
||||
}
|
||||
else
|
||||
{
|
||||
kind = ActionPacer.ClassifyUse(host, use.ObjectId, use.DoorOrCorpse);
|
||||
}
|
||||
string who = "RynthAi/" + use.Subsystem + (use.Kind == UseKind.Asked ? " (asked)" : "");
|
||||
ActionPacer.Begin(host, kind, use.ObjectId, use.What, who, use.UseDoneSeqBefore);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The busy count the item managers gate on (inventory, salvage, mana stones, pets): our mirror of
|
||||
/// AC's count, plus one while a server action is unanswered so they don't start one on top of it.
|
||||
/// </summary>
|
||||
private int PacedBusy
|
||||
{
|
||||
get
|
||||
{
|
||||
int busy = _busyCount;
|
||||
if (ActionPacer.Enabled && ActionPacer.Current(Host) != null) busy++;
|
||||
return busy;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>/ra pace: what the pacing is waiting on, and its counters.</summary>
|
||||
private void HandlePaceCommand()
|
||||
{
|
||||
foreach (string line in ActionPacer.DescribeLines(Host))
|
||||
ChatLine("[RynthAi] " + line);
|
||||
ChatLine($"[RynthAi] Busy mirror {_busyCount} (shadow resets only; the client's count is never force-cleared by RynthAi now)");
|
||||
}
|
||||
}
|
||||
|
|
@ -165,11 +165,21 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// and never reads Host.ImGuiContext.)
|
||||
ComponentDatabase.SetLog(msg => Log(msg));
|
||||
_dashboard = new LegacyDashboardRenderer(Host);
|
||||
_killClock.MacroRunning = () => _dashboard?.Settings.IsMacroRunning == true;
|
||||
_dashboard.KillClock = _killClock;
|
||||
// Every use goes through Host.UseFor (Plugins/Shared/UseAudit.cs): one log line
|
||||
// each, and no automatic door/corpse use while the macro is off.
|
||||
RynthCore.Plugin.Shared.UseAudit.Reset("RynthAi", () => _dashboard?.Settings.IsMacroRunning == true);
|
||||
// Every movement call is logged with its subsystem (Plugins/Shared/MoveAudit.cs).
|
||||
RynthCore.Plugin.Shared.MoveAudit.Reset();
|
||||
// A door/corpse use the server is still answering holds RynthAi's own moves and turns
|
||||
// (moving would cancel the server's walk/turn to it; 2026-10-06).
|
||||
RynthCore.Plugin.Shared.UseAudit.TrackWorldUses = true;
|
||||
// One server action at a time (Plugins/Shared/ActionPacer.cs, 2026-10-06): every use,
|
||||
// use-on, cast and combat-mode change waits for the server's answer to the last one.
|
||||
RynthCore.Plugin.Shared.ActionPacer.Reset();
|
||||
RynthCore.Plugin.Shared.ActionPacer.Enabled = true;
|
||||
RynthCore.Plugin.Shared.UseAudit.AfterSend = RecordUseForPacing;
|
||||
_objectCache = new WorldObjectCache(Host); // must exist before CreateObject events fire during login
|
||||
// Items we use (or use something on) get re-identified before a meta reads them.
|
||||
// ObjectUsed is a static event and Shutdown never unsubscribes: when the engine
|
||||
|
|
@ -217,6 +227,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_dashboard = null;
|
||||
// Don't let the static audit hold this instance once it's gone (a reused module).
|
||||
RynthCore.Plugin.Shared.UseAudit.MacroOn = static () => false;
|
||||
RynthCore.Plugin.Shared.UseAudit.AfterSend = null;
|
||||
RynthCore.Plugin.Shared.ActionPacer.Enabled = false;
|
||||
RynthCore.Plugin.Shared.ActionPacer.Forget("shutdown");
|
||||
|
||||
// Give the heap back. When a changed RynthAi is deployed, the engine loads
|
||||
// it as a new copy and this one is abandoned for good (a NativeAOT DLL can't
|
||||
|
|
@ -345,6 +358,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
private void TeardownSession()
|
||||
{
|
||||
ObjectChangeTracker.Clear();
|
||||
// The server drops whatever it was doing for this character at logout.
|
||||
RynthCore.Plugin.Shared.ActionPacer.Forget("logout");
|
||||
_navigationEngine?.Stop();
|
||||
_navigationEngine = null;
|
||||
// The dungeon cell graph is a static single-landblock cache; nothing may outlive the session.
|
||||
|
|
@ -365,6 +380,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
}
|
||||
_combatManager?.Dispose();
|
||||
_combatManager = null;
|
||||
// A relog is what clears a server that refuses every use: start the next session clean.
|
||||
ResetUseRefusalState();
|
||||
Log($"RynthAi: TeardownSession — RadarWallFlush={tFlushMs} ms, RaycastDispose={tRayMs} ms");
|
||||
_fellowshipTracker?.Dispose();
|
||||
_fellowshipTracker = null;
|
||||
|
|
@ -452,6 +469,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
|
||||
_loginCompletedAt = DateTime.Now;
|
||||
_loginComplete = true;
|
||||
_killClock.SessionStarted();
|
||||
_dashboard.OnLoginComplete();
|
||||
_dashboard.ChatSubmitHandler = HandleRynthChatSubmit;
|
||||
_navigationEngine = new NavigationEngine(Host, _dashboard.Settings)
|
||||
|
|
@ -607,6 +625,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
|
||||
_combatManager = new CombatManager(Host, _dashboard.Settings, _objectCache!, _spellManager);
|
||||
_combatManager.SetWeaponSwapGate(_weaponSwapGate);
|
||||
_combatManager.HoldIdlePeace = LootHoldsIdlePeace;
|
||||
_combatManager.SetStaleBusyCallback(OnCombatBusyStale);
|
||||
_buffManager?.SetStaleBusyCallback(OnCombatBusyStale); // a heal ahead of a leftover busy count
|
||||
if (_buffManager != null)
|
||||
|
|
@ -646,6 +665,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_metaManager.SetQuestTracker(_questTracker);
|
||||
if (_buffManager != null) _metaManager.SetBuffManager(_buffManager);
|
||||
_metaManager.SetCreatureStore(_creatureStore);
|
||||
_metaManager.SetKillClock(_killClock);
|
||||
if (_dashboard != null)
|
||||
_dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot();
|
||||
|
||||
|
|
@ -698,6 +718,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// decides whether nav runs at all. One edge-detect replaces the cascade.
|
||||
private BotActivity _activity = BotActivity.Idle; // last arbiter decision
|
||||
private bool _macroWasRunning; // edge: release held turns when the macro stops
|
||||
|
||||
// Time since our last kill (KillerNotification only): secondssincelastkill[], the
|
||||
// No Kills Within Minutes meta condition and the status feed. Counts from login / plugin
|
||||
// load, then from each macro start, until the first kill.
|
||||
private readonly KillClock _killClock = new();
|
||||
internal KillClock Kills => _killClock;
|
||||
private BotActivity _navStoppedFor = BotActivity.Idle; // activity we last issued a nav Stop() for
|
||||
private bool _navStopIssued;
|
||||
// Buffing-coma watchdog (see the Priority-1 block): how long BotAction has
|
||||
|
|
@ -733,8 +759,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_navStopIssued = true;
|
||||
_navStoppedFor = owner;
|
||||
|
||||
bool ownMovement = RynthCore.Plugin.Shared.MoveAudit.OwnMovementActive; // before nav's own stops clear it
|
||||
_navigationEngine?.Stop();
|
||||
if (Host.HasStopCompletely)
|
||||
// A StopCompletely only when RynthAi itself has the character moving (2026-10-06): with
|
||||
// nothing of ours moving it is one more movement packet on the server's motion - 116 in 46
|
||||
// minutes on 10-06, on every change of activity - and it cut off movement another plugin
|
||||
// (RynthNav, RynthLua) had just started (analysis by Silentkelpie). RynthNav's travel is
|
||||
// stopped by its own command (TickOwnCorpseTravel). Without the pacing, as before.
|
||||
if (Host.HasStopCompletely
|
||||
&& (!RynthCore.Plugin.Shared.ActionPacer.Enabled || ownMovement))
|
||||
Host.StopCompletelyBy("Arbiter");
|
||||
|
||||
// Combat taking the tick invalidates any in-progress door interaction.
|
||||
|
|
@ -846,7 +879,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
["MonsterRange"] = (1, 200), ["MonsterDisengageRange"] = (0, 200), ["RingRange"] = (1, 50), ["ApproachRange"] = (1, 50),
|
||||
["CorpseApproachRangeMax"] = (0.5, 50), ["CorpseApproachRangeMin"] = (0.5, 20),
|
||||
["FollowNavMin"] = (0.5, 20), ["NavRingThickness"] = (1, 16), ["NavLineThickness"] = (1, 16),
|
||||
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0),
|
||||
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["NavLabelMode"] = (0, 2), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 0),
|
||||
["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10),
|
||||
["NavLookaheadYards"] = (0, 30), ["NavShortcutYards"] = (0, 10), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30),
|
||||
["NavOffTrackYards"] = (160, 1000), ["NavMaxDetourAttempts"] = (1, 10),
|
||||
|
|
@ -1358,10 +1391,13 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// to run only inside the legacy dashboard's Render(), which the engine no
|
||||
// longer calls, so edits waited for the next login. A flag check when idle.
|
||||
_dashboard?.TickMonsterReload();
|
||||
// A nav saved into NavProfiles from outside (RynthNav's "save as nav route"): list it.
|
||||
_dashboard?.TickNavFolder();
|
||||
_questTracker?.Tick();
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after quest tracker");
|
||||
DrainGiveQueue();
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after drain give queue");
|
||||
if (_loginComplete) TickItemInfo();
|
||||
_jumper?.Tick();
|
||||
if (diag) Host.Log("[RynthAi] OnTick: after jumper tick");
|
||||
|
||||
|
|
@ -1487,6 +1523,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
if (!_macroWasRunning && settings.IsMacroRunning)
|
||||
_navigationEngine?.ResumeFromNearestWaypoint();
|
||||
_macroWasRunning = settings.IsMacroRunning;
|
||||
_killClock.ObserveMacro(settings.IsMacroRunning); // a start counts even if nothing reads the clock meanwhile
|
||||
|
||||
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
|
||||
{
|
||||
|
|
@ -1589,6 +1626,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
_combatEndedAt = nowMs;
|
||||
|
||||
bool wantLoot = HasLootWork(settings, nowMs);
|
||||
_lastWantLoot = wantLoot;
|
||||
bool wantSalvage = _salvageManager != null && _salvageManager.IsBusy;
|
||||
bool routeLoaded = settings.CurrentRoute != null && settings.CurrentRoute.Points.Count > 0;
|
||||
|
||||
|
|
@ -1735,7 +1773,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
&& _openedContainerId == 0
|
||||
&& _targetCorpseId == 0)
|
||||
{
|
||||
_inventoryManager.OnHeartbeat(_busyCount);
|
||||
_inventoryManager.OnHeartbeat(PacedBusy);
|
||||
}
|
||||
|
||||
// Status feed: main-pack empty slots (cache-based, off-thread-safe). Throttled to
|
||||
|
|
@ -1808,7 +1846,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// combine work while a threat is up so it doesn't contend with
|
||||
// combat over SelectItem; it resumes the moment the threat clears.
|
||||
if (inventorySettled && !combatThreat)
|
||||
_salvageManager?.OnTick(_busyCount);
|
||||
_salvageManager?.OnTick(PacedBusy);
|
||||
if (diag) Host.Log("[RynthAi] OnTick: before manaStoneManager");
|
||||
|
||||
// STEP 4: the salvage gap-fill that used to pin/release
|
||||
|
|
@ -1821,8 +1859,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
// decision from scratch every tick.
|
||||
|
||||
// Mana stone tapping — runs after salvage, independent of looting state.
|
||||
_manaStoneManager?.OnHeartbeat(_busyCount);
|
||||
_petManager?.OnHeartbeat(_busyCount);
|
||||
_manaStoneManager?.OnHeartbeat(PacedBusy);
|
||||
_petManager?.OnHeartbeat(PacedBusy);
|
||||
if (diag) Host.Log("[RynthAi] OnTick: before combatManager");
|
||||
|
||||
// Missile crafting runs before combat — blocks everything while active.
|
||||
|
|
@ -1960,13 +1998,14 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
if (Host.HasQueryHealth) Host.QueryHealth(currentTargetId);
|
||||
}
|
||||
|
||||
if (_lootInspectMode && currentTargetId != 0)
|
||||
if (currentTargetId != 0)
|
||||
{
|
||||
int sid = unchecked((int)currentTargetId);
|
||||
WorldObject? obj = _objectCache?[sid];
|
||||
// Skip non-items (monsters, players, NPCs, doors, corpses, portals, etc.)
|
||||
if (obj != null && IsLootableClass(obj.ObjectClass))
|
||||
if (_lootInspectMode && obj != null && IsLootableClass(obj.ObjectClass))
|
||||
InspectLootRuleForItem(sid, quiet: true);
|
||||
QueueItemInfoOnSelect(currentTargetId, obj);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2011,6 +2050,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
public override void OnKillNotification(string? deathMessage)
|
||||
{
|
||||
if (string.IsNullOrEmpty(deathMessage)) return;
|
||||
_killClock.RecordKill(); // the only kill source: KillerNotification goes to the killer alone
|
||||
_combatManager?.OnKillNotification(deathMessage);
|
||||
_dashboard?.RecordKill(); // feeds the kills/hour session stat
|
||||
}
|
||||
|
|
@ -3026,6 +3066,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "listpvars": HandleListPvarsCommand(); break;
|
||||
case "listgvars": HandleListGvarsCommand(); break;
|
||||
case "dumpprops": HandleDumpPropsCommand(parts); break;
|
||||
case "iteminfo": HandleItemInfoCommand(parts); break;
|
||||
case "version": HandleVersionCommand(); break;
|
||||
case "wielded": HandleWieldedCommand(); break;
|
||||
case "scan": HandleScanCommand(); break;
|
||||
|
|
@ -3052,6 +3093,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
|||
case "lootcheck": HandleLootCheckSelectedCommand(parts); break;
|
||||
case "loot": HandleLootCommand(parts); break;
|
||||
case "corpseinfo": HandleCorpseInfoCommand(); break;
|
||||
case "pace": HandlePaceCommand(); break;
|
||||
case "corpsecheck": HandleCorpseCheckCommand(parts); break;
|
||||
case "corpseopen": HandleCorpseOpenCommand(); break;
|
||||
case "owncorpse":
|
||||
|
|
|
|||
|
|
@ -39,6 +39,10 @@
|
|||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
<!-- Movement calls logged with the subsystem that sent them (stuck-cast diagnosis, 2026-10-05). -->
|
||||
<Compile Include="..\Shared\MoveAudit.cs" Link="Shared\MoveAudit.cs" />
|
||||
<!-- One server action at a time, paced on the server's answers (stuck use/cast, 2026-10-06). -->
|
||||
<Compile Include="..\Shared\ActionPacer.cs" Link="Shared\ActionPacer.cs" />
|
||||
<!-- Text in the world on the Nav3D buffer (waypoint labels; RynthNav's path markers use it too). -->
|
||||
<Compile Include="..\Shared\Nav3DText.cs" Link="Shared\Nav3DText.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
@ -93,4 +97,9 @@
|
|||
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ namespace RynthCore.Plugin.RynthAi.Trade;
|
|||
/// </summary>
|
||||
internal sealed class AutoTradeManager
|
||||
{
|
||||
public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoTrade";
|
||||
public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoTrade");
|
||||
public const string ProfileSubfolder = "AutoTrade";
|
||||
public const string AutoAcceptListFileName = "autoAcceptList.json";
|
||||
public const uint RequiredApiVersion = 72;
|
||||
|
|
|
|||
|
|
@ -170,7 +170,7 @@ public sealed partial class RynthAiPlugin
|
|||
{
|
||||
string n = name.Trim().Trim('"');
|
||||
if (File.Exists(n)) return n;
|
||||
const string folder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
foreach (string cand in new[] { n, n + ".utl", n + ".json" })
|
||||
{
|
||||
string p = Path.Combine(folder, cand);
|
||||
|
|
@ -236,7 +236,7 @@ public sealed partial class RynthAiPlugin
|
|||
int sp = args.IndexOf(' ');
|
||||
if (sp > 0 && int.TryParse(args.AsSpan(0, sp), out _)) file = args.Substring(sp + 1).Trim();
|
||||
file = file.Trim('"');
|
||||
if (!Path.IsPathRooted(file)) file = Path.Combine(@"C:\Games\RynthSuite\RynthAi", file);
|
||||
if (!Path.IsPathRooted(file)) file = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, file);
|
||||
if (!File.Exists(file)) { ChatLine($"[RynthAi] Sound file not found: {file}"); return; }
|
||||
try { PlaySound(file, IntPtr.Zero, 0x00020000 /*SND_FILENAME*/ | 0x0001 /*SND_ASYNC*/); }
|
||||
catch (Exception ex) { ChatLine($"[RynthAi] playsound failed: {ex.Message}"); }
|
||||
|
|
@ -352,7 +352,7 @@ public sealed partial class RynthAiPlugin
|
|||
ChatLine("[RynthAi] Usage: /ub translateroute <startLandblock> <routeToLoad> <endLandblock> <routeToSaveAs> [force]");
|
||||
return;
|
||||
}
|
||||
const string navFolder = @"C:\Games\RynthSuite\RynthAi\NavProfiles";
|
||||
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
string inPath = Path.IsPathRooted(w[1]) ? w[1] : Path.Combine(navFolder, w[1]);
|
||||
string outPath = Path.IsPathRooted(w[3]) ? w[3] : Path.Combine(navFolder, w[3]);
|
||||
if (!outPath.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) outPath += ".nav";
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ namespace RynthCore.Plugin.RynthAi.Vendor;
|
|||
/// </summary>
|
||||
internal sealed class AutoVendorManager
|
||||
{
|
||||
public const string MainProfileDir = @"C:\Games\RynthSuite\RynthAi\AutoVendor";
|
||||
public static readonly string MainProfileDir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor");
|
||||
public const string ProfileSubfolder = "AutoVendor";
|
||||
|
||||
private const long BailMs = 60_000; // UB bailTimer
|
||||
|
|
|
|||
|
|
@ -44,4 +44,9 @@
|
|||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -10,11 +10,11 @@ namespace RynthCore.Plugin.RynthLua;
|
|||
/// </summary>
|
||||
internal static class RynthLuaPaths
|
||||
{
|
||||
/// <summary>RynthLua's folder: Scripts\, Data\, settings.json, editor.lua.</summary>
|
||||
public static string Root { get; set; } = @"C:\Games\RynthSuite\RynthLua";
|
||||
/// <summary>RynthLua's folder: Scripts\, Data\, settings.json, editor.lua (<SuiteDir>\RynthLua, C:\Games\RynthSuite\RynthLua by default).</summary>
|
||||
public static string Root { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthLua");
|
||||
|
||||
/// <summary>Where scripts lived while Lua was part of RynthAi (copied over once, then left alone).</summary>
|
||||
public static string LegacyScripts { get; set; } = @"C:\Games\RynthSuite\RynthAi\LuaScripts";
|
||||
public static string LegacyScripts { get; set; } = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LuaScripts");
|
||||
|
||||
public static string Scripts => Path.Combine(Root, "Scripts");
|
||||
public static string Data => Path.Combine(Root, "Data");
|
||||
|
|
|
|||
203
Plugins/RynthCore.Plugin.RynthNav/NavRouteExport.cs
Normal file
203
Plugins/RynthCore.Plugin.RynthNav/NavRouteExport.cs
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// "Save as nav route": a planned trip as a RynthAi nav route (uTank2 NAV 1.2, the VTank format
|
||||
/// RynthAi reads and writes; RynthAi's own NavRouteParser, linked in, does the writing), so RynthAi
|
||||
/// can load it from NavProfiles and run it. Route type Once.
|
||||
///
|
||||
/// a walk step its path's waypoints (Point), thinned (TripPathBuilder.Thin): not every
|
||||
/// navmesh corner, a point at least every 60 yd on straight ground
|
||||
/// a portal step the walk up to PortalStopShort yd before the entrance, then a Portal step
|
||||
/// (VTank "Portal", type 6) naming the portal object, at the entrance: RynthAi
|
||||
/// uses it by name (the nearest one) and walks the last yards itself
|
||||
/// a recall spell a Recall step (type 2) with the spell id, cast where the trip stands
|
||||
/// a command recall (@lifestone, @house recall...): a Chat step with the command, then a Pause
|
||||
/// of CommandRecallPauseMs (RynthAi doesn't wait for a chat command's teleport)
|
||||
/// the Town Network the walk inside (townnet.json) as waypoints, then a Portal step for the exit
|
||||
/// a dungeon goto ends with the Portal step into the dungeon's entrance portal
|
||||
/// A step it can't write (a recall the plan doesn't know, a Town Network walk townnet.json doesn't
|
||||
/// have) stops the route there: what comes before is kept, and the reason is given.
|
||||
/// Host-free: the route tests convert made-up trips and read the file back with RynthAi's reader.
|
||||
/// </summary>
|
||||
internal static class NavRouteExport
|
||||
{
|
||||
/// <summary>The walk to a portal stops this far short of its entrance (the Portal step walks the rest).</summary>
|
||||
public const double PortalStopShort = 5.0;
|
||||
/// <summary>Inside the Town Network the stored walk ends at the exit portal: stop this far short.</summary>
|
||||
public const double HubStopShort = 2.0;
|
||||
/// <summary>After a command recall's chat step: wait this long for its teleport (ms).</summary>
|
||||
public const int CommandRecallPauseMs = 20000;
|
||||
/// <summary>VTank's object class for a portal (the Portal step's second trailer line).</summary>
|
||||
public const int PortalObjectClass = 14;
|
||||
|
||||
public sealed class Result
|
||||
{
|
||||
public NavRouteParser Route = new() { RouteType = NavRouteType.Once };
|
||||
/// <summary>The step (0-based) the route stops at, short of the trip's end; -1 = the whole trip.</summary>
|
||||
public int StoppedAt = -1;
|
||||
public string StopReason = "";
|
||||
public int Waypoints, Portals, Recalls, Chats;
|
||||
}
|
||||
|
||||
/// <summary>The trip as nav points (see the class notes). <paramref name="path"/> must be this trip's.</summary>
|
||||
public static Result Convert(PlannedTrip trip, TripPath path, TownNet? net)
|
||||
{
|
||||
var r = new Result();
|
||||
if (path.TripId != trip.Id) { r.StoppedAt = 0; r.StopReason = "the path was worked out for another trip"; return r; }
|
||||
WorldPt here = trip.Start; // where action steps happen when nothing better is known
|
||||
double lastH = double.IsNaN(trip.Start.H) ? 0 : trip.Start.H;
|
||||
|
||||
void Stop(int i, string why) { r.StoppedAt = i; r.StopReason = $"step {i + 1}: {why}"; }
|
||||
void AddPoint(WorldPt p)
|
||||
{
|
||||
if (!double.IsNaN(p.H)) lastH = p.H;
|
||||
r.Route.Points.Add(new NavPoint { Type = NavPointType.Point, NS = p.Ns, EW = p.Ew, Z = lastH / 240.0 });
|
||||
r.Waypoints++;
|
||||
here = p;
|
||||
}
|
||||
void AddPortal(string name, WorldPt at)
|
||||
{
|
||||
if (!double.IsNaN(at.H)) lastH = at.H;
|
||||
double ns = at.Ns, ew = at.Ew, z = lastH / 240.0;
|
||||
r.Route.Points.Add(new NavPoint
|
||||
{
|
||||
Type = NavPointType.PortalNPC, NS = ns, EW = ew, Z = z,
|
||||
TargetName = name, ObjectClass = PortalObjectClass, IsTie = true,
|
||||
PortalExitNS = ns, PortalExitEW = ew, PortalExitZ = z,
|
||||
});
|
||||
r.Portals++;
|
||||
}
|
||||
void Land(RouteStep s)
|
||||
{
|
||||
if (!double.IsNaN(s.LandNs)) here = WorldPt.FromMap(s.LandNs, s.LandEw, double.NaN);
|
||||
}
|
||||
|
||||
for (int i = 0; i < trip.Count; i++)
|
||||
{
|
||||
RouteStep s = trip.Steps[i];
|
||||
if (s.UseRecall)
|
||||
{
|
||||
TripRecall? rec = trip.RecallOf(i);
|
||||
if (rec is not TripRecall o) { Stop(i, $"the recall {s.Label} isn't one the plan knows how to cast"); return r; }
|
||||
WorldPt at = trip.Point[i] ?? here;
|
||||
double z = (double.IsNaN(at.H) ? lastH : at.H) / 240.0;
|
||||
if (o.SpellId != 0)
|
||||
{
|
||||
r.Route.Points.Add(new NavPoint { Type = NavPointType.Recall, NS = at.Ns, EW = at.Ew, Z = z, SpellId = o.SpellId });
|
||||
r.Recalls++;
|
||||
}
|
||||
else if (o.Command.Length > 0)
|
||||
{
|
||||
r.Route.Points.Add(new NavPoint { Type = NavPointType.Chat, NS = at.Ns, EW = at.Ew, Z = z, ChatCommand = o.Command });
|
||||
r.Route.Points.Add(new NavPoint { Type = NavPointType.Pause, NS = at.Ns, EW = at.Ew, Z = z, PauseTimeMs = CommandRecallPauseMs });
|
||||
r.Chats++;
|
||||
}
|
||||
else { Stop(i, $"{o.Name} has neither a spell nor a command"); return r; }
|
||||
Land(s);
|
||||
continue;
|
||||
}
|
||||
if (s.IsHub)
|
||||
{
|
||||
WorldPt[]? inside = path.Hub[i];
|
||||
WorldPt? exit = PlannedTrip.HubExitPoint(net, s);
|
||||
if (inside == null || exit == null || net == null)
|
||||
{
|
||||
trip.HubWalk(i, net, out string why);
|
||||
Stop(i, $"the walk inside the Town Network isn't known ({(why.Length > 0 ? why : "no townnet.json")})");
|
||||
return r;
|
||||
}
|
||||
List<WorldPt> walk = TripPathBuilder.StopShort(inside, HubStopShort);
|
||||
for (int k = 1; k < walk.Count; k++) AddPoint(walk[k]);
|
||||
AddPortal(net.Exits[s.HubExit].Name, exit.Value);
|
||||
Land(s);
|
||||
continue;
|
||||
}
|
||||
WorldPt[]? pts = path.Walks[i];
|
||||
if (pts == null || pts.Length == 0)
|
||||
{
|
||||
if (trip.WalkFrom[i] == null) { Stop(i, "it starts where the plan has no map position (inside a dungeon)"); return r; }
|
||||
Stop(i, "its walk wasn't worked out");
|
||||
return r;
|
||||
}
|
||||
if (s.UsePortal)
|
||||
{
|
||||
List<WorldPt> walk = TripPathBuilder.StopShort(pts, PortalStopShort);
|
||||
for (int k = 1; k < walk.Count; k++) AddPoint(walk[k]);
|
||||
WorldPt at = trip.Point[i] is WorldPt p ? p with { H = pts[^1].H } : pts[^1];
|
||||
string name = trip.PortalName(i);
|
||||
if (name.Length == 0) { Stop(i, "the portal has no name to look for"); return r; }
|
||||
AddPortal(name, at);
|
||||
Land(s);
|
||||
continue;
|
||||
}
|
||||
for (int k = 1; k < pts.Length; k++) AddPoint(pts[k]);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// ── The file ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// A nav file name from what was typed: trimmed, without ".nav". "" with <paramref name="error"/>
|
||||
/// when it can't be one (empty, characters a file name can't have, a path).
|
||||
/// </summary>
|
||||
public static string FileName(string typed, out string error)
|
||||
{
|
||||
error = "";
|
||||
string n = (typed ?? "").Trim();
|
||||
if (n.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) n = n[..^4].TrimEnd();
|
||||
if (n.Length == 0) { error = "give the route a name"; return ""; }
|
||||
if (n.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || n.Contains("..") || n.Length > 100)
|
||||
{ error = $"'{typed}' can't be used as a file name"; return ""; }
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>A file name made from a place's name (characters a file can't have become spaces).</summary>
|
||||
public static string SafeName(string text)
|
||||
{
|
||||
var chars = (text ?? "").ToCharArray();
|
||||
char[] bad = Path.GetInvalidFileNameChars();
|
||||
for (int i = 0; i < chars.Length; i++) if (Array.IndexOf(bad, chars[i]) >= 0) chars[i] = ' ';
|
||||
string s = string.Join(" ", new string(chars).Split(' ', StringSplitOptions.RemoveEmptyEntries));
|
||||
return s.Length > 60 ? s[..60].TrimEnd() : s;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes <paramref name="route"/> to <folder>\<name>.nav. An existing file is only replaced
|
||||
/// with <paramref name="overwrite"/>; otherwise nothing is written and false comes back with
|
||||
/// <paramref name="exists"/> set. Written to a temporary file first, then moved into place.
|
||||
/// </summary>
|
||||
public static bool Save(string folder, string name, NavRouteParser route, bool overwrite, out string path, out bool exists, out string error)
|
||||
{
|
||||
error = "";
|
||||
path = Path.Combine(folder, name + ".nav");
|
||||
exists = File.Exists(path);
|
||||
if (exists && !overwrite) return false;
|
||||
string tmp = path + ".tmp";
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
File.WriteAllLines(tmp, route.ToLines());
|
||||
File.Move(tmp, path, overwrite);
|
||||
return true;
|
||||
}
|
||||
catch (IOException) when (!overwrite && File.Exists(path))
|
||||
{
|
||||
exists = true; // made by someone else in the meantime
|
||||
try { File.Delete(tmp); } catch { }
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
try { File.Delete(tmp); } catch { }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
295
Plugins/RynthCore.Plugin.RynthNav/PathMarkers.cs
Normal file
295
Plugins/RynthCore.Plugin.RynthNav/PathMarkers.cs
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
internal enum MarkKind : byte { Waypoint, Portal, Recall, Town, Goal }
|
||||
|
||||
/// <summary>One marker on the ground: a waypoint of a walk, or where a step happens.</summary>
|
||||
internal readonly record struct Mark(WorldPt P, MarkKind Kind, string Label, int Step, bool LineToNext);
|
||||
|
||||
/// <summary>
|
||||
/// A trip's markers, built on the tick from the trip and its path and then never changed: the
|
||||
/// Nav3D emit reads only this (never the plan, the route or the walker's state).
|
||||
/// </summary>
|
||||
internal sealed class MarkerSnapshot
|
||||
{
|
||||
public static readonly MarkerSnapshot Empty = new(0, false, Array.Empty<Mark>());
|
||||
|
||||
public readonly int TripId;
|
||||
/// <summary>Built with the trip's path (waypoints and lines), not just the steps' points.</summary>
|
||||
public readonly bool HasPath;
|
||||
public readonly Mark[] Marks;
|
||||
|
||||
public MarkerSnapshot(int tripId, bool hasPath, Mark[] marks) { TripId = tripId; HasPath = hasPath; Marks = marks; }
|
||||
|
||||
/// <summary>The first marker of step <paramref name="step"/>, or -1.</summary>
|
||||
public int FirstOfStep(int step)
|
||||
{
|
||||
for (int i = 0; i < Marks.Length; i++) if (Marks[i].Step == step) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>The last marker of step <paramref name="step"/>, or -1.</summary>
|
||||
public int LastOfStep(int step)
|
||||
{
|
||||
for (int i = Marks.Length - 1; i >= 0; i--) if (Marks[i].Step == step) return i;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where the markers go: the engine's Nav3D buffer in the game, a recorder in the tests.</summary>
|
||||
internal interface IMarkerSink : INav3DSink
|
||||
{
|
||||
void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb);
|
||||
}
|
||||
|
||||
/// <summary>What the emit needs to know about this tick (all plain values, taken on the tick).</summary>
|
||||
internal readonly record struct MarkerView(
|
||||
double Px, double Py, double Pz, // the character: world east, north, height
|
||||
int Next, // the marker the walk is heading for (-1: none, a plan only)
|
||||
bool Labels, bool Guide);
|
||||
|
||||
/// <summary>
|
||||
/// RynthNav's path markers: the planned trip drawn on the ground the way RynthAi draws its nav
|
||||
/// routes (rings at the waypoints, lines between them, on the engine's Nav3D buffer), with the
|
||||
/// place each step happens (a portal, a recall, the Town Network, the goal) in its own colour and,
|
||||
/// optionally, a label (Plugins/Shared/Nav3DText) and a guide line from your feet to the next
|
||||
/// waypoint. Host-free: the route tests build and emit these into a recorder.
|
||||
/// </summary>
|
||||
internal static class PathMarkers
|
||||
{
|
||||
public const double WaypointRange = 160.0; // waypoints this close (yards) are drawn
|
||||
public const double StepRange = 400.0; // a step's own marker, this close
|
||||
public const double LabelRange = 90.0;
|
||||
public const double MaxGuideUnits = 500.0;
|
||||
public const double NextReach = 4.0; // the next waypoint counts as reached this close
|
||||
public const int MaxWaypointRings = 40;
|
||||
public const int MaxStepRings = 8;
|
||||
public const int MaxLines = 90;
|
||||
public const int MaxLabelTriangles = 900; // the engine keeps 8192 a tick for every plugin
|
||||
public const int MaxLabelChars = 22;
|
||||
|
||||
public const uint WaypointColor = 0xFF40D973, LineColor = 0xFF2FB863, NextColor = 0xFFFF4444,
|
||||
PortalColor = 0xFFBF4DFF, RecallColor = 0xFFFFC040, TownColor = 0xFF2EC4C4, GoalColor = 0xFFFFD24D,
|
||||
GuideColor = 0xFFFFD21E;
|
||||
|
||||
private const float WaypointRadius = 0.9f, StepRadius = 1.8f, RingThick = 0.12f, LineThick = 0.08f, Lift = 0.1f;
|
||||
|
||||
// ── Build (tick) ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The markers for <paramref name="trip"/>: with its <paramref name="path"/> (same trip), every
|
||||
/// walk's waypoints joined by lines and each step's own marker; without it (still being worked
|
||||
/// out, or none to be had), only the steps' markers.
|
||||
/// </summary>
|
||||
public static MarkerSnapshot Build(PlannedTrip trip, TripPath? path, TownNet? net)
|
||||
{
|
||||
if (path != null && path.TripId != trip.Id) path = null;
|
||||
var marks = new List<Mark>();
|
||||
int n = trip.Count;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
RouteStep s = trip.Steps[i];
|
||||
bool last = i == n - 1;
|
||||
if (s.UseRecall)
|
||||
{
|
||||
if (trip.Point[i] is WorldPt at)
|
||||
marks.Add(new Mark(at, MarkKind.Recall, Fit("RECALL " + (trip.RecallOf(i)?.Name ?? s.Label)), i, false));
|
||||
continue;
|
||||
}
|
||||
if (s.IsHub)
|
||||
{
|
||||
WorldPt? exit = PlannedTrip.HubExitPoint(net, s);
|
||||
WorldPt[]? inside = path?.Hub[i];
|
||||
if (inside != null)
|
||||
foreach (WorldPt p in inside)
|
||||
{
|
||||
if (exit is WorldPt e && p.FlatDistance(e) < 2.0) continue;
|
||||
Add(marks, new Mark(p, MarkKind.Waypoint, "", i, true));
|
||||
}
|
||||
WorldPt? at = exit ?? (inside is { Length: > 0 } ? inside[^1] : null);
|
||||
string where = net != null && s.HubExit >= 0 && s.HubExit < net.Exits.Count ? net.Exits[s.HubExit].Where : s.Label;
|
||||
if (at is WorldPt a) marks.Add(new Mark(a, MarkKind.Town, Fit("PORTAL TO " + where), i, false));
|
||||
continue;
|
||||
}
|
||||
if (trip.Point[i] is not WorldPt to) continue;
|
||||
WorldPt[]? walk = path?.Walks[i];
|
||||
if (walk != null)
|
||||
for (int k = 0; k < walk.Length - 1; k++)
|
||||
Add(marks, new Mark(walk[k], MarkKind.Waypoint, "", i, true));
|
||||
if (walk is { Length: > 0 }) to = to with { H = walk[^1].H };
|
||||
Mark end;
|
||||
if (s.UsePortal)
|
||||
{
|
||||
bool intoHub = i + 1 < n && trip.Steps[i + 1].IsHub;
|
||||
string label = intoHub ? "TOWN NETWORK"
|
||||
: last && trip.EndsInEntrance ? "ENTER " + trip.EnterName
|
||||
: "PORTAL " + s.Label;
|
||||
end = new Mark(to, intoHub ? MarkKind.Town : MarkKind.Portal, Fit(label), i, false);
|
||||
}
|
||||
else if (last) end = new Mark(to, MarkKind.Goal, Fit(trip.Goal.Length > 0 ? trip.Goal : "ARRIVE"), i, false);
|
||||
else end = new Mark(to, MarkKind.Waypoint, "", i, walk != null);
|
||||
Add(marks, end);
|
||||
}
|
||||
return new MarkerSnapshot(trip.Id, path != null, marks.ToArray());
|
||||
}
|
||||
|
||||
// A leg starts where the last one ended: the same point once. A step's own marker takes the
|
||||
// place of a waypoint under it (the line before it then runs into the step's marker).
|
||||
private static void Add(List<Mark> marks, Mark m)
|
||||
{
|
||||
if (marks.Count > 0 && marks[^1].P.FlatDistance(m.P) < 1.0)
|
||||
{
|
||||
Mark prev = marks[^1];
|
||||
if (m.Kind == MarkKind.Waypoint)
|
||||
{
|
||||
if (m.LineToNext && !prev.LineToNext && prev.Kind == MarkKind.Waypoint) marks[^1] = prev with { LineToNext = true };
|
||||
return;
|
||||
}
|
||||
if (prev.Kind == MarkKind.Waypoint) marks.RemoveAt(marks.Count - 1);
|
||||
}
|
||||
marks.Add(m);
|
||||
}
|
||||
|
||||
private static string Fit(string s)
|
||||
{
|
||||
s = s.Trim().ToUpperInvariant();
|
||||
return s.Length > MaxLabelChars ? s[..(MaxLabelChars - 2)] + ".." : s;
|
||||
}
|
||||
|
||||
// ── The next waypoint (tick) ─────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The marker the walk on step <paramref name="step"/> heads for next, carried on from
|
||||
/// <paramref name="idx"/> (last tick's): it moves on when the character is within
|
||||
/// <see cref="NextReach"/> of it, or is already nearer the stretch after it than the one before
|
||||
/// it (a re-plan or a cut corner). Never moves back within a step. -1 when the step has no markers.
|
||||
/// </summary>
|
||||
public static int Advance(MarkerSnapshot s, int idx, int step, double px, double py)
|
||||
{
|
||||
Mark[] m = s.Marks;
|
||||
int first = s.FirstOfStep(step), lastOfStep = s.LastOfStep(step);
|
||||
if (first < 0) return -1;
|
||||
if (idx < first || idx > lastOfStep) idx = first;
|
||||
var me = new WorldPt(px, py, 0);
|
||||
while (idx < lastOfStep)
|
||||
{
|
||||
if (m[idx].P.FlatDistance(me) < NextReach) { idx++; continue; }
|
||||
WorldPt before = idx > first ? m[idx - 1].P : m[idx].P;
|
||||
double toBefore = idx > first ? PlannedTrip.SegmentDistance(me, before, m[idx].P) : double.MaxValue;
|
||||
double toAfter = PlannedTrip.SegmentDistance(me, m[idx].P, m[idx + 1].P, out double t);
|
||||
if (toAfter + 1.0 < toBefore && t > 0.05) { idx++; continue; }
|
||||
break;
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
|
||||
/// <summary>The marker nearest the character (a plan only: where the guide line points), or -1.</summary>
|
||||
public static int Nearest(MarkerSnapshot s, double px, double py)
|
||||
{
|
||||
int best = -1;
|
||||
double bestD = MaxGuideUnits;
|
||||
var me = new WorldPt(px, py, 0);
|
||||
for (int i = 0; i < s.Marks.Length; i++)
|
||||
{
|
||||
double d = s.Marks[i].P.FlatDistance(me);
|
||||
if (d < bestD) { bestD = d; best = i; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// ── Emit (tick, into the Nav3D buffer) ───────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Submits the markers near the character: rings (waypoints within <see cref="WaypointRange"/>,
|
||||
/// at most <see cref="MaxWaypointRings"/> nearest; steps' markers within <see cref="StepRange"/>),
|
||||
/// lines between neighbouring waypoints, the guide line first (so a full line buffer never drops
|
||||
/// it) and the labels last. Positions go in the Nav3D frame: the character's landblock, X = east
|
||||
/// metres, Y = height, Z = north metres. Returns the number of rings drawn.
|
||||
/// </summary>
|
||||
public static int Emit(MarkerSnapshot s, in MarkerView v, IMarkerSink sink)
|
||||
{
|
||||
Mark[] m = s.Marks;
|
||||
if (m.Length == 0) return 0;
|
||||
double baseX = Math.Floor(v.Px / 192.0) * 192.0, baseY = Math.Floor(v.Py / 192.0) * 192.0;
|
||||
float px = (float)(v.Px - baseX), py = (float)(v.Py - baseY), pz = (float)v.Pz;
|
||||
var me = new WorldPt(v.Px, v.Py, v.Pz);
|
||||
|
||||
// Which markers: steps' own within StepRange, waypoints within WaypointRange (the nearest).
|
||||
var dist = new double[m.Length];
|
||||
var drawn = new bool[m.Length];
|
||||
var waypoints = new List<int>();
|
||||
int steps = 0;
|
||||
for (int i = 0; i < m.Length; i++)
|
||||
{
|
||||
dist[i] = m[i].P.FlatDistance(me);
|
||||
if (m[i].Kind == MarkKind.Waypoint) { if (dist[i] <= WaypointRange) waypoints.Add(i); }
|
||||
else if (dist[i] <= StepRange && steps < MaxStepRings) { drawn[i] = true; steps++; }
|
||||
}
|
||||
if (waypoints.Count > MaxWaypointRings) waypoints.Sort((a, b) => dist[a].CompareTo(dist[b]));
|
||||
for (int k = 0; k < waypoints.Count && k < MaxWaypointRings; k++) drawn[waypoints[k]] = true;
|
||||
if (v.Next >= 0 && v.Next < m.Length && dist[v.Next] <= StepRange) drawn[v.Next] = true;
|
||||
|
||||
(float X, float Y, float Z) Local(WorldPt p) =>
|
||||
((float)(p.X - baseX), (double.IsNaN(p.H) ? pz : (float)p.H) + Lift, (float)(p.Y - baseY));
|
||||
|
||||
// Guide line: to the next waypoint (a walk), else the nearest marker (a plan).
|
||||
if (v.Guide)
|
||||
{
|
||||
int g = v.Next >= 0 && v.Next < m.Length ? v.Next : Nearest(s, v.Px, v.Py);
|
||||
if (g >= 0 && dist[g] <= MaxGuideUnits)
|
||||
{
|
||||
var (gx, gy, gz) = Local(m[g].P);
|
||||
sink.Line(px, pz + Lift + 0.05f, py, gx, gy, gz, LineThick, GuideColor);
|
||||
}
|
||||
}
|
||||
|
||||
int rings = 0;
|
||||
for (int i = 0; i < m.Length; i++)
|
||||
{
|
||||
if (!drawn[i]) continue;
|
||||
var (x, y, z) = Local(m[i].P);
|
||||
bool next = i == v.Next;
|
||||
bool step = m[i].Kind != MarkKind.Waypoint;
|
||||
uint color = next ? NextColor : ColorOf(m[i].Kind);
|
||||
sink.Ring(x, y, z, step ? StepRadius : next ? WaypointRadius * 1.2f : WaypointRadius, step || next ? RingThick * 1.4f : RingThick, color);
|
||||
rings++;
|
||||
}
|
||||
|
||||
int lines = 0;
|
||||
for (int i = 0; i + 1 < m.Length && lines < MaxLines; i++)
|
||||
{
|
||||
if (!m[i].LineToNext) continue;
|
||||
// A line when either end is drawn and the other isn't far off.
|
||||
if (!(drawn[i] || drawn[i + 1]) || Math.Min(dist[i], dist[i + 1]) > WaypointRange) continue;
|
||||
var (ax, ay, az) = Local(m[i].P);
|
||||
var (bx, by, bz) = Local(m[i + 1].P);
|
||||
sink.Line(ax, ay, az, bx, by, bz, LineThick, LineColor);
|
||||
lines++;
|
||||
}
|
||||
|
||||
if (v.Labels)
|
||||
{
|
||||
int tris = 0;
|
||||
for (int i = 0; i < m.Length; i++)
|
||||
{
|
||||
if (!drawn[i] || m[i].Label.Length == 0 || dist[i] > LabelRange) continue;
|
||||
var (x, y, z) = Local(m[i].P);
|
||||
if (!Nav3DText.Emit(x, y, z, m[i].Label, 0, ColorOf(m[i].Kind), px, py, sink, ref tris, MaxLabelTriangles)) break;
|
||||
}
|
||||
}
|
||||
return rings;
|
||||
}
|
||||
|
||||
public static uint ColorOf(MarkKind k) => k switch
|
||||
{
|
||||
MarkKind.Portal => PortalColor,
|
||||
MarkKind.Recall => RecallColor,
|
||||
MarkKind.Town => TownColor,
|
||||
MarkKind.Goal => GoalColor,
|
||||
_ => WaypointColor,
|
||||
};
|
||||
}
|
||||
|
|
@ -42,6 +42,13 @@
|
|||
<Compile Include="..\Shared\RynthNavPathApi.cs" Link="Shared\RynthNavPathApi.cs" />
|
||||
<!-- One logged, guarded way to use an object (who used what, and why). -->
|
||||
<Compile Include="..\Shared\UseAudit.cs" Link="Shared\UseAudit.cs" />
|
||||
<!-- Text in the world on the Nav3D buffer (the path markers' labels; RynthAi's waypoint labels use it too). -->
|
||||
<Compile Include="..\Shared\Nav3DText.cs" Link="Shared\Nav3DText.cs" />
|
||||
<!-- Install folders (RynthAi's NavProfiles, where "save as nav route" writes). Read only. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
<!-- RynthAi's own nav file reader/writer (uTank2 NAV 1.2), so a saved route is written exactly
|
||||
the way RynthAi writes its own. Self-contained (System.IO only). -->
|
||||
<Compile Include="..\RynthCore.Plugin.RynthAi\LegacyUi\NavRouteParser.cs" Link="Shared\NavRouteParser.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -48,18 +48,9 @@ public sealed partial class RynthNavPlugin
|
|||
_nextAvoidMs = now + AvoidRefreshMs;
|
||||
if (!_avoidPortals) { _avoid.Clear(); return; }
|
||||
|
||||
Atlas atlas = _atlas;
|
||||
if (!ReferenceEquals(atlas, _avoidAtlas))
|
||||
{
|
||||
var list = new List<PortalAvoid.Spot>();
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
if (l.OnMap && l.Type.Equals("Portal", StringComparison.Ordinal))
|
||||
list.Add(new PortalAvoid.Spot(NavCoords.WorldX(l.Ew), NavCoords.WorldY(l.Ns), PortalAvoid.MapRadius, l.Name));
|
||||
_atlasPortals = list;
|
||||
_avoidAtlas = atlas;
|
||||
}
|
||||
IReadOnlyList<PortalAvoid.Spot> atlasPortals = AtlasPortalSpots();
|
||||
var map = new List<PortalAvoid.Spot>();
|
||||
foreach (PortalAvoid.Spot sp in _atlasPortals)
|
||||
foreach (PortalAvoid.Spot sp in atlasPortals)
|
||||
if (Math.Abs(sp.X - _wx) < AvoidNearUnits && Math.Abs(sp.Y - _wy) < AvoidNearUnits) map.Add(sp);
|
||||
|
||||
var live = new List<PortalAvoid.Spot>();
|
||||
|
|
|
|||
220
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs
Normal file
220
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.Markers.cs
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// The planned trip on the ground: RynthNav's path markers (PathMarkers), drawn on the engine's
|
||||
// Nav3D buffer the way RynthAi draws its nav routes. When Route or Go plans a trip, a worker works
|
||||
// out the whole walk ahead of time (TilePathFinder: the route graph and the tiles, in its own
|
||||
// navmesh), and the markers show it: rings at the waypoints near you, lines between them, the
|
||||
// portal / recall / Town Network / goal markers in their own colours, and (switches) labels on
|
||||
// those and a guide line from your feet to the next waypoint. The same path is what "save as nav
|
||||
// route" writes (RynthNavPlugin.SaveRoute.cs).
|
||||
//
|
||||
// The markers go away when the trip ends (arrived, stopped), is cancelled (Stop, the d-pad), or you
|
||||
// land in a landblock that isn't on it (a teleport elsewhere). Switches in rynthnav.json
|
||||
// (markers, markerLabels, markerGuide); /rnav markers and the panel's Go tab change them.
|
||||
//
|
||||
// Threads: everything here runs on the tick, except the path worker, which reads only the frozen
|
||||
// trip (PlannedTrip), the immutable route graph and Atlas portal list, and the tile files. The
|
||||
// emit reads only the frozen MarkerSnapshot, never the trip, the route or the walker.
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
private volatile bool _markersOn = true, _markerLabels = true, _markerGuide;
|
||||
|
||||
// The last trip planned (Route or Go): kept for "save as nav route" after it ends.
|
||||
private volatile PlannedTrip? _trip;
|
||||
private int _tripSeq;
|
||||
private volatile bool _tripShown; // its markers are on the ground (not ended / cancelled / left)
|
||||
private TripPath? _tripPath; // its path, once worked out
|
||||
private Task<(TripPath Path, long Ms, int Tiles)>? _pathTask;
|
||||
private PlannedTrip? _pathTaskTrip;
|
||||
private string _nextEnterPortal = "", _enterPortal = "";
|
||||
|
||||
// Markers (tick thread).
|
||||
private MarkerSnapshot _markerSnap = MarkerSnapshot.Empty;
|
||||
private PlannedTrip? _snapTrip;
|
||||
private TripPath? _snapPath;
|
||||
private int _markNext = -1, _markStep = -2, _markTrip;
|
||||
private uint _markLb;
|
||||
private HostMarkerSink? _markerSink;
|
||||
private volatile string _markerStatus = "";
|
||||
|
||||
private void LoadMarkerSettings()
|
||||
{
|
||||
_markersOn = NavDataConfig.ReadSwitch("markers", true);
|
||||
_markerLabels = NavDataConfig.ReadSwitch("markerLabels", true);
|
||||
_markerGuide = NavDataConfig.ReadSwitch("markerGuide", false);
|
||||
}
|
||||
|
||||
// ── The trip ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A new plan (Route) or goto (Go): its trip, shown, its path worked out. Tick thread.</summary>
|
||||
private void SetTrip(List<RouteStep>? steps, string goal, double goalNs, double goalEw, List<RecallOption>? recalls,
|
||||
string enterName, bool live)
|
||||
{
|
||||
var tr = new List<TripRecall>();
|
||||
if (recalls != null) foreach (RecallOption o in recalls) tr.Add(new TripRecall(o.Name, o.SpellId, o.Command, o.CastSeconds));
|
||||
_trip = new PlannedTrip(++_tripSeq, steps ?? new List<RouteStep>(), goal, goalNs, goalEw,
|
||||
IsOnMap(_cellId), new WorldPt(_wx, _wy, _wz), _cellId, tr,
|
||||
enterName.Length > 0 ? _enterPortal : "", enterName, live);
|
||||
_tripPath = null;
|
||||
_tripShown = true;
|
||||
_markNext = -1; _markStep = -2;
|
||||
_markLb = CurrentLandblock;
|
||||
_saveConflict = "";
|
||||
_saveDefault = NavRouteExport.SafeName("To " + goal);
|
||||
if (_markersOn) StartPathBuild();
|
||||
_markerStatus = "working out the path…";
|
||||
}
|
||||
|
||||
/// <summary>Takes the markers off the ground (the trip stays for "save as nav route"). Tick thread.</summary>
|
||||
private void HideMarkers(string why)
|
||||
{
|
||||
if (!_tripShown) return;
|
||||
_tripShown = false;
|
||||
_markNext = -1;
|
||||
_markerStatus = why;
|
||||
Host.Log($"[RynthNav] path markers: off ({why})");
|
||||
}
|
||||
|
||||
private void StartPathBuild()
|
||||
{
|
||||
PlannedTrip? trip = _trip;
|
||||
if (trip == null || (_tripPath != null && _tripPath.TripId == trip.Id)) return;
|
||||
if (_pathTask != null && ReferenceEquals(_pathTaskTrip, trip)) return;
|
||||
NavGraph? g = UsableGraph();
|
||||
IReadOnlyList<PortalAvoid.Spot> portals = AtlasPortalSpots();
|
||||
TownNet? net = _townNet;
|
||||
string dir = NavDataDir;
|
||||
_pathTaskTrip = trip;
|
||||
_pathTask = Task.Run(() =>
|
||||
{
|
||||
long t0 = Environment.TickCount64;
|
||||
var finder = new TilePathFinder(dir, g, portals);
|
||||
TripPath p = TripPathBuilder.Build(trip,
|
||||
(WorldPt a, WorldPt b, bool intoPortal, out string note) => finder.Walk(a, b, intoPortal, out note), net);
|
||||
return (p, Environment.TickCount64 - t0, finder.TilesRead);
|
||||
});
|
||||
}
|
||||
|
||||
private void TakePathResult()
|
||||
{
|
||||
if (_pathTask is not { IsCompleted: true } task) return;
|
||||
PlannedTrip? forTrip = _pathTaskTrip;
|
||||
_pathTask = null; _pathTaskTrip = null;
|
||||
if (task.IsFaulted)
|
||||
{
|
||||
Host.Log($"[RynthNav] trip path failed: {task.Exception?.GetBaseException().Message}");
|
||||
_markerStatus = "the path couldn't be worked out (see the log)";
|
||||
OnPathReady(forTrip, null);
|
||||
return;
|
||||
}
|
||||
var (path, ms, tiles) = task.Result;
|
||||
if (_trip == null || path.TripId != _trip.Id) { if (_markersOn || _pendingSave != null) StartPathBuild(); return; } // planned for an older trip
|
||||
_tripPath = path;
|
||||
int points = 0;
|
||||
foreach (WorldPt[]? w in path.Walks) points += w?.Length ?? 0;
|
||||
foreach (WorldPt[]? w in path.Hub) points += w?.Length ?? 0;
|
||||
Host.Log($"[RynthNav] trip path to {_trip.Goal}: {points} waypoints over {_trip.Count} step(s), {tiles} tile(s) read, {ms} ms");
|
||||
foreach (string n in path.Notes) Host.Log($"[RynthNav] trip path: {n}");
|
||||
_markerStatus = path.Notes.Count == 0 ? $"{points} waypoints" : $"{points} waypoints; {path.Notes[0]}";
|
||||
OnPathReady(_trip, path);
|
||||
}
|
||||
|
||||
// ── Tick ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void TickMarkers()
|
||||
{
|
||||
TakePathResult();
|
||||
PlannedTrip? trip = _trip;
|
||||
if (trip == null) return;
|
||||
|
||||
// A landblock that isn't on the trip (a teleport somewhere else): the markers go.
|
||||
if (_hasPose && _tripShown)
|
||||
{
|
||||
uint lb = CurrentLandblock;
|
||||
if (lb != _markLb && lb != 0)
|
||||
{
|
||||
_markLb = lb;
|
||||
TownNet? net = _townNet;
|
||||
if (!trip.Covers(lb, _tripPath, net == null ? null : net.Contains))
|
||||
HideMarkers($"landblock 0x{lb:X4} isn't on the trip");
|
||||
}
|
||||
}
|
||||
if (!_markersOn || !_tripShown || !Host.HasNav3D || !_hasPose) return;
|
||||
|
||||
if (!ReferenceEquals(trip, _snapTrip) || !ReferenceEquals(_tripPath, _snapPath))
|
||||
{
|
||||
_snapTrip = trip; _snapPath = _tripPath;
|
||||
_markerSnap = PathMarkers.Build(trip, _tripPath, _townNet);
|
||||
_markNext = -1; _markStep = -2;
|
||||
}
|
||||
MarkerSnapshot snap = _markerSnap;
|
||||
if (snap.Marks.Length == 0) return;
|
||||
if ((_cellId >> 16) == 0 || (Host.HasIsPortaling && Host.IsPortaling())) return;
|
||||
|
||||
// The marker the walk heads for: on the running goto's current step.
|
||||
int next = -1;
|
||||
if (_gotoActive && trip.Live && !_settling)
|
||||
{
|
||||
int step = _route != null ? _routeIdx : 0;
|
||||
if (step != _markStep || snap.TripId != _markTrip) { _markStep = step; _markTrip = snap.TripId; _markNext = -1; }
|
||||
_markNext = next = PathMarkers.Advance(snap, _markNext, step, _wx, _wy);
|
||||
}
|
||||
var view = new MarkerView(_wx, _wy, _wz, next, _markerLabels && Host.HasNav3DTriangle, _markerGuide);
|
||||
try { PathMarkers.Emit(snap, view, _markerSink ??= new HostMarkerSink(Host)); }
|
||||
catch (Exception ex) { Host.Log($"[RynthNav] path markers: {ex.Message}"); }
|
||||
}
|
||||
|
||||
// ── /rnav markers ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>/rnav markers [on|off | labels on|off | guide on|off]</summary>
|
||||
private void CmdMarkers(string rest)
|
||||
{
|
||||
string[] a = rest.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (a.Length == 1 && a[0] is "on" or "off")
|
||||
{
|
||||
_markersOn = a[0] == "on";
|
||||
NavDataConfig.WriteSwitch("markers", _markersOn);
|
||||
if (_markersOn) StartPathBuild();
|
||||
}
|
||||
else if (a.Length == 2 && a[0] == "labels" && a[1] is "on" or "off")
|
||||
{ _markerLabels = a[1] == "on"; NavDataConfig.WriteSwitch("markerLabels", _markerLabels); }
|
||||
else if (a.Length == 2 && a[0] == "guide" && a[1] is "on" or "off")
|
||||
{ _markerGuide = a[1] == "on"; NavDataConfig.WriteSwitch("markerGuide", _markerGuide); }
|
||||
else if (a.Length > 0) { Say("/rnav markers on|off, markers labels on|off, markers guide on|off"); return; }
|
||||
Say($"path markers {(_markersOn ? "ON" : "OFF")}, labels {(_markerLabels ? "on" : "off")}, guide line {(_markerGuide ? "on" : "off")}"
|
||||
+ (_trip == null ? "" : _tripShown ? $" — showing the trip to {_trip.Goal}" : $" — the trip to {_trip.Goal} isn't shown ({_markerStatus})"));
|
||||
}
|
||||
|
||||
/// <summary>The Atlas's portals on the map (positions to 0.01 degree): the circles a walk keeps out of. Tick thread.</summary>
|
||||
private IReadOnlyList<PortalAvoid.Spot> AtlasPortalSpots()
|
||||
{
|
||||
Atlas atlas = _atlas;
|
||||
if (!ReferenceEquals(atlas, _avoidAtlas))
|
||||
{
|
||||
var list = new List<PortalAvoid.Spot>();
|
||||
foreach (AtlasLocation l in atlas.Locations)
|
||||
if (l.OnMap && l.Type.Equals("Portal", StringComparison.Ordinal))
|
||||
list.Add(new PortalAvoid.Spot(NavCoords.WorldX(l.Ew), NavCoords.WorldY(l.Ns), PortalAvoid.MapRadius, l.Name));
|
||||
_atlasPortals = list;
|
||||
_avoidAtlas = atlas;
|
||||
}
|
||||
return _atlasPortals;
|
||||
}
|
||||
|
||||
/// <summary>The engine's Nav3D buffer (the engine clears it each tick; every plugin adds to it).</summary>
|
||||
private sealed class HostMarkerSink : IMarkerSink
|
||||
{
|
||||
private readonly RynthCore.PluginSdk.RynthCoreHost _host;
|
||||
public HostMarkerSink(RynthCore.PluginSdk.RynthCoreHost host) => _host = host;
|
||||
public void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb) => _host.Nav3DAddRing(x, y, z, radius, thickness, colorArgb);
|
||||
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
|
||||
=> _host.Nav3DAddLine(x1, y1, z1, x2, y2, z2, thickness, colorArgb);
|
||||
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb)
|
||||
=> _host.Nav3DAddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, colorArgb);
|
||||
}
|
||||
}
|
||||
|
|
@ -152,6 +152,14 @@ public sealed partial class RynthNavPlugin
|
|||
.Append("\",\"tileHere\":").Append(_tileHere).Append(",\"indoors\":").Append(_hasPose && (cell & 0xFFFF) >= 0x100 ? 1 : 0)
|
||||
.Append(",\"onDisk\":").Append(_tilesOnDisk)
|
||||
.Append(",\"townNet\":").Append(_townNet != null ? 1 : 0).Append(",\"townNetStatus\":\"").Append(Esc(_townNetStatus)).Append("\"}");
|
||||
// Path markers (RynthNavPlugin.Markers.cs) and "save as nav route" (RynthNavPlugin.SaveRoute.cs), 0.6.6+.
|
||||
PlannedTrip? trip = _trip;
|
||||
sb.Append(",\"markers\":{\"on\":").Append(_markersOn ? 1 : 0).Append(",\"labels\":").Append(_markerLabels ? 1 : 0)
|
||||
.Append(",\"guide\":").Append(_markerGuide ? 1 : 0).Append(",\"shown\":").Append(trip != null && _tripShown ? 1 : 0)
|
||||
.Append(",\"status\":\"").Append(Esc(_markerStatus)).Append("\"}");
|
||||
sb.Append(",\"save\":{\"can\":").Append(trip != null ? 1 : 0).Append(",\"for\":\"").Append(Esc(trip?.Goal ?? ""))
|
||||
.Append("\",\"name\":\"").Append(Esc(_saveDefault)).Append("\",\"conflict\":\"").Append(Esc(_saveConflict))
|
||||
.Append("\",\"busy\":").Append(_saveBusy ? 1 : 0).Append(",\"last\":\"").Append(Esc(_saveLast)).Append("\"}");
|
||||
}
|
||||
|
||||
// ── The character's own recall spots, for the Recalls section (travel JSON) ──
|
||||
|
|
|
|||
100
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.SaveRoute.cs
Normal file
100
Plugins/RynthCore.Plugin.RynthNav/RynthNavPlugin.SaveRoute.cs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using RynthCore.Install;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
// "Save as nav route": the last trip RynthNav planned (Route or Go) written as a RynthAi nav route
|
||||
// (NavRouteExport) into RynthAi's NavProfiles folder, where RynthAi's route picker lists it
|
||||
// (RynthAi re-reads the folder when it changes) and /ra nav load <name> loads it.
|
||||
// /rnav saveroute [name] [overwrite] (the panel: the name box and Save on the Go tab)
|
||||
// No name: "To <the place>". An existing file is never replaced without "overwrite" (the panel
|
||||
// then offers Replace). The path is the one the markers show; if it isn't worked out yet, it is
|
||||
// first, and the save follows when it's done. Tick thread, except the file write (a worker).
|
||||
public sealed partial class RynthNavPlugin
|
||||
{
|
||||
/// <summary>RynthAi's route folder (what its Nav picker lists): <RynthSuite>\RynthAi\NavProfiles.</summary>
|
||||
private static string NavProfilesDir => Path.Combine(RynthInstallPaths.RynthAiDir, "NavProfiles");
|
||||
|
||||
private (int TripId, string Name, bool Overwrite)? _pendingSave;
|
||||
// For the panel (any thread reads them).
|
||||
private volatile string _saveDefault = "", _saveConflict = "", _saveLast = "";
|
||||
private volatile bool _saveBusy;
|
||||
|
||||
/// <summary>/rnav saveroute [name] [overwrite]</summary>
|
||||
private void CmdSaveRoute(string rest)
|
||||
{
|
||||
PlannedTrip? trip = _trip;
|
||||
if (trip == null) { Note("saveroute: plan a trip first (Route or Go), then save it"); return; }
|
||||
string text = rest.Trim();
|
||||
bool overwrite = false;
|
||||
if (text.Equals("overwrite", StringComparison.OrdinalIgnoreCase)) { overwrite = true; text = ""; }
|
||||
else if (text.EndsWith(" overwrite", StringComparison.OrdinalIgnoreCase)) { overwrite = true; text = text[..^10].TrimEnd(); }
|
||||
if (text.Length == 0) text = _saveDefault.Length > 0 ? _saveDefault : NavRouteExport.SafeName("To " + trip.Goal);
|
||||
string name = NavRouteExport.FileName(text, out string error);
|
||||
if (name.Length == 0) { Note("saveroute: " + error); return; }
|
||||
|
||||
if (!overwrite && File.Exists(Path.Combine(NavProfilesDir, name + ".nav")))
|
||||
{
|
||||
_saveConflict = name;
|
||||
Note($"saveroute: {name}.nav is already in RynthAi's NavProfiles; /rnav saveroute {name} overwrite replaces it");
|
||||
return;
|
||||
}
|
||||
_saveConflict = "";
|
||||
if (_tripPath != null && _tripPath.TripId == trip.Id) { WriteRoute(trip, _tripPath, name, overwrite); return; }
|
||||
_pendingSave = (trip.Id, name, overwrite);
|
||||
StartPathBuild();
|
||||
_saveBusy = true;
|
||||
Note($"saveroute: working out the path to {trip.Goal} first…");
|
||||
}
|
||||
|
||||
/// <summary>The trip's path is in (or failed: null): a save waiting for it goes ahead. Tick thread.</summary>
|
||||
private void OnPathReady(PlannedTrip? trip, TripPath? path)
|
||||
{
|
||||
if (_pendingSave is not { } ps || trip == null || ps.TripId != trip.Id) return;
|
||||
_pendingSave = null;
|
||||
_saveBusy = false;
|
||||
if (path == null) { Note("saveroute: the path couldn't be worked out, so nothing was saved (see the log)"); return; }
|
||||
WriteRoute(trip, path, ps.Name, ps.Overwrite);
|
||||
}
|
||||
|
||||
private void WriteRoute(PlannedTrip trip, TripPath path, string name, bool overwrite)
|
||||
{
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, path, _townNet);
|
||||
if (r.Route.Points.Count == 0)
|
||||
{
|
||||
Note($"saveroute: nothing to save: {(r.StopReason.Length > 0 ? r.StopReason : "the trip has no steps")}");
|
||||
return;
|
||||
}
|
||||
string folder = NavProfilesDir;
|
||||
string goal = trip.Goal;
|
||||
int notes = path.Notes.Count;
|
||||
string firstNote = notes > 0 ? path.Notes[0] : "";
|
||||
_saveBusy = true;
|
||||
Task.Run(() =>
|
||||
{
|
||||
string line;
|
||||
bool ok = NavRouteExport.Save(folder, name, r.Route, overwrite, out string file, out bool exists, out string error);
|
||||
if (ok)
|
||||
{
|
||||
line = $"saveroute: saved {name}.nav to {folder}: {r.Route.Points.Count} steps ({r.Waypoints} waypoints"
|
||||
+ (r.Portals > 0 ? $", {r.Portals} portal(s)" : "") + (r.Recalls + r.Chats > 0 ? $", {r.Recalls + r.Chats} recall(s)" : "")
|
||||
+ $"). RynthAi: pick it in Nav, or /ra nav load {name}.";
|
||||
if (r.StoppedAt >= 0) line += $" It stops short of {goal}: {r.StopReason}.";
|
||||
if (notes > 0) line += $" Check it: {firstNote}{(notes > 1 ? $" (+{notes - 1} more in the log)" : "")}.";
|
||||
_saveConflict = "";
|
||||
Host.Log($"[RynthNav] {line} ({file})");
|
||||
}
|
||||
else if (exists)
|
||||
{
|
||||
_saveConflict = name;
|
||||
line = $"saveroute: {name}.nav is already there; /rnav saveroute {name} overwrite replaces it";
|
||||
}
|
||||
else line = $"saveroute: couldn't write {name}.nav: {error}";
|
||||
_saveLast = line;
|
||||
_saveBusy = false;
|
||||
Say(line);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -821,7 +821,9 @@ public sealed partial class RynthNavPlugin
|
|||
"/rnav route <place|coords> — plan a route (portals and recalls), no walking\n" +
|
||||
"/rnav atlas <search> — find places | fav [place] — favorite | recalls [on|off] | tie 1|2\n" +
|
||||
"/rnav goto <coords> | preview <coords> | portals on|off | stop | here | load | test | navdata\n" +
|
||||
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>";
|
||||
"/rnav avoid — show; avoid portals on|off|<m> | walls on|off|<m> | corners <m>\n" +
|
||||
"/rnav markers on|off | markers labels on|off | markers guide on|off — the trip on the ground\n" +
|
||||
"/rnav saveroute [name] [overwrite] — save the last trip as a RynthAi nav route (NavProfiles)";
|
||||
|
||||
/// <summary>One /rnav command. Tick thread.</summary>
|
||||
private void RunCommand(string raw, bool fromPanel)
|
||||
|
|
@ -863,6 +865,8 @@ public sealed partial class RynthNavPlugin
|
|||
break;
|
||||
case "recalls": CmdRecalls(rest); break;
|
||||
case "tie": CmdTie(rest); break;
|
||||
case "markers": CmdMarkers(rest); break;
|
||||
case "saveroute": CmdSaveRoute(rest); break;
|
||||
case "arrive":
|
||||
if (double.TryParse(rest, NumberStyles.Float, CultureInfo.InvariantCulture, out double yd) && yd >= 2 && yd <= 200)
|
||||
{ _arrow.ArriveUnits = yd; Say($"the arrow counts you as arrived within {yd:F0} yd"); }
|
||||
|
|
@ -937,6 +941,7 @@ public sealed partial class RynthNavPlugin
|
|||
AtlasLocation? portal = Entrance.PortalFor(_atlas, place, hasPos, pns, pew, out string why);
|
||||
if (portal == null) { Note("goto: " + why); return; }
|
||||
ns = portal.Ns; ew = portal.Ew; enter = place.Name; enterType = place.Type;
|
||||
_nextEnterPortal = portal.Name; // the portal object a saved nav route uses (RynthNavPlugin.SaveRoute.cs)
|
||||
}
|
||||
StartGoto(name, type, ns, ew, enter, enterType); // StartWalk says "walking to ..." (or why it can't)
|
||||
}
|
||||
|
|
@ -1034,7 +1039,7 @@ public sealed partial class RynthNavPlugin
|
|||
/// <summary>Plans a route (portals and, unless off, recalls) and shows it in the panel. Tick thread.</summary>
|
||||
private List<RouteStep>? PlanAndShow(string name, double ns, double ew, out int used, out double est, out string refusal)
|
||||
{
|
||||
TravelPlan.Result plan = PlanRoute(name, ns, ew, out _);
|
||||
TravelPlan.Result plan = PlanRoute(name, ns, ew, out List<RecallOption> recalls);
|
||||
List<RouteStep>? steps = plan.Steps;
|
||||
used = plan.Teleports; est = plan.Est; refusal = plan.Refusal;
|
||||
_shownRoute = steps ?? new List<RouteStep> { new(ns, ew, false, false, "walk") };
|
||||
|
|
@ -1042,6 +1047,7 @@ public sealed partial class RynthNavPlugin
|
|||
_shownRouteEst = est;
|
||||
_shownRouteLive = false;
|
||||
_routeVersion++;
|
||||
if (refusal.Length == 0) SetTrip(steps, name, ns, ew, recalls, "", live: false);
|
||||
return steps;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ namespace RynthCore.Plugin.RynthNav;
|
|||
public sealed partial class RynthNavPlugin : RynthPluginBase
|
||||
{
|
||||
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthNav");
|
||||
internal const string PluginVersion = "0.6.5";
|
||||
internal const string PluginVersion = "0.6.6";
|
||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(PluginVersion);
|
||||
|
||||
// Where the tiles, portals.tsv, locations.json and the player's atlas.txt/recalls.txt live.
|
||||
|
|
@ -140,6 +140,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
_portalsEnabled = NavDataConfig.ReadSwitch("portals", false);
|
||||
_recallsEnabled = NavDataConfig.ReadSwitch("recalls", true);
|
||||
LoadAvoidSettings();
|
||||
LoadMarkerSettings();
|
||||
Host.Log($"[RynthNav] Initialized v{PluginVersion} (tiled streaming + long-range goto + portal/recall routing + arrow + atlas). Panel: RynthNav. Tiles: {NavDataDir} ({NavConfig.Source})");
|
||||
InitTravel();
|
||||
LoadGraph();
|
||||
|
|
@ -180,6 +181,8 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
_tileRegions.Clear(); _tilePrints.Clear(); ResetCoarse();
|
||||
_chatOut.Clear();
|
||||
_goNote = "";
|
||||
HideMarkers("logged out");
|
||||
_trip = null; _tripPath = null;
|
||||
OnLogoutTravel();
|
||||
}
|
||||
|
||||
|
|
@ -199,6 +202,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
TickTravel();
|
||||
ProcessRequests();
|
||||
ApplyMovement();
|
||||
TickMarkers();
|
||||
UpdateGoLine();
|
||||
FlushChat();
|
||||
}
|
||||
|
|
@ -342,6 +346,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
if (_gotoActive) _goNote = "stopped"; // the panel's status line (the d-pad and Stop say nothing in chat)
|
||||
_gotoActive = false; _route = null; _portalWait = false; if (_recallWait) EndRecall();
|
||||
ResetHub();
|
||||
HideMarkers("cancelled");
|
||||
}
|
||||
if (load && _hasPose) RefreshTiles(CurrentLandblock);
|
||||
if (test) TestImpl();
|
||||
|
|
@ -427,9 +432,9 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
{
|
||||
if (!_hasPose) { lock (_gate) _status = "no pose"; Note("goto: no player position yet"); return; }
|
||||
// A new goto (not the re-plan after "no route over land") may re-plan once again.
|
||||
if (!landReplan) _landReplanned = false;
|
||||
if (!landReplan) { _landReplanned = false; _enterPortal = enter.Length > 0 ? _nextEnterPortal : ""; _nextEnterPortal = ""; }
|
||||
// Whatever was running stops first: a refused goto must not leave the old one half-changed.
|
||||
if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); Host.SetAutoRun(false); Host.StopCompletely(); }
|
||||
if (_gotoActive) { _gotoActive = false; _route = null; _portalWait = false; ResetHub(); Host.SetAutoRun(false); Host.StopCompletely(); HideMarkers("a new goto"); }
|
||||
double twx = NavCoords.WorldX(tew), twy = NavCoords.WorldY(tns);
|
||||
int gLbX = (int)Math.Floor(twx / 192.0), gLbY = (int)Math.Floor(twy / 192.0);
|
||||
if (double.IsNaN(twx) || double.IsNaN(twy) || gLbX < 0 || gLbX > 255 || gLbY < 0 || gLbY > 255)
|
||||
|
|
@ -503,6 +508,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
if (_route == null && !File.Exists(Path.Combine(NavDataDir, $"nav_{goalLb:X4}.tile")))
|
||||
Say($"goto: the target's landblock 0x{goalLb:X4} has no tile; walking as far as the navmesh goes");
|
||||
|
||||
SetTrip(_route, name, tns, tew, recalls, enter, live: true);
|
||||
_gotoActive = true;
|
||||
_gotoName = name; _gotoType = type;
|
||||
_walkHaveLast = false;
|
||||
|
|
@ -790,6 +796,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
|
|||
Say(status == "arrived" && _gotoName.Length > 0 ? $"goto: arrived at {_gotoName}" : $"goto: {status}");
|
||||
_goNote = status == "arrived" && _gotoName.Length > 0 ? $"arrived at {_gotoName}" : status;
|
||||
_enterName = ""; _enterType = "";
|
||||
HideMarkers(status == "arrived" ? "arrived" : "the goto ended");
|
||||
}
|
||||
|
||||
// At a portal entrance, waiting for the teleport. A portal ALWAYS changes the
|
||||
|
|
|
|||
241
Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs
Normal file
241
Plugins/RynthCore.Plugin.RynthNav/TilePathFinder.cs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using DotRecast.Core.Numerics;
|
||||
using DotRecast.Detour;
|
||||
using DotRecast.Detour.Io;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
|
||||
namespace RynthNav.Routing;
|
||||
|
||||
/// <summary>
|
||||
/// Whole walking legs on the navmesh, worked out ahead of time for a planned trip (the path
|
||||
/// markers and "save as nav route"), the way the walker would go: the route graph's border
|
||||
/// crossings from the start's region to the goal's (NavGraph A*), then the detailed Detour path
|
||||
/// between each pair of crossings, kept out of the Atlas's portals (AvoidFilter, PortalAvoid.Bend)
|
||||
/// except the leg's own. Its own navmesh, filled from the tile files a few tiles at a time, so it
|
||||
/// runs on a worker and never touches the walker's (tick-thread) navmesh. One instance per worker.
|
||||
/// Without a route graph only short legs (a few landblocks) are planned; longer ones get none.
|
||||
/// </summary>
|
||||
internal sealed class TilePathFinder
|
||||
{
|
||||
private const int MaxTiles = 64;
|
||||
private const int MaxDirectTiles = 16; // without a graph: a leg spanning at most this many tiles
|
||||
private const float ProbeReach = 40f;
|
||||
private const double OwnPortalUnits = 15.0; // the leg's own portal (its goal) isn't avoided
|
||||
private const double AvoidNearUnits = 300.0;
|
||||
|
||||
private readonly string _dir;
|
||||
private readonly NavGraph? _graph;
|
||||
private readonly IReadOnlyList<PortalAvoid.Spot> _portals;
|
||||
private readonly DtNavMesh _nav;
|
||||
private DtNavMeshQuery _query;
|
||||
private readonly HashSet<uint> _loaded = new(), _bad = new();
|
||||
private readonly PortalAvoid _avoid = new();
|
||||
private readonly AvoidFilter _filter;
|
||||
private readonly DtQueryDefaultFilter _plain = new();
|
||||
|
||||
/// <summary>Tile files read so far (for the log).</summary>
|
||||
public int TilesRead { get; private set; }
|
||||
|
||||
public TilePathFinder(string navDataDir, NavGraph? graph, IReadOnlyList<PortalAvoid.Spot>? portals)
|
||||
{
|
||||
_dir = navDataDir;
|
||||
_graph = graph;
|
||||
_portals = portals ?? Array.Empty<PortalAvoid.Spot>();
|
||||
_nav = new DtNavMesh();
|
||||
var p = new DtNavMeshParams { orig = new RcVec3f(0, 0, 0), tileWidth = 192f, tileHeight = 192f, maxTiles = MaxTiles, maxPolys = 1 << 16 };
|
||||
_nav.Init(p, 6);
|
||||
_query = new DtNavMeshQuery(_nav);
|
||||
_filter = new AvoidFilter(_avoid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The walk from <paramref name="from"/> to <paramref name="to"/>: corners, both ends included.
|
||||
/// <paramref name="ownPortal"/>: the walk ends by stepping into a portal there (not avoided).
|
||||
/// Null when the navmesh can't give one (no tiles, no way over land); <paramref name="note"/> says why.
|
||||
/// </summary>
|
||||
public List<WorldPt>? Walk(WorldPt from, WorldPt to, bool ownPortal, out string note)
|
||||
{
|
||||
note = "";
|
||||
var anchors = new List<WorldPt> { from };
|
||||
if (_graph != null)
|
||||
{
|
||||
NavCoarse.Probe? s = GroundProbe(from), g = GroundProbe(to);
|
||||
if (s == null || g == null) { note = $"no navmesh at its {(s == null ? "start" : "end")}"; return null; }
|
||||
List<int>? route = _graph.FindRoute(s.Region, s.Pt.X, s.Pt.Z, g.Region, g.Pt.X, g.Pt.Z, out _, out _);
|
||||
if (route == null) { note = "no way over land on the navmesh"; return null; }
|
||||
// Plan from and to the ground found there (the trip's own ends are added back by the caller).
|
||||
anchors[0] = new WorldPt(s.Pt.X, s.Pt.Z, s.Pt.Y);
|
||||
from = anchors[0];
|
||||
to = new WorldPt(g.Pt.X, g.Pt.Z, g.Pt.Y);
|
||||
foreach (int p in route)
|
||||
{
|
||||
var c = _graph.Portal(p);
|
||||
anchors.Add(new WorldPt(c.Ew, c.Ns, c.Up));
|
||||
}
|
||||
}
|
||||
else if (TileSpan(from, to) > MaxDirectTiles)
|
||||
{
|
||||
note = "too far to plan without the route graph (navgraph.bin)";
|
||||
return null;
|
||||
}
|
||||
anchors.Add(to);
|
||||
|
||||
var path = new List<WorldPt> { from };
|
||||
int gaps = 0;
|
||||
for (int k = 0; k + 1 < anchors.Count; k++)
|
||||
{
|
||||
bool last = k + 2 == anchors.Count;
|
||||
List<WorldPt>? piece = Piece(anchors[k], anchors[k + 1], last && ownPortal ? anchors[k + 1] : null);
|
||||
if (piece == null) { gaps++; piece = new List<WorldPt> { anchors[k], anchors[k + 1] }; }
|
||||
for (int i = 1; i < piece.Count; i++) path.Add(piece[i]);
|
||||
}
|
||||
if (gaps > 0) note = $"{gaps} gap(s) in the navmesh, straight lines there";
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Walkable ground at <paramref name="p"/> for the route search. A point with no height (a
|
||||
/// landing, a portal, a town's centre) can find a roof or a ledge first: a region of a tiny
|
||||
/// landmass that leads nowhere (the real map: Lytelthorpe's centre is under a roof). Then the
|
||||
/// ground a few yards round it (rings out to 36 yd) that's part of a real landmass is taken.
|
||||
/// </summary>
|
||||
private NavCoarse.Probe? GroundProbe(WorldPt p)
|
||||
{
|
||||
NavGraph g = _graph!;
|
||||
NavCoarse.Probe? first = NavCoarse.ProbeFile(g, _dir, p.X, p.H, p.Y, ProbeReach);
|
||||
if (first != null && !Tiny(first.Region)) return first;
|
||||
for (double r = 6; r <= 36; r += 6)
|
||||
for (int k = 0; k < 8; k++)
|
||||
{
|
||||
double a = k * Math.PI / 4;
|
||||
NavCoarse.Probe? q = NavCoarse.ProbeFile(g, _dir, p.X + Math.Cos(a) * r, p.H, p.Y + Math.Sin(a) * r, 4f);
|
||||
if (q != null && !Tiny(q.Region)) return q;
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
/// <summary>A region of a landmass this small (a roof, a ledge); false when the graph has no landmasses worked out.</summary>
|
||||
private bool Tiny(int region)
|
||||
{
|
||||
int c = _graph!.Component(region);
|
||||
return c >= 0 && _graph.ComponentSize(c) < 8;
|
||||
}
|
||||
|
||||
private static int TileSpan(WorldPt a, WorldPt b)
|
||||
{
|
||||
int ax = (int)Math.Floor(a.X / 192.0), ay = (int)Math.Floor(a.Y / 192.0), bx = (int)Math.Floor(b.X / 192.0), by = (int)Math.Floor(b.Y / 192.0);
|
||||
return (Math.Abs(ax - bx) + 1) * (Math.Abs(ay - by) + 1);
|
||||
}
|
||||
|
||||
/// <summary>The Detour path a→b (both ends' tiles and those between loaded); null when there's none.</summary>
|
||||
private List<WorldPt>? Piece(WorldPt a, WorldPt b, WorldPt? own)
|
||||
{
|
||||
if (!LoadBox(a, b)) return null;
|
||||
var half = new RcVec3f(8, 600, 8);
|
||||
var pa = new RcVec3f((float)a.X, double.IsNaN(a.H) ? 0f : (float)a.H, (float)a.Y);
|
||||
var pb = new RcVec3f((float)b.X, double.IsNaN(b.H) ? 0f : (float)b.H, (float)b.Y);
|
||||
_query.FindNearestPoly(pa, half, _plain, out long sRef, out RcVec3f sPt, out _);
|
||||
_query.FindNearestPoly(pb, half, _plain, out long gRef, out RcVec3f gPt, out _);
|
||||
if (sRef == 0 || gRef == 0) return null;
|
||||
|
||||
// Portals near this piece, except the leg's own.
|
||||
var near = new List<PortalAvoid.Spot>();
|
||||
double minX = Math.Min(a.X, b.X) - AvoidNearUnits, maxX = Math.Max(a.X, b.X) + AvoidNearUnits;
|
||||
double minY = Math.Min(a.Y, b.Y) - AvoidNearUnits, maxY = Math.Max(a.Y, b.Y) + AvoidNearUnits;
|
||||
foreach (PortalAvoid.Spot sp in _portals)
|
||||
if (sp.X >= minX && sp.X <= maxX && sp.Y >= minY && sp.Y <= maxY) near.Add(sp);
|
||||
if (own is WorldPt ownAt) _avoid.Set(Array.Empty<PortalAvoid.Spot>(), near, ownAt.X, ownAt.Y, OwnPortalUnits);
|
||||
else _avoid.Set(Array.Empty<PortalAvoid.Spot>(), near);
|
||||
_filter.AllowA = sRef; _filter.AllowB = gRef;
|
||||
|
||||
Span<long> polys = new long[1024];
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, _filter, polys, out int pc, 1024);
|
||||
if ((pc == 0 || polys[pc - 1] != gRef) && _avoid.Count > 0)
|
||||
_query.FindPath(sRef, gRef, sPt, gPt, _plain, polys, out pc, 1024);
|
||||
if (pc == 0 || polys[pc - 1] != gRef) return null;
|
||||
Span<DtStraightPath> sp2 = new DtStraightPath[256];
|
||||
_query.FindStraightPath(sPt, gPt, polys[..pc], pc, sp2, out int spc, 256, 0);
|
||||
if (spc < 2) return null;
|
||||
|
||||
var corners = new List<(double X, double Y)>(spc);
|
||||
List<double>? heights = new List<double>(spc);
|
||||
for (int i = 0; i < spc; i++) { corners.Add((sp2[i].pos.X, sp2[i].pos.Z)); heights.Add(sp2[i].pos.Y); }
|
||||
if (_avoid.Count > 0)
|
||||
{
|
||||
var q = _query;
|
||||
bool OnMesh(double x, double y)
|
||||
{
|
||||
q.FindNearestPoly(new RcVec3f((float)x, pa.Y, (float)y), new RcVec3f(0.5f, 600, 0.5f), _plain, out long r, out RcVec3f np, out _);
|
||||
return r != 0 && Math.Abs(np.X - x) < 0.05 && Math.Abs(np.Z - y) < 0.05;
|
||||
}
|
||||
bool LegOnMesh(double ax, double ay, double bx, double by)
|
||||
{
|
||||
double len = Math.Sqrt((bx - ax) * (bx - ax) + (by - ay) * (by - ay));
|
||||
int n = Math.Max(1, (int)Math.Ceiling(len));
|
||||
for (int k = 1; k < n; k++)
|
||||
if (!OnMesh(ax + (bx - ax) * k / n, ay + (by - ay) * k / n)) return false;
|
||||
return true;
|
||||
}
|
||||
int before = corners.Count;
|
||||
corners = _avoid.Bend(corners, OnMesh, 12, LegOnMesh);
|
||||
if (corners.Count != before) heights = null; // bend corners: heights filled from the neighbours
|
||||
}
|
||||
var o = new List<WorldPt>(corners.Count) { a with { H = heights != null ? heights[0] : (double.IsNaN(a.H) ? sPt.Y : a.H) } };
|
||||
for (int i = 1; i < corners.Count; i++)
|
||||
o.Add(new WorldPt(corners[i].X, corners[i].Y, heights != null ? heights[i] : double.NaN));
|
||||
if (heights == null) o[^1] = o[^1] with { H = gPt.Y };
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Loads the tiles of the box a..b (evicting others when full); false when it's too big or none loads.</summary>
|
||||
private bool LoadBox(WorldPt a, WorldPt b)
|
||||
{
|
||||
int x0 = (int)Math.Floor(Math.Min(a.X, b.X) / 192.0), x1 = (int)Math.Floor(Math.Max(a.X, b.X) / 192.0);
|
||||
int y0 = (int)Math.Floor(Math.Min(a.Y, b.Y) / 192.0), y1 = (int)Math.Floor(Math.Max(a.Y, b.Y) / 192.0);
|
||||
// A crossing on a tile edge belongs to both tiles: take one more on each side then.
|
||||
if (a.X - x0 * 192.0 < 1 || b.X - x0 * 192.0 < 1) x0--;
|
||||
if ((x1 + 1) * 192.0 - Math.Max(a.X, b.X) < 1) x1++;
|
||||
if (a.Y - y0 * 192.0 < 1 || b.Y - y0 * 192.0 < 1) y0--;
|
||||
if ((y1 + 1) * 192.0 - Math.Max(a.Y, b.Y) < 1) y1++;
|
||||
x0 = Math.Max(0, x0); y0 = Math.Max(0, y0); x1 = Math.Min(255, x1); y1 = Math.Min(255, y1);
|
||||
int want = (x1 - x0 + 1) * (y1 - y0 + 1);
|
||||
if (want > MaxTiles / 2) return false;
|
||||
var needed = new HashSet<uint>();
|
||||
for (int x = x0; x <= x1; x++)
|
||||
for (int y = y0; y <= y1; y++) needed.Add((uint)((x << 8) | y));
|
||||
bool changed = false;
|
||||
if (_loaded.Count + want > MaxTiles - 1)
|
||||
{
|
||||
foreach (uint lb in new List<uint>(_loaded))
|
||||
{
|
||||
if (needed.Contains(lb)) continue;
|
||||
long r = _nav.GetTileRefAt((int)(lb >> 8), (int)(lb & 0xFF), 0);
|
||||
if (r != 0) _nav.RemoveTile(r);
|
||||
_loaded.Remove(lb);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
bool any = false;
|
||||
foreach (uint lb in needed)
|
||||
{
|
||||
if (_loaded.Contains(lb)) { any = true; continue; }
|
||||
if (_bad.Contains(lb)) continue;
|
||||
string path = Path.Combine(_dir, $"nav_{lb:X4}.tile");
|
||||
if (!File.Exists(path)) { _bad.Add(lb); continue; }
|
||||
try
|
||||
{
|
||||
DtMeshData md;
|
||||
using (var fr = File.OpenRead(path)) using (var br = new BinaryReader(fr)) md = new DtMeshDataReader().Read(br, 6);
|
||||
TilesRead++;
|
||||
if (_nav.AddTile(md, 0, 0, out _).Failed()) { _bad.Add(lb); continue; }
|
||||
_loaded.Add(lb);
|
||||
changed = any = true;
|
||||
}
|
||||
catch { _bad.Add(lb); }
|
||||
}
|
||||
if (changed) _query = new DtNavMeshQuery(_nav);
|
||||
return any;
|
||||
}
|
||||
}
|
||||
190
Plugins/RynthCore.Plugin.RynthNav/TripPath.cs
Normal file
190
Plugins/RynthCore.Plugin.RynthNav/TripPath.cs
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// The ground a <see cref="PlannedTrip"/> walks, worked out once for the whole trip (on a worker:
|
||||
/// TilePathFinder reads the tiles and the route graph into its own navmesh): per walking step, the
|
||||
/// path from where the step starts to its point, thinned to the corners that matter; per hub step,
|
||||
/// the walk inside the Town Network. The path markers draw it and "save as nav route" writes it.
|
||||
/// Never changed after it's built. Host-free: the route tests build these with a fake path finder.
|
||||
/// </summary>
|
||||
internal sealed class TripPath
|
||||
{
|
||||
public readonly int TripId;
|
||||
/// <summary>Per step: the walk, first point = where it starts, last = the step's point (null = no walk).</summary>
|
||||
public readonly WorldPt[]?[] Walks;
|
||||
/// <summary>Per hub step: the walk inside the Town Network to the exit portal (null otherwise).</summary>
|
||||
public readonly WorldPt[]?[] Hub;
|
||||
/// <summary>What couldn't be worked out ("step 2: no navmesh path, a straight line"), for chat.</summary>
|
||||
public readonly IReadOnlyList<string> Notes;
|
||||
|
||||
public TripPath(int tripId, WorldPt[]?[] walks, WorldPt[]?[] hub, IReadOnlyList<string> notes)
|
||||
{
|
||||
TripId = tripId; Walks = walks; Hub = hub; Notes = notes;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class TripPathBuilder
|
||||
{
|
||||
/// <summary>A corner closer than this (yards) to the straight line past it is dropped.</summary>
|
||||
public const double ThinTolerance = 0.75;
|
||||
/// <summary>Straight stretches get a point at least this often (yards), so the markers and a nav follow the ground.</summary>
|
||||
public const double MaxSpacing = 60.0;
|
||||
/// <summary>Points closer together than this are one point.</summary>
|
||||
public const double DuplicateUnits = 0.5;
|
||||
|
||||
/// <summary>
|
||||
/// A walkable path from <paramref name="from"/> to <paramref name="to"/> (corners, both ends
|
||||
/// included), or null when there is none to be had; <paramref name="note"/> says why or what was
|
||||
/// approximated. <paramref name="intoPortal"/>: the walk ends by stepping into a portal at
|
||||
/// <paramref name="to"/> (so that one isn't kept out of).
|
||||
/// </summary>
|
||||
public delegate List<WorldPt>? WalkFinder(WorldPt from, WorldPt to, bool intoPortal, out string note);
|
||||
|
||||
/// <summary>
|
||||
/// The trip's ground: each walking step through <paramref name="walk"/> (a straight line where it
|
||||
/// has nothing, with a note), each hub step from <paramref name="net"/>; all thinned.
|
||||
/// </summary>
|
||||
public static TripPath Build(PlannedTrip trip, WalkFinder? walk, TownNet? net)
|
||||
{
|
||||
int n = trip.Count;
|
||||
var walks = new WorldPt[]?[n];
|
||||
var hub = new WorldPt[]?[n];
|
||||
var notes = new List<string>();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (trip.Steps[i].IsHub)
|
||||
{
|
||||
List<WorldPt>? inside = trip.HubWalk(i, net, out string why);
|
||||
if (inside == null) notes.Add($"step {i + 1}: {why}");
|
||||
else hub[i] = Thin(inside).ToArray();
|
||||
continue;
|
||||
}
|
||||
if (trip.WalkFrom[i] is not WorldPt from || trip.Point[i] is not WorldPt to) continue;
|
||||
string note = "";
|
||||
List<WorldPt>? raw = null;
|
||||
try { raw = walk?.Invoke(from, to, trip.Steps[i].UsePortal, out note); }
|
||||
catch (Exception ex) { note = "path finder failed: " + ex.Message; raw = null; }
|
||||
if (raw == null || raw.Count < 2)
|
||||
{
|
||||
raw = new List<WorldPt> { from, to };
|
||||
notes.Add($"step {i + 1}: {(note.Length > 0 ? note : "no navmesh path")}; a straight line there");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (note.Length > 0) notes.Add($"step {i + 1}: {note}");
|
||||
// The path ends on the navmesh beside the point; the point itself is where the step goes.
|
||||
if (raw[0].FlatDistance(from) > 2.0) raw.Insert(0, from);
|
||||
if (raw[^1].FlatDistance(to) > 2.0) raw.Add(new WorldPt(to.X, to.Y, raw[^1].H));
|
||||
}
|
||||
walks[i] = Thin(raw).ToArray();
|
||||
}
|
||||
return new TripPath(trip.Id, walks, hub, notes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path with near-duplicate points merged, corners within <paramref name="tolerance"/> of the
|
||||
/// line past them dropped (Ramer-Douglas-Peucker, ends kept), and straight stretches longer than
|
||||
/// <paramref name="maxSpacing"/> split evenly. Unknown heights are filled from the neighbours.
|
||||
/// </summary>
|
||||
public static List<WorldPt> Thin(IReadOnlyList<WorldPt> pts, double tolerance = ThinTolerance, double maxSpacing = MaxSpacing)
|
||||
{
|
||||
var dedup = new List<WorldPt>(pts.Count);
|
||||
foreach (WorldPt p in pts)
|
||||
{
|
||||
if (double.IsNaN(p.X) || double.IsNaN(p.Y)) continue;
|
||||
if (dedup.Count > 0 && dedup[^1].FlatDistance(p) < DuplicateUnits)
|
||||
{
|
||||
if (double.IsNaN(dedup[^1].H) && !double.IsNaN(p.H)) dedup[^1] = dedup[^1] with { H = p.H };
|
||||
continue;
|
||||
}
|
||||
dedup.Add(p);
|
||||
}
|
||||
FillHeights(dedup);
|
||||
if (dedup.Count <= 2) return Split(dedup, maxSpacing);
|
||||
|
||||
var keep = new bool[dedup.Count];
|
||||
keep[0] = keep[^1] = true;
|
||||
var stack = new Stack<(int A, int B)>();
|
||||
stack.Push((0, dedup.Count - 1));
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
var (a, b) = stack.Pop();
|
||||
int best = -1;
|
||||
double bestD = tolerance;
|
||||
for (int i = a + 1; i < b; i++)
|
||||
{
|
||||
double d = PlannedTrip.SegmentDistance(dedup[i], dedup[a], dedup[b]);
|
||||
if (d > bestD) { bestD = d; best = i; }
|
||||
}
|
||||
if (best < 0) continue;
|
||||
keep[best] = true;
|
||||
stack.Push((a, best));
|
||||
stack.Push((best, b));
|
||||
}
|
||||
var kept = new List<WorldPt>();
|
||||
for (int i = 0; i < dedup.Count; i++) if (keep[i]) kept.Add(dedup[i]);
|
||||
return Split(kept, maxSpacing);
|
||||
}
|
||||
|
||||
private static List<WorldPt> Split(List<WorldPt> pts, double maxSpacing)
|
||||
{
|
||||
if (pts.Count < 2 || maxSpacing <= 0) return pts;
|
||||
var o = new List<WorldPt>(pts.Count) { pts[0] };
|
||||
for (int i = 1; i < pts.Count; i++)
|
||||
{
|
||||
WorldPt a = pts[i - 1], b = pts[i];
|
||||
int parts = (int)Math.Ceiling(a.FlatDistance(b) / maxSpacing);
|
||||
for (int k = 1; k < parts; k++)
|
||||
{
|
||||
double t = (double)k / parts;
|
||||
o.Add(new WorldPt(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.H + (b.H - a.H) * t));
|
||||
}
|
||||
o.Add(b);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>NaN heights take the nearest known one before them (else after them).</summary>
|
||||
private static void FillHeights(List<WorldPt> pts)
|
||||
{
|
||||
double last = double.NaN;
|
||||
for (int i = 0; i < pts.Count; i++)
|
||||
{
|
||||
if (!double.IsNaN(pts[i].H)) last = pts[i].H;
|
||||
else if (!double.IsNaN(last)) pts[i] = pts[i] with { H = last };
|
||||
}
|
||||
double next = double.NaN;
|
||||
for (int i = pts.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (!double.IsNaN(pts[i].H)) next = pts[i].H;
|
||||
else if (!double.IsNaN(next)) pts[i] = pts[i] with { H = next };
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path stopped <paramref name="units"/> short of its end, measured along it (a walk to a
|
||||
/// portal stops before stepping in). Only the start is left when the path is shorter than that.
|
||||
/// </summary>
|
||||
public static List<WorldPt> StopShort(IReadOnlyList<WorldPt> pts, double units)
|
||||
{
|
||||
var o = new List<WorldPt>(pts);
|
||||
double left = units;
|
||||
while (o.Count >= 2 && left > 0)
|
||||
{
|
||||
WorldPt a = o[^2], b = o[^1];
|
||||
double d = a.FlatDistance(b);
|
||||
if (d > left)
|
||||
{
|
||||
double t = (d - left) / d;
|
||||
o[^1] = new WorldPt(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.H + (b.H - a.H) * t);
|
||||
return o;
|
||||
}
|
||||
left -= d;
|
||||
o.RemoveAt(o.Count - 1);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
}
|
||||
215
Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs
Normal file
215
Plugins/RynthCore.Plugin.RynthNav/TripPlan.cs
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthCore.Plugin.RynthNav;
|
||||
|
||||
/// <summary>
|
||||
/// A point in RynthNav's world units: X = east, Y = north (landblock * 192 + local), H = height
|
||||
/// (the pose z; NaN = not known).
|
||||
/// </summary>
|
||||
internal readonly record struct WorldPt(double X, double Y, double H)
|
||||
{
|
||||
public static WorldPt FromMap(double ns, double ew, double h = double.NaN) => new(NavCoords.WorldX(ew), NavCoords.WorldY(ns), h);
|
||||
public double Ns => NavCoords.NsFromWorld(Y);
|
||||
public double Ew => NavCoords.EwFromWorld(X);
|
||||
public double FlatDistance(WorldPt o) => Math.Sqrt((X - o.X) * (X - o.X) + (Y - o.Y) * (Y - o.Y));
|
||||
/// <summary>The landblock under the point (0xXXYY), or uint.MaxValue off the map.</summary>
|
||||
public uint Landblock
|
||||
{
|
||||
get
|
||||
{
|
||||
int x = (int)Math.Floor(X / 192.0), y = (int)Math.Floor(Y / 192.0);
|
||||
return x is >= 0 and <= 255 && y is >= 0 and <= 255 ? (uint)((x << 8) | y) : uint.MaxValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A recall of the plan, as the plan was made (RouteStep.RecallIndex indexes these).</summary>
|
||||
internal readonly record struct TripRecall(string Name, int SpellId, string Command, double CastSeconds);
|
||||
|
||||
/// <summary>
|
||||
/// One trip RynthNav planned (Route) or is walking (Go), frozen when it was planned: the steps,
|
||||
/// where it started, the recalls it may cast and the portal a dungeon goto ends in. Never changed
|
||||
/// after it's made, so the path builder (a worker), the markers and "save as nav route" all read
|
||||
/// the same thing without locks. Host-free: the route tests build these.
|
||||
///
|
||||
/// What each step walks (<see cref="WalkFrom"/> to <see cref="Point"/>):
|
||||
/// a walk step from where the last step left you to its point;
|
||||
/// a portal step the same, its point being the portal's entrance (then the teleport);
|
||||
/// a recall step nothing: cast where you stand (its point is that spot);
|
||||
/// a hub step nothing on the map: the walk inside the Town Network (TownNet's walks).
|
||||
/// After a portal or recall you stand at its landing (LandNs/LandEw); after a portal into a
|
||||
/// dungeon or the Town Network there's no map position until a hub step or a recall.
|
||||
/// </summary>
|
||||
internal sealed class PlannedTrip
|
||||
{
|
||||
/// <summary>A landblock this close to a leg (its centre, world units) counts as on the plan.</summary>
|
||||
public const double CoverUnits = 288.0;
|
||||
|
||||
public readonly int Id;
|
||||
public readonly IReadOnlyList<RouteStep> Steps;
|
||||
public readonly string Goal;
|
||||
public readonly double GoalNs, GoalEw;
|
||||
public readonly bool StartOnMap;
|
||||
public readonly WorldPt Start;
|
||||
public readonly uint StartCell;
|
||||
public readonly IReadOnlyList<TripRecall> Recalls;
|
||||
/// <summary>The portal object the last step walks into (a dungeon goto); "" = none or not known.</summary>
|
||||
public readonly string EnterPortal;
|
||||
/// <summary>The dungeon (or portal) that last step goes into; "" = none.</summary>
|
||||
public readonly string EnterName;
|
||||
/// <summary>The running goto's plan (false: planned with Route, not walked).</summary>
|
||||
public readonly bool Live;
|
||||
|
||||
/// <summary>Per step: where its walk starts (null = no walk: a recall, a hub step, or no map position).</summary>
|
||||
public readonly WorldPt?[] WalkFrom;
|
||||
/// <summary>Per step: where it happens (a walk's end, a portal's entrance, a recall's cast spot); null for a hub step.</summary>
|
||||
public readonly WorldPt?[] Point;
|
||||
|
||||
public PlannedTrip(int id, IReadOnlyList<RouteStep> steps, string goal, double goalNs, double goalEw,
|
||||
bool startOnMap, WorldPt start, uint startCell, IReadOnlyList<TripRecall>? recalls,
|
||||
string enterPortal = "", string enterName = "", bool live = false)
|
||||
{
|
||||
Id = id;
|
||||
Steps = steps.Count == 0 ? new[] { new RouteStep(goalNs, goalEw, false, false, "walk") } : new List<RouteStep>(steps).ToArray();
|
||||
Goal = goal; GoalNs = goalNs; GoalEw = goalEw;
|
||||
StartOnMap = startOnMap; Start = start; StartCell = startCell;
|
||||
Recalls = recalls ?? Array.Empty<TripRecall>();
|
||||
EnterPortal = enterPortal ?? ""; EnterName = enterName ?? ""; Live = live;
|
||||
|
||||
int n = Steps.Count;
|
||||
WalkFrom = new WorldPt?[n];
|
||||
Point = new WorldPt?[n];
|
||||
WorldPt? here = startOnMap ? start : null;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
RouteStep s = Steps[i];
|
||||
if (s.UseRecall)
|
||||
{
|
||||
// Cast where you stand: the trip's start for a first step (in a dungeon too).
|
||||
Point[i] = here ?? (i == 0 ? start : null);
|
||||
here = double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw);
|
||||
continue;
|
||||
}
|
||||
if (s.IsHub)
|
||||
{
|
||||
here = double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw);
|
||||
continue;
|
||||
}
|
||||
WorldPt to = WorldPt.FromMap(s.Ns, s.Ew);
|
||||
WalkFrom[i] = here;
|
||||
Point[i] = to;
|
||||
here = !s.UsePortal ? to : double.IsNaN(s.LandNs) ? null : WorldPt.FromMap(s.LandNs, s.LandEw);
|
||||
}
|
||||
}
|
||||
|
||||
public int Count => Steps.Count;
|
||||
public bool HasHub { get { foreach (RouteStep s in Steps) if (s.IsHub) return true; return false; } }
|
||||
|
||||
/// <summary>The last step is a portal into the place the goto was for (a dungeon).</summary>
|
||||
public bool EndsInEntrance => EnterName.Length > 0 && Steps.Count > 0 && Steps[^1].UsePortal;
|
||||
|
||||
/// <summary>The portal object step <paramref name="i"/> walks into: its label, or for the dungeon entrance, the portal's own name.</summary>
|
||||
public string PortalName(int i)
|
||||
{
|
||||
if (i == Steps.Count - 1 && EndsInEntrance && EnterPortal.Length > 0) return EnterPortal;
|
||||
return Steps[i].Label ?? "";
|
||||
}
|
||||
|
||||
/// <summary>The recall of step <paramref name="i"/>, or null when the plan doesn't know it.</summary>
|
||||
public TripRecall? RecallOf(int i)
|
||||
{
|
||||
int r = Steps[i].RecallIndex;
|
||||
return r >= 0 && r < Recalls.Count ? Recalls[r] : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is <paramref name="landblock"/> on this trip: the start's own landblock, near one of its walks
|
||||
/// (the straight leg, or the path built for it), its steps or landings, or inside the Town
|
||||
/// Network on a trip that takes it? A teleport somewhere else isn't.
|
||||
/// </summary>
|
||||
public bool Covers(uint landblock, TripPath? path, Func<uint, bool>? inHub)
|
||||
{
|
||||
if (landblock == 0 || landblock == ((StartCell >> 16) & 0xFFFF)) return true;
|
||||
if (HasHub && inHub != null && inHub(landblock)) return true;
|
||||
double cx = ((landblock >> 8) & 0xFF) * 192.0 + 96.0, cy = (landblock & 0xFF) * 192.0 + 96.0;
|
||||
var c = new WorldPt(cx, cy, 0);
|
||||
for (int i = 0; i < Steps.Count; i++)
|
||||
{
|
||||
if (Point[i] is WorldPt p && p.FlatDistance(c) <= CoverUnits) return true;
|
||||
if (WalkFrom[i] is WorldPt f && Point[i] is WorldPt t && SegmentDistance(c, f, t) <= CoverUnits) return true;
|
||||
RouteStep s = Steps[i];
|
||||
if (!double.IsNaN(s.LandNs) && WorldPt.FromMap(s.LandNs, s.LandEw).FlatDistance(c) <= CoverUnits) return true;
|
||||
WorldPt[]? w = path?.TripId == Id && i < path.Walks.Length ? path.Walks[i] : null;
|
||||
if (w != null)
|
||||
for (int k = 1; k < w.Length; k++)
|
||||
if (SegmentDistance(c, w[k - 1], w[k]) <= CoverUnits) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Flat distance from <paramref name="p"/> to the segment a→b.</summary>
|
||||
public static double SegmentDistance(WorldPt p, WorldPt a, WorldPt b) => SegmentDistance(p, a, b, out _);
|
||||
|
||||
/// <summary>Flat distance from <paramref name="p"/> to the segment a→b, and how far along it the nearest point is (0..1).</summary>
|
||||
public static double SegmentDistance(WorldPt p, WorldPt a, WorldPt b, out double t)
|
||||
{
|
||||
double vx = b.X - a.X, vy = b.Y - a.Y, l2 = vx * vx + vy * vy;
|
||||
t = l2 < 1e-9 ? 0 : Math.Clamp(((p.X - a.X) * vx + (p.Y - a.Y) * vy) / l2, 0, 1);
|
||||
double x = a.X + vx * t, y = a.Y + vy * t;
|
||||
return Math.Sqrt((p.X - x) * (p.X - x) + (p.Y - y) * (p.Y - y));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The walk inside the Town Network for hub step <paramref name="i"/>, in world units (the
|
||||
/// network's landblock): from the arrival the entry portal before it lands on (or, for a trip
|
||||
/// that starts inside, from where it started) to the exit portal. Null, with a reason, when
|
||||
/// townnet.json doesn't have it.
|
||||
/// </summary>
|
||||
public List<WorldPt>? HubWalk(int i, TownNet? net, out string why)
|
||||
{
|
||||
why = "";
|
||||
if (net == null) { why = "the Town Network data (townnet.json) isn't loaded"; return null; }
|
||||
RouteStep s = Steps[i];
|
||||
int exit = s.HubExit;
|
||||
if (exit < 0 || exit >= net.Exits.Count) { why = "the Town Network exit isn't in townnet.json"; return null; }
|
||||
IReadOnlyList<TownNetPoint>? pts = null;
|
||||
if (i > 0 && Steps[i - 1].UsePortal)
|
||||
{
|
||||
// The entry portal walked into: the townnet.json entry at that spot, and its arrival.
|
||||
RouteStep e = Steps[i - 1];
|
||||
TownNetEntry? best = null;
|
||||
double bestD = 2.0; // the plan's entry coordinates are the entry's own
|
||||
foreach (TownNetEntry en in net.Entries)
|
||||
{
|
||||
if (!en.OnMap) continue;
|
||||
double d = NavCoords.Distance(en.Ns, en.Ew, e.Ns, e.Ew);
|
||||
if (d < bestD) { bestD = d; best = en; }
|
||||
}
|
||||
if (best == null || best.Arrival < 0) { why = $"the entry portal {e.Label} isn't in townnet.json"; return null; }
|
||||
pts = net.Walk(best.Arrival, exit)?.Points;
|
||||
if (pts == null) { why = $"townnet.json has no walk from {best.Name}'s arrival to the {net.Exits[exit].Name}"; return null; }
|
||||
}
|
||||
else if (i == 0 && !StartOnMap && net.Contains((StartCell >> 16) & 0xFFFF))
|
||||
{
|
||||
double lx = Start.X - ((StartCell >> 24) & 0xFF) * 192.0, ly = Start.Y - ((StartCell >> 16) & 0xFF) * 192.0;
|
||||
pts = net.WayTo(exit, lx, ly, HubWalker.OffRouteUnits, out _);
|
||||
if (pts == null) { why = "no Town Network walk to that exit passes where the trip started"; return null; }
|
||||
}
|
||||
else { why = "the plan doesn't say how it gets into the Town Network"; return null; }
|
||||
|
||||
var list = new List<WorldPt>(pts.Count);
|
||||
foreach (TownNetPoint p in pts)
|
||||
list.Add(new WorldPt(((p.Cell >> 24) & 0xFF) * 192.0 + p.X, ((p.Cell >> 16) & 0xFF) * 192.0 + p.Y, p.Z));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Where the hub step's exit portal stands (world units), or null.</summary>
|
||||
public static WorldPt? HubExitPoint(TownNet? net, RouteStep s)
|
||||
{
|
||||
if (net == null || s.HubExit < 0 || s.HubExit >= net.Exits.Count) return null;
|
||||
TownNetExit x = net.Exits[s.HubExit];
|
||||
return new WorldPt(((x.Cell >> 24) & 0xFF) * 192.0 + x.X, ((x.Cell >> 16) & 0xFF) * 192.0 + x.Y, x.Z);
|
||||
}
|
||||
}
|
||||
|
|
@ -38,4 +38,9 @@
|
|||
<Compile Include="..\Shared\RynthAiScriptApi.cs" Link="Shared\RynthAiScriptApi.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ internal sealed class RynthNetCharacter
|
|||
|
||||
internal sealed class RynthNetSettings
|
||||
{
|
||||
public const string DefaultFolder = @"C:\Games\RynthSuite\RynthNet";
|
||||
public static readonly string DefaultFolder = Path.Combine(RynthCore.Install.RynthInstallPaths.SuiteDir, "RynthNet"); // C:\Games\RynthSuite\RynthNet by default
|
||||
/// <summary>The settings folder; RYNTHNET_DIR overrides it (tests, portable setups).</summary>
|
||||
public static string Folder => Environment.GetEnvironmentVariable("RYNTHNET_DIR") is { Length: > 0 } dir ? dir : DefaultFolder;
|
||||
public static string FilePath => Path.Combine(Folder, "settings.json");
|
||||
|
|
|
|||
471
Plugins/Shared/ActionPacer.cs
Normal file
471
Plugins/Shared/ActionPacer.cs
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/ActionPacer.cs
|
||||
// One server action at a time: RynthAi's pacing of uses, casts and combat-mode
|
||||
// changes on the server's answers (2026-10-06).
|
||||
//
|
||||
// Why: Drakkon's "can't use anything" and "stuck in the cast animation" stalls on
|
||||
// DreamWeave (ops/overnight/2026-10-06-action-pacing.md). Every stall began with a
|
||||
// combat-mode change sent while a corpse use was still unanswered by the server
|
||||
// (4 of 4 onsets; 0 stalls after ~920 uses with no such overlap). Once in that state
|
||||
// the server finishes nothing that waits on an animation until a relog, and the bot
|
||||
// made it worse by firing the next cast/use every 0.4-2.5 s because nothing waited
|
||||
// for the server's answer: the client busy count it paced on was zeroed and repaired
|
||||
// hundreds of times an hour, and "cast resolved" meant the enchantment, not the
|
||||
// server's UseDone.
|
||||
//
|
||||
// The rule here:
|
||||
// * A use, a use-on, a cast or a combat-mode change that RynthAi sends is the ONE
|
||||
// outstanding server action until the server answers it:
|
||||
// - use / use-on / cast: the next UseDone (GameEvent 0x01C7) after the send,
|
||||
// whatever its error (a refusal is an answer too); a wield also counts as
|
||||
// answered when the item reads wielded (a wield gets no UseDone);
|
||||
// - combat mode: the client reads the new mode and ModeSettleMs has passed
|
||||
// (the stance animation; the server sends no UseDone for it);
|
||||
// or its time limit passes (logged; nothing is force-cleared).
|
||||
// * While one is outstanding, RynthAi starts no other one (MayStart; mode changes
|
||||
// are refused right at ChangeCombatModeFor) and moves or turns the character
|
||||
// only to stop real movement (MoveAudit asks HoldsMovement).
|
||||
// * Heals keep their priority: a heal may go ahead of a corpse/door use the server
|
||||
// hasn't answered after HealAfterWorldUseMs (EmergencyAfterWorldUseMs at
|
||||
// Emergency Heal At), and one heal may follow a cast whose result is already in
|
||||
// (the server queues one cast behind the recoil).
|
||||
//
|
||||
// Opt-in (Enabled, RynthAi sets it at Init); off = every call goes through as before.
|
||||
// Linked into RynthAi only. UseAudit reports its sends through UseAudit.AfterSend.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
internal enum PacedKind
|
||||
{
|
||||
None,
|
||||
/// <summary>A door, corpse, portal or NPC: the server walks/turns the character to it first.</summary>
|
||||
WorldUse,
|
||||
/// <summary>A kit, potion, stone, wand or weapon (wield), scroll... in the character's own packs.</summary>
|
||||
ItemUse,
|
||||
/// <summary>A spell cast.</summary>
|
||||
Cast,
|
||||
/// <summary>A combat-mode (stance) change.</summary>
|
||||
CombatMode,
|
||||
}
|
||||
|
||||
internal enum HealNeed
|
||||
{
|
||||
None,
|
||||
/// <summary>Health under a heal line.</summary>
|
||||
Heal,
|
||||
/// <summary>Health at or under Emergency Heal At.</summary>
|
||||
Emergency,
|
||||
}
|
||||
|
||||
/// <summary>The one server action RynthAi is waiting on.</summary>
|
||||
internal sealed class PacedAction
|
||||
{
|
||||
public PacedKind Kind;
|
||||
public uint Id;
|
||||
public string Label = "";
|
||||
public string Who = "";
|
||||
public long SentMs;
|
||||
public int SeqAtSend;
|
||||
public int ModeTarget;
|
||||
public bool WieldedAtSend;
|
||||
public bool ResultSeen; // a cast's result is in (enchantment / chat); the server is in its recoil
|
||||
public bool HealQueued; // the one heal allowed behind that recoil went out
|
||||
public long ModeSeenMs; // when the client first read the requested mode
|
||||
public long WieldSeenMs; // when a wield first read done
|
||||
public readonly HashSet<string> LoggedWaits = new();
|
||||
}
|
||||
|
||||
internal static class ActionPacer
|
||||
{
|
||||
/// <summary>Off = nothing is paced (every call goes through as before). RynthAi turns it on.</summary>
|
||||
public static volatile bool Enabled;
|
||||
|
||||
/// <summary>Clock (ms); tests replace it.</summary>
|
||||
public static Func<long> NowMs = () => Environment.TickCount64;
|
||||
|
||||
// Time limits: the longest the server took to answer in 3.7 h of healthy logs (10-05/10-06,
|
||||
// p99 / max): corpse use 3.0 / 3.7 s, kit 2.5 s, buff cast 3.6 s, vital cast 4.7 / 5.0 s.
|
||||
public const long WorldUseMaxMs = 5000;
|
||||
public const long ItemUseMaxMs = 3500;
|
||||
public const long CastMaxMs = 7000;
|
||||
public const long ModeMaxMs = 2000;
|
||||
/// <summary>The stance animation after the client reads the new mode: no action before it ends.</summary>
|
||||
public const long ModeSettleMs = 800;
|
||||
/// <summary>A wield that reads done: a short settle for the wield motion.</summary>
|
||||
public const long WieldSettleMs = 150;
|
||||
/// <summary>A heal may go ahead of a door/corpse use unanswered this long (the server cancels the walk cleanly).</summary>
|
||||
public const long HealAfterWorldUseMs = 1000;
|
||||
public const long EmergencyAfterWorldUseMs = 300;
|
||||
/// <summary>A heal behind a stance change: once the client has read the new mode this long.</summary>
|
||||
public const long HealAfterModeReadMs = 300;
|
||||
/// <summary>An engine without UseDone: an action counts as answered after this (no real pacing).</summary>
|
||||
public const long NoUseDoneFallbackMs = 600;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private static PacedAction? _cur;
|
||||
|
||||
// Counters for /ra pace and the periodic summary.
|
||||
private static long _started, _answered, _timedOut, _sentOverOutstanding, _modeRefused, _modeSkipped;
|
||||
private static long _heldStarts, _heldMoves, _healsAhead;
|
||||
private static long _maxWaitMs;
|
||||
private static string _maxWaitWhat = "";
|
||||
private static readonly Dictionary<string, int> _holdsByWho = new();
|
||||
private static string _lastTimeout = "";
|
||||
|
||||
public static long Started => _started;
|
||||
public static long Answered => _answered;
|
||||
public static long TimedOut => _timedOut;
|
||||
public static long SentOverOutstanding => _sentOverOutstanding;
|
||||
public static long ModeChangesRefused => _modeRefused;
|
||||
public static long ModeChangesSkipped => _modeSkipped;
|
||||
public static long HeldStarts => _heldStarts;
|
||||
public static long HeldMoves => _heldMoves;
|
||||
public static long HealsAhead => _healsAhead;
|
||||
|
||||
/// <summary>Back to a fresh load (Init, logout, tests). Enabled is left as it is.</summary>
|
||||
public static void Reset()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_cur = null;
|
||||
_started = _answered = _timedOut = _sentOverOutstanding = _modeRefused = _modeSkipped = 0;
|
||||
_heldStarts = _heldMoves = _healsAhead = 0;
|
||||
_maxWaitMs = 0;
|
||||
_maxWaitWhat = "";
|
||||
_holdsByWho.Clear();
|
||||
_lastTimeout = "";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forget the outstanding action (logout, death, portal): the server dropped it.</summary>
|
||||
public static void Forget(string why)
|
||||
{
|
||||
lock (Gate) { _cur = null; }
|
||||
}
|
||||
|
||||
// ── Recording what went out ──────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Records an action that just went out. <paramref name="seqAtSend"/> is the UseDone count read
|
||||
/// BEFORE the send. Logs once when it went out over another unanswered action (a player command,
|
||||
/// a meta, or a heal let ahead).
|
||||
/// </summary>
|
||||
public static void Begin(RynthCoreHost host, PacedKind kind, uint id, string label, string who, int seqAtSend, int modeTarget = 0)
|
||||
{
|
||||
if (!Enabled || kind == PacedKind.None) return;
|
||||
PacedAction? prev = Current(host);
|
||||
long now = NowMs();
|
||||
var a = new PacedAction
|
||||
{
|
||||
Kind = kind, Id = id, Label = label, Who = who, SentMs = now, SeqAtSend = seqAtSend, ModeTarget = modeTarget,
|
||||
};
|
||||
if (kind == PacedKind.ItemUse) a.WieldedAtSend = IsWieldedByPlayer(host, id);
|
||||
string? over = null;
|
||||
lock (Gate)
|
||||
{
|
||||
_started++;
|
||||
if (prev != null)
|
||||
{
|
||||
_sentOverOutstanding++;
|
||||
over = $"[Pace] {who}: {Describe(kind, label)} went out while {Describe(prev.Kind, prev.Label)} ({prev.Who}) was unanswered for {now - prev.SentMs} ms";
|
||||
}
|
||||
_cur = a;
|
||||
}
|
||||
if (over != null) Log(host, over);
|
||||
}
|
||||
|
||||
/// <summary>A cast's result (enchantment landed, "You cast ...") is in: the server is in its recoil.</summary>
|
||||
public static void NoteCastResult()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if (_cur is { Kind: PacedKind.Cast }) _cur.ResultSeen = true;
|
||||
}
|
||||
}
|
||||
|
||||
// ── The outstanding action ───────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The action still waiting for the server's answer, or null. Each call settles answers and
|
||||
/// time limits first, so it is always current.
|
||||
/// </summary>
|
||||
public static PacedAction? Current(RynthCoreHost host)
|
||||
{
|
||||
if (!Enabled) return null;
|
||||
PacedAction? a;
|
||||
lock (Gate) a = _cur;
|
||||
if (a == null) return null;
|
||||
|
||||
long now = NowMs();
|
||||
long age = now - a.SentMs;
|
||||
string? answeredHow = null;
|
||||
bool timedOut = false;
|
||||
|
||||
switch (a.Kind)
|
||||
{
|
||||
case PacedKind.WorldUse:
|
||||
case PacedKind.ItemUse:
|
||||
case PacedKind.Cast:
|
||||
{
|
||||
bool hasSeq = false;
|
||||
int seq = 0;
|
||||
try { hasSeq = host.HasUseDoneSeq; if (hasSeq) seq = host.GetUseDoneSeq(); } catch { hasSeq = false; }
|
||||
if (hasSeq && seq != a.SeqAtSend)
|
||||
{
|
||||
answeredHow = "UseDone";
|
||||
}
|
||||
else if (a.Kind == PacedKind.ItemUse && IsWieldedByPlayer(host, a.Id) != a.WieldedAtSend)
|
||||
{
|
||||
if (a.WieldSeenMs == 0) a.WieldSeenMs = now;
|
||||
if (now - a.WieldSeenMs >= WieldSettleMs) answeredHow = "wield";
|
||||
}
|
||||
else if (!hasSeq && age >= NoUseDoneFallbackMs)
|
||||
{
|
||||
answeredHow = "time (no UseDone on this engine)";
|
||||
}
|
||||
long max = a.Kind switch { PacedKind.WorldUse => WorldUseMaxMs, PacedKind.Cast => CastMaxMs, _ => ItemUseMaxMs };
|
||||
if (answeredHow == null && age >= max) timedOut = true;
|
||||
break;
|
||||
}
|
||||
case PacedKind.CombatMode:
|
||||
{
|
||||
int mode = -1;
|
||||
try { if (host.HasGetCurrentCombatMode) mode = host.GetCurrentCombatMode(); } catch { mode = -1; }
|
||||
if (mode == a.ModeTarget || mode < 0)
|
||||
{
|
||||
if (a.ModeSeenMs == 0) a.ModeSeenMs = now;
|
||||
if (age >= ModeSettleMs) answeredHow = "mode";
|
||||
}
|
||||
if (answeredHow == null && age >= ModeMaxMs) timedOut = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (answeredHow == null && !timedOut) return a;
|
||||
|
||||
string? line = null;
|
||||
lock (Gate)
|
||||
{
|
||||
if (!ReferenceEquals(_cur, a)) return _cur; // replaced meanwhile
|
||||
_cur = null;
|
||||
if (timedOut)
|
||||
{
|
||||
_timedOut++;
|
||||
_lastTimeout = $"{Describe(a.Kind, a.Label)} ({a.Who}) after {age} ms";
|
||||
line = $"[Pace] no answer from the server to {Describe(a.Kind, a.Label)} ({a.Who}) in {age} ms - going on (nothing cleared)";
|
||||
}
|
||||
else
|
||||
{
|
||||
_answered++;
|
||||
}
|
||||
}
|
||||
if (line != null) Log(host, line);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>True while an action is waiting for the server (out: it).</summary>
|
||||
public static bool Outstanding(RynthCoreHost host, out PacedAction? action)
|
||||
{
|
||||
action = Current(host);
|
||||
return action != null;
|
||||
}
|
||||
|
||||
// ── Gates ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// May <paramref name="who"/> send a use, a cast or a mode change now? False (with why) while
|
||||
/// another action waits for the server, except the heal rules in the file header. One log
|
||||
/// line per outstanding action and subsystem.
|
||||
/// </summary>
|
||||
public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why)
|
||||
{
|
||||
why = "";
|
||||
PacedAction? a = Current(host);
|
||||
if (a == null) return true;
|
||||
long age = NowMs() - a.SentMs;
|
||||
|
||||
if (heal != HealNeed.None)
|
||||
{
|
||||
if (a.Kind == PacedKind.WorldUse
|
||||
&& age >= (heal == HealNeed.Emergency ? EmergencyAfterWorldUseMs : HealAfterWorldUseMs))
|
||||
{
|
||||
lock (Gate) _healsAhead++;
|
||||
Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms)");
|
||||
return true;
|
||||
}
|
||||
// A stance change (most often the one this heal asked for: the wand swap, or peace for
|
||||
// a kit): the heal goes once the client has read the new mode for HealAfterModeReadMs,
|
||||
// like BuffManager's emergency settle, not the full ModeSettleMs.
|
||||
if (a.Kind == PacedKind.CombatMode && a.ModeSeenMs != 0 && NowMs() - a.ModeSeenMs >= HealAfterModeReadMs)
|
||||
return true;
|
||||
if (a.Kind == PacedKind.Cast && a.ResultSeen && !a.HealQueued)
|
||||
{
|
||||
a.HealQueued = true;
|
||||
lock (Gate) _healsAhead++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
why = $"{Describe(a.Kind, a.Label)} sent {age} ms ago by {a.Who} has no answer yet";
|
||||
bool log;
|
||||
lock (Gate)
|
||||
{
|
||||
_heldStarts++;
|
||||
_holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1;
|
||||
if (age > _maxWaitMs) { _maxWaitMs = age; _maxWaitWhat = Describe(a.Kind, a.Label); }
|
||||
log = a.LoggedWaits.Add(who);
|
||||
}
|
||||
if (log) Log(host, $"[Pace] {who} waits: {why}");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while the outstanding action is one the server animates (all of them: the walk/turn
|
||||
/// to a used object, a heal or wield motion, a cast, a stance change). MoveAudit holds
|
||||
/// RynthAi's movement starts and turns meanwhile.
|
||||
/// </summary>
|
||||
public static bool HoldsMovement(RynthCoreHost host, out string what)
|
||||
{
|
||||
what = "";
|
||||
PacedAction? a = Current(host);
|
||||
if (a == null) return false;
|
||||
what = $"{Describe(a.Kind, a.Label)} ({a.Who}, {NowMs() - a.SentMs} ms)";
|
||||
lock (Gate) _heldMoves++;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
internal static string Describe(PacedKind kind, string label) => kind switch
|
||||
{
|
||||
PacedKind.WorldUse => $"the use of {label}",
|
||||
PacedKind.ItemUse => $"the use of {label}",
|
||||
PacedKind.Cast => $"the cast of {label}",
|
||||
PacedKind.CombatMode => $"the change to {label} mode",
|
||||
_ => label,
|
||||
};
|
||||
|
||||
internal static string ModeName(int mode) => mode switch
|
||||
{
|
||||
1 => "Peace", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => $"mode {mode}",
|
||||
};
|
||||
|
||||
private static bool IsWieldedByPlayer(RynthCoreHost host, uint id)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (id == 0 || !host.HasGetObjectWielderInfo || !host.HasGetPlayerId) return false;
|
||||
uint player = host.GetPlayerId();
|
||||
return player != 0 && host.TryGetObjectWielderInfo(id, out uint wielder, out _) && wielder == player;
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/// <summary>World object (no container, no wielder) = the server walks to it; else an item of ours.</summary>
|
||||
internal static PacedKind ClassifyUse(RynthCoreHost host, uint id, bool doorOrCorpse)
|
||||
{
|
||||
if (doorOrCorpse) return PacedKind.WorldUse;
|
||||
try
|
||||
{
|
||||
if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _))
|
||||
return container == 0 && wielder == 0 ? PacedKind.WorldUse : PacedKind.ItemUse;
|
||||
}
|
||||
catch { }
|
||||
return PacedKind.ItemUse;
|
||||
}
|
||||
|
||||
internal static int UseDoneSeqNow(RynthCoreHost host)
|
||||
{
|
||||
try { return host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { return 0; }
|
||||
}
|
||||
|
||||
private static void Log(RynthCoreHost host, string line)
|
||||
{
|
||||
try { host.Log(line); } catch { }
|
||||
}
|
||||
|
||||
/// <summary>Lines for /ra pace.</summary>
|
||||
public static string[] DescribeLines(RynthCoreHost host)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
PacedAction? a = Current(host);
|
||||
lines.Add($"Action pacing: {(Enabled ? "on" : "off")} (one server action at a time; see ops note 2026-10-06-action-pacing)");
|
||||
lines.Add(a == null
|
||||
? " Waiting on: nothing"
|
||||
: $" Waiting on: {Describe(a.Kind, a.Label)} from {a.Who}, sent {NowMs() - a.SentMs} ms ago{(a.ResultSeen ? " (result in, recoil)" : "")}");
|
||||
lock (Gate)
|
||||
{
|
||||
lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}");
|
||||
lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}");
|
||||
lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}");
|
||||
if (_maxWaitMs > 0) lines.Add($" Longest wait seen: {_maxWaitMs} ms ({_maxWaitWhat})");
|
||||
if (_holdsByWho.Count > 0)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
foreach (var kv in _holdsByWho) parts.Add($"{kv.Key} {kv.Value}");
|
||||
lines.Add(" Holds by subsystem: " + string.Join(", ", parts));
|
||||
}
|
||||
}
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
// ── The paced sends that are not uses ────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// CastSpell, recorded as the outstanding action. RynthAi's callers check MayStart first;
|
||||
/// <paramref name="asked"/> (a player command or meta) is never held, only recorded.
|
||||
/// </summary>
|
||||
public static bool CastSpellFor(this RynthCoreHost host, uint targetId, int spellId, string who, string label, bool asked = false)
|
||||
{
|
||||
int seq = UseDoneSeqNow(host);
|
||||
bool ok = host.CastSpell(targetId, spellId);
|
||||
if (ok) Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ChangeCombatMode with the pacing rules: nothing is sent when the client already reads that
|
||||
/// mode (the engine would push a raw 0x53 to the server anyway, and on ACE every mode change
|
||||
/// cancels the walk/turn of a pending use and fails a cast in progress) unless
|
||||
/// <paramref name="force"/>; and nothing while another server action is unanswered unless
|
||||
/// <paramref name="force"/>. Returns false only when the pacing held the request back (or the
|
||||
/// client already reads that mode); otherwise the request was made, as a plain ChangeCombatMode
|
||||
/// call was before (whose result the callers never read), so their retry timers run as before.
|
||||
/// </summary>
|
||||
public static bool ChangeCombatModeFor(this RynthCoreHost host, int mode, string who, string why, bool force = false)
|
||||
{
|
||||
if (!host.HasChangeCombatMode) return true; // nothing to send or pace (the callers went on before too)
|
||||
if (Enabled && !force)
|
||||
{
|
||||
int current = -1;
|
||||
try { if (host.HasGetCurrentCombatMode) current = host.GetCurrentCombatMode(); } catch { current = -1; }
|
||||
if (current == mode)
|
||||
{
|
||||
lock (Gate) _modeSkipped++;
|
||||
return false;
|
||||
}
|
||||
PacedAction? a = Current(host);
|
||||
if (a != null)
|
||||
{
|
||||
bool log;
|
||||
lock (Gate)
|
||||
{
|
||||
_modeRefused++;
|
||||
log = a.LoggedWaits.Add("mode:" + who);
|
||||
}
|
||||
if (log)
|
||||
Log(host, $"[Pace] {who}: change to {ModeName(mode)} mode held ({why}): {Describe(a.Kind, a.Label)} sent {NowMs() - a.SentMs} ms ago by {a.Who} has no answer yet (a mode change now would cancel it on the server)");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
int seq = UseDoneSeqNow(host);
|
||||
if (host.ChangeCombatMode(mode))
|
||||
Begin(host, PacedKind.CombatMode, 0, ModeName(mode), who, seq, mode);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -50,37 +50,142 @@ internal static class MoveAudit
|
|||
|
||||
public static bool SetAutoRunBy(this RynthCoreHost host, string who, bool on)
|
||||
{
|
||||
if (on && HeldForUse(host, who, "SetAutoRun(True)")) return false;
|
||||
if (HeldForAction(host, who, on ? "SetAutoRun(True)" : "SetAutoRun(False)", isStop: !on)) return false;
|
||||
Note(host, who, "SetAutoRun", on ? "True" : "False", collapseByKindOnly: false);
|
||||
lock (Gate) { _autoRunOn = on; if (on) _lastStartMs = NowMs(); }
|
||||
return host.SetAutoRun(on);
|
||||
}
|
||||
|
||||
public static bool StopCompletelyBy(this RynthCoreHost host, string who)
|
||||
{
|
||||
if (HeldForAction(host, who, "StopCompletely()", isStop: true)) return false;
|
||||
Note(host, who, "StopCompletely", "", collapseByKindOnly: false);
|
||||
lock (Gate) { _autoRunOn = false; _motionsOn.Clear(); }
|
||||
return host.StopCompletely();
|
||||
}
|
||||
|
||||
public static bool SetMotionBy(this RynthCoreHost host, string who, uint motion, bool on)
|
||||
{
|
||||
if (on && HeldForUse(host, who, $"SetMotion(0x{motion:X8}, True)")) return false;
|
||||
if (HeldForAction(host, who, $"SetMotion(0x{motion:X8}, {(on ? "True" : "False")})", isStop: !on, motion)) return false;
|
||||
Note(host, who, "SetMotion", $"0x{motion:X8}, {(on ? "True" : "False")}", collapseByKindOnly: false);
|
||||
lock (Gate) { if (on) { _motionsOn.Add(motion); _lastStartMs = NowMs(); } else _motionsOn.Remove(motion); }
|
||||
return host.SetMotion(motion, on);
|
||||
}
|
||||
|
||||
public static bool DoMovementBy(this RynthCoreHost host, string who, uint motion, float speed, int holdKey)
|
||||
{
|
||||
if (HeldForUse(host, who, $"DoMovement(0x{motion:X8})")) return false;
|
||||
if (HeldForAction(host, who, $"DoMovement(0x{motion:X8})", isStop: false)) return false;
|
||||
Note(host, who, "DoMovement", $"0x{motion:X8}, {speed:0.##}, {holdKey}", collapseByKindOnly: false);
|
||||
lock (Gate) { _motionsOn.Add(motion); _lastStartMs = NowMs(); }
|
||||
return host.DoMovement(motion, speed, holdKey);
|
||||
}
|
||||
|
||||
// -- Hold while any paced server action is unanswered (2026-10-06, ActionPacer) ----------
|
||||
// A use, cast or stance change the server is still animating is what a movement packet
|
||||
// disturbs: on ACE every client MoveToState is applied to the server's physics, a mode change
|
||||
// or a stop cancels the walk/turn to a used object, and a cast's end waits for its gesture.
|
||||
// While ActionPacer has one outstanding:
|
||||
// * starting to move or turning is held (returns false, one log line per action and caller);
|
||||
// * a stop goes through only when RynthAi itself has the character moving (autorun, or the
|
||||
// motion it turned on); a stop with nothing of ours moving would only send a redundant
|
||||
// movement packet in the middle of the action, so it is held as well;
|
||||
// * the deliberate kick for a held cast (Buff/Nudge), a macro stop and typed commands pass.
|
||||
// Off unless ActionPacer.Enabled (RynthAi only).
|
||||
|
||||
private static bool _autoRunOn;
|
||||
private static long _lastStartMs = long.MinValue / 2;
|
||||
/// <summary>Our "moving" state counts only this long after the last start we sent: nav re-sends
|
||||
/// autorun every second while it drives, and AC can stop on its own (arrival, a portal) without
|
||||
/// RynthAi sending a stop, so an old "on" must not hold casts back forever.</summary>
|
||||
internal const long OwnMovementFreshMs = 3000;
|
||||
private static readonly System.Collections.Generic.HashSet<uint> _motionsOn = new();
|
||||
private static readonly System.Collections.Generic.HashSet<string> _actionHoldLogged = new();
|
||||
private static long _actionHoldLoggedFor = long.MinValue;
|
||||
|
||||
/// <summary>Callers whose movement is never held: the cast nudge, a macro stop, typed commands.</summary>
|
||||
internal static bool IsExemptFromActionHold(string who) =>
|
||||
who == "Buff/Nudge" || who == "MacroStop" || who == "Command";
|
||||
|
||||
/// <summary>True when RynthAi itself has the character moving (autorun or a motion it turned on).</summary>
|
||||
internal static bool OwnMovementActive
|
||||
{
|
||||
get { lock (Gate) return (_autoRunOn || _motionsOn.Count > 0) && NowMs() - _lastStartMs < OwnMovementFreshMs; }
|
||||
}
|
||||
|
||||
/// <summary>True when the call must wait for an unanswered paced action (internal for the tests).</summary>
|
||||
internal static bool HeldForAction(RynthCoreHost host, string who, string call, bool isStop, uint motion = 0)
|
||||
{
|
||||
if (!ActionPacer.Enabled || IsExemptFromActionHold(who)) return false;
|
||||
if (isStop)
|
||||
{
|
||||
bool moving;
|
||||
lock (Gate) moving = (motion != 0 ? _motionsOn.Contains(motion) : (_autoRunOn || _motionsOn.Count > 0))
|
||||
&& NowMs() - _lastStartMs < OwnMovementFreshMs;
|
||||
if (moving) return false; // a real stop always goes through
|
||||
}
|
||||
var pending = ActionPacer.Current(host);
|
||||
if (pending == null) return false;
|
||||
if (!ActionPacer.HoldsMovement(host, out string what)) return false;
|
||||
bool log;
|
||||
lock (Gate)
|
||||
{
|
||||
if (_actionHoldLoggedFor != pending.SentMs) { _actionHoldLoggedFor = pending.SentMs; _actionHoldLogged.Clear(); }
|
||||
log = Enabled && _actionHoldLogged.Add(who + (isStop ? "|stop" : "|move"));
|
||||
}
|
||||
if (log)
|
||||
{
|
||||
string kind = isStop ? "redundant stop, nothing of ours is moving" : "move/turn";
|
||||
try { host.Log($"[Move] {PluginName}/{who} {call} held ({kind}): the server is still answering {what}"); }
|
||||
catch { }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Hold while a door/corpse use is in flight (2026-10-06) ─────────────────────
|
||||
// A move or a turn sent while the server is still walking/turning the character to a used
|
||||
// door or corpse cancels that use (ACE stops its move-to chain on a client MoveToState).
|
||||
// UseAudit knows when one is in flight (opt-in, UseAudit.TrackWorldUses); until the server
|
||||
// answers (UseDone) or UseAudit.WorldUseInFlightMaxMs passes, starting to move or turning
|
||||
// is skipped and the call returns false. Stops always go through. One line per held use.
|
||||
|
||||
private static uint _heldLoggedFor;
|
||||
private static long _heldLoggedAt;
|
||||
|
||||
/// <summary>True when the call must wait for an in-flight door/corpse use (internal for the tests).</summary>
|
||||
internal static bool HeldForUse(RynthCoreHost host, string who, string call)
|
||||
{
|
||||
if (!UseAudit.WorldUseInFlight(host, out uint objectId)) return false;
|
||||
bool log;
|
||||
lock (Gate)
|
||||
{
|
||||
long now = NowMs();
|
||||
log = Enabled && (objectId != _heldLoggedFor || now - _heldLoggedAt > UseAudit.WorldUseInFlightMaxMs);
|
||||
if (log) { _heldLoggedFor = objectId; _heldLoggedAt = now; }
|
||||
}
|
||||
if (log)
|
||||
{
|
||||
try { host.Log($"[Move] {PluginName}/{who} {call} held: the server is still answering the use of 0x{objectId:X8} (moving now would cancel it)"); }
|
||||
catch { }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool StopMovementBy(this RynthCoreHost host, string who, uint motion, int holdKey)
|
||||
{
|
||||
if (HeldForAction(host, who, $"StopMovement(0x{motion:X8})", isStop: true, motion)) return false;
|
||||
Note(host, who, "StopMovement", $"0x{motion:X8}, {holdKey}", collapseByKindOnly: false);
|
||||
lock (Gate) _motionsOn.Remove(motion);
|
||||
return host.StopMovement(motion, holdKey);
|
||||
}
|
||||
|
||||
/// <summary>A heading snap. Successive turns from one subsystem collapse whatever the angle.</summary>
|
||||
public static bool TurnToHeadingBy(this RynthCoreHost host, string who, float headingDegrees)
|
||||
{
|
||||
if (HeldForUse(host, who, "TurnToHeading")) return false;
|
||||
if (HeldForAction(host, who, "TurnToHeading", isStop: false)) return false;
|
||||
Note(host, who, "TurnToHeading", headingDegrees.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture), collapseByKindOnly: true);
|
||||
return host.TurnToHeading(headingDegrees);
|
||||
}
|
||||
|
|
@ -131,6 +236,13 @@ internal static class MoveAudit
|
|||
_lastWrittenMs = long.MinValue;
|
||||
_repeats = 0;
|
||||
_repeatLastArg = "";
|
||||
_heldLoggedFor = 0;
|
||||
_heldLoggedAt = 0;
|
||||
_autoRunOn = false;
|
||||
_motionsOn.Clear();
|
||||
_lastStartMs = long.MinValue / 2;
|
||||
_actionHoldLogged.Clear();
|
||||
_actionHoldLoggedFor = long.MinValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
175
Plugins/Shared/Nav3DText.cs
Normal file
175
Plugins/Shared/Nav3DText.cs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/Nav3DText.cs
|
||||
// Text in the world on the engine's Nav3D buffer: a small stroke font drawn as
|
||||
// filled strokes (Nav3D triangles) on an upright plane turned toward the
|
||||
// character. RynthAi's waypoint labels (NavOverlay) and RynthNav's path
|
||||
// markers both draw with it. Compiled into each plugin (linked source); no
|
||||
// host calls, so the offline tests compile it too.
|
||||
//
|
||||
// Frame: the Nav3D one (X = east metres, Y = height, Z = north metres, in the
|
||||
// player's landblock). Call only from the plugin tick (the Nav3D submit side).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
/// <summary>Where Nav3D geometry goes: the engine's buffer in the game, a recorder in the tests.</summary>
|
||||
internal interface INav3DSink
|
||||
{
|
||||
void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb);
|
||||
void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One line of text over a point in the world, as filled strokes facing the viewer, sized up with
|
||||
/// distance so far text stays readable. Rows stack upward from just above the point.
|
||||
/// </summary>
|
||||
internal static class Nav3DText
|
||||
{
|
||||
/// <summary>Row 0's baseline above the point (m).</summary>
|
||||
public const float LabelLift = 1.1f;
|
||||
public const float MinLineHeight = 0.30f, MaxLineHeight = 1.5f, HeightPerMetre = 0.015f;
|
||||
|
||||
/// <summary>The line height (m) for text this far from the viewer.</summary>
|
||||
public static float LineHeight(float distance) =>
|
||||
Math.Clamp(MinLineHeight + HeightPerMetre * distance, MinLineHeight, MaxLineHeight);
|
||||
|
||||
/// <summary>
|
||||
/// Emits <paramref name="text"/> over (x, y, z), row <paramref name="row"/>, facing the viewer at
|
||||
/// (viewX, viewZ). Counts triangles in <paramref name="tris"/>; returns false (having drawn what
|
||||
/// fitted) when the next stroke would go past <paramref name="maxTris"/>.
|
||||
/// </summary>
|
||||
public static bool Emit(float x, float y, float z, string text, int row, uint color,
|
||||
float viewX, float viewZ, INav3DSink sink, ref int tris, int maxTris)
|
||||
{
|
||||
float dx = x - viewX, dz = z - viewZ;
|
||||
float d = MathF.Sqrt(dx * dx + dz * dz);
|
||||
// Text faces the viewer: its right-hand direction is the view direction turned 90° clockwise.
|
||||
float fx = 0f, fz = 1f;
|
||||
if (d > 0.01f) { fx = dx / d; fz = dz / d; }
|
||||
float rx = fz, rz = -fx;
|
||||
|
||||
float h = LineHeight(d);
|
||||
float s = h / NavStrokeFont.Height;
|
||||
float width = NavStrokeFont.Width(text) * s;
|
||||
float u0 = -width * 0.5f;
|
||||
float v0 = y + LabelLift + row * h * 1.5f;
|
||||
float half = NavStrokeFont.Stroke * 0.5f * s;
|
||||
|
||||
for (int c = 0; c < text.Length; c++)
|
||||
{
|
||||
float[][]? strokes = NavStrokeFont.Glyph(text[c]);
|
||||
if (strokes == null) continue;
|
||||
float cu = u0 + c * NavStrokeFont.Advance * s;
|
||||
foreach (float[] poly in strokes)
|
||||
{
|
||||
for (int k = 0; k + 3 < poly.Length; k += 2)
|
||||
{
|
||||
if (tris + 2 > maxTris) return false;
|
||||
float au = cu + poly[k] * s, av = v0 + poly[k + 1] * s;
|
||||
float bu = cu + poly[k + 2] * s, bv = v0 + poly[k + 3] * s;
|
||||
Quad(sink, x, z, color, rx, rz, au, av, bu, bv, half);
|
||||
tris += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// A stroke a→b in the text plane (u along the text, v up) as two triangles, its ends pushed
|
||||
// out half a stroke so corners close.
|
||||
private static void Quad(INav3DSink sink, float x, float z, uint color, float rx, float rz,
|
||||
float au, float av, float bu, float bv, float half)
|
||||
{
|
||||
float eu = bu - au, ev = bv - av;
|
||||
float len = MathF.Sqrt(eu * eu + ev * ev);
|
||||
if (len < 1e-5f) { eu = 0f; ev = 1f; }
|
||||
else { eu /= len; ev /= len; }
|
||||
au -= eu * half; av -= ev * half;
|
||||
bu += eu * half; bv += ev * half;
|
||||
float nu = -ev * half, nv = eu * half;
|
||||
|
||||
// (u, v) → world: u runs along the right-hand direction, v is height.
|
||||
float a1x = x + rx * (au + nu), a1z = z + rz * (au + nu), a1y = av + nv;
|
||||
float a2x = x + rx * (au - nu), a2z = z + rz * (au - nu), a2y = av - nv;
|
||||
float b1x = x + rx * (bu + nu), b1z = z + rz * (bu + nu), b1y = bv + nv;
|
||||
float b2x = x + rx * (bu - nu), b2z = z + rz * (bu - nu), b2y = bv - nv;
|
||||
sink.Triangle(a1x, a1y, a1z, a2x, a2y, a2z, b1x, b1y, b1z, color);
|
||||
sink.Triangle(a2x, a2y, a2z, b2x, b2y, b2z, b1x, b1y, b1z, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A small stroke font for labels in the world: digits, A-Z and a few marks, each a set of
|
||||
/// polylines on a 4 x 6 grid (y up). Lower case draws as upper case; anything else is a gap.
|
||||
/// </summary>
|
||||
internal static class NavStrokeFont
|
||||
{
|
||||
public const float Height = 6f, Advance = 5.5f, Stroke = 0.75f;
|
||||
|
||||
/// <summary>The text's drawn width in grid units.</summary>
|
||||
public static float Width(string text) => text.Length == 0 ? 0f : text.Length * Advance - (Advance - 4f);
|
||||
|
||||
public static float[][]? Glyph(char c)
|
||||
{
|
||||
c = char.ToUpperInvariant(c);
|
||||
return Glyphs.TryGetValue(c, out float[][]? g) ? g : null;
|
||||
}
|
||||
|
||||
private static float[] P(params float[] xy) => xy;
|
||||
|
||||
private static readonly Dictionary<char, float[][]> Glyphs = new()
|
||||
{
|
||||
['0'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(0, 0, 4, 6) },
|
||||
['1'] = new[] { P(1, 5, 2, 6, 2, 0), P(1, 0, 3, 0) },
|
||||
['2'] = new[] { P(0, 6, 4, 6, 4, 3, 0, 3, 0, 0, 4, 0) },
|
||||
['3'] = new[] { P(0, 6, 4, 6, 4, 0, 0, 0), P(1, 3, 4, 3) },
|
||||
['4'] = new[] { P(0, 6, 0, 3, 4, 3), P(4, 6, 4, 0) },
|
||||
['5'] = new[] { P(4, 6, 0, 6, 0, 4, 3, 4, 4, 3, 4, 1, 3, 0, 0, 0) },
|
||||
['6'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0, 4, 3, 0, 3) },
|
||||
['7'] = new[] { P(0, 6, 4, 6, 1, 0) },
|
||||
['8'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(0, 3, 4, 3) },
|
||||
['9'] = new[] { P(4, 3, 0, 3, 0, 6, 4, 6, 4, 0, 0, 0) },
|
||||
['A'] = new[] { P(0, 0, 0, 4, 2, 6, 4, 4, 4, 0), P(0, 3, 4, 3) },
|
||||
['B'] = new[] { P(0, 0, 0, 6, 3, 6, 4, 5, 4, 4, 3, 3, 0, 3), P(3, 3, 4, 2, 4, 1, 3, 0, 0, 0) },
|
||||
['C'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0) },
|
||||
['D'] = new[] { P(0, 0, 0, 6, 2, 6, 4, 4, 4, 2, 2, 0, 0, 0) },
|
||||
['E'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0), P(0, 3, 3, 3) },
|
||||
['F'] = new[] { P(4, 6, 0, 6, 0, 0), P(0, 3, 3, 3) },
|
||||
['G'] = new[] { P(4, 6, 0, 6, 0, 0, 4, 0, 4, 3, 2, 3) },
|
||||
['H'] = new[] { P(0, 0, 0, 6), P(4, 0, 4, 6), P(0, 3, 4, 3) },
|
||||
['I'] = new[] { P(1, 6, 3, 6), P(2, 6, 2, 0), P(1, 0, 3, 0) },
|
||||
['J'] = new[] { P(4, 6, 4, 0, 0, 0, 0, 2) },
|
||||
['K'] = new[] { P(0, 0, 0, 6), P(4, 6, 0, 3, 4, 0) },
|
||||
['L'] = new[] { P(0, 6, 0, 0, 4, 0) },
|
||||
['M'] = new[] { P(0, 0, 0, 6, 2, 3, 4, 6, 4, 0) },
|
||||
['N'] = new[] { P(0, 0, 0, 6, 4, 0, 4, 6) },
|
||||
['O'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0) },
|
||||
['P'] = new[] { P(0, 0, 0, 6, 4, 6, 4, 3, 0, 3) },
|
||||
['Q'] = new[] { P(0, 0, 4, 0, 4, 6, 0, 6, 0, 0), P(2, 2, 4, -1) },
|
||||
['R'] = new[] { P(0, 0, 0, 6, 4, 6, 4, 3, 0, 3, 4, 0) },
|
||||
['S'] = new[] { P(4, 6, 0, 6, 0, 3, 4, 3, 4, 0, 0, 0) },
|
||||
['T'] = new[] { P(0, 6, 4, 6), P(2, 6, 2, 0) },
|
||||
['U'] = new[] { P(0, 6, 0, 0, 4, 0, 4, 6) },
|
||||
['V'] = new[] { P(0, 6, 2, 0, 4, 6) },
|
||||
['W'] = new[] { P(0, 6, 1, 0, 2, 3, 3, 0, 4, 6) },
|
||||
['X'] = new[] { P(0, 0, 4, 6), P(0, 6, 4, 0) },
|
||||
['Y'] = new[] { P(0, 6, 2, 3, 4, 6), P(2, 3, 2, 0) },
|
||||
['Z'] = new[] { P(0, 6, 4, 6, 0, 0, 4, 0) },
|
||||
['-'] = new[] { P(1, 3, 3, 3) },
|
||||
['+'] = new[] { P(1, 3, 3, 3), P(2, 2, 2, 4) },
|
||||
['.'] = new[] { P(2, 0, 2, 0.4f) },
|
||||
[','] = new[] { P(2, 0.6f, 1.5f, -0.6f) },
|
||||
[':'] = new[] { P(2, 1, 2, 1.4f), P(2, 4, 2, 4.4f) },
|
||||
['\''] = new[] { P(2, 6, 2, 4.6f) },
|
||||
['/'] = new[] { P(0, 0, 4, 6) },
|
||||
['#'] = new[] { P(1, 0, 1, 6), P(3, 0, 3, 6), P(0, 2, 4, 2), P(0, 4, 4, 4) },
|
||||
['('] = new[] { P(3, 6, 2, 5, 2, 1, 3, 0) },
|
||||
[')'] = new[] { P(1, 6, 2, 5, 2, 1, 1, 0) },
|
||||
['?'] = new[] { P(0, 5, 1, 6, 3, 6, 4, 5, 4, 4, 2, 3, 2, 2), P(2, 0, 2, 0.4f) },
|
||||
['!'] = new[] { P(2, 6, 2, 2), P(2, 0, 2, 0.4f) },
|
||||
['_'] = new[] { P(0, 0, 4, 0) },
|
||||
};
|
||||
}
|
||||
186
Plugins/Shared/RynthInstallPaths.cs
Normal file
186
Plugins/Shared/RynthInstallPaths.cs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
// ============================================================================
|
||||
// RynthInstallPaths.cs - where RynthCore and RynthSuite are installed.
|
||||
//
|
||||
// ONE FILE, TWO COPIES: RynthCore src\Shared\RynthInstallPaths.cs (engine,
|
||||
// launcher, injector, loader, StatusAgent) and RynthSuite
|
||||
// Plugins\Shared\RynthInstallPaths.cs (plugins, Loot Editor). Keep them
|
||||
// byte-identical; RynthSuite's RynthAi host tests compare the two when the
|
||||
// RynthCore sibling is checked out.
|
||||
//
|
||||
// READ ONLY. This only answers "which folder"; it never writes or deletes a
|
||||
// setting, and nothing here may be used to pick a DLL or EXE to load or run.
|
||||
//
|
||||
// Order, per folder (first usable answer wins):
|
||||
// 1. environment variable RYNTHCORE_DIR / RYNTHSUITE_DIR (dev setups)
|
||||
// 2. HKCU\Software\Rynth CoreDir / SuiteDir (per-user install)
|
||||
// 3. HKLM\Software\Rynth CoreDir / SuiteDir, 32-bit view (all-users install)
|
||||
// 4. C:\Games\RynthCore / C:\Games\RynthSuite (today's layout)
|
||||
// A value counts only if it is an absolute path; anything else is skipped.
|
||||
// With nothing set the result is exactly the old hard-coded folder.
|
||||
//
|
||||
// Idea from Silentkelpie (rynth PR #1); re-implemented here.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Install;
|
||||
|
||||
/// <summary>Where <see cref="RynthInstallPaths"/> reads settings from. Tests pass a fake.</summary>
|
||||
internal interface IInstallSettingSource
|
||||
{
|
||||
/// <summary>The process environment variable, or null.</summary>
|
||||
string? EnvironmentVariable(string name);
|
||||
|
||||
/// <summary>A string value under HKCU\Software\Rynth, or null.</summary>
|
||||
string? CurrentUser(string valueName);
|
||||
|
||||
/// <summary>A string value under HKLM\Software\Rynth (32-bit registry view), or null.</summary>
|
||||
string? LocalMachine(string valueName);
|
||||
}
|
||||
|
||||
internal static class RynthInstallPaths
|
||||
{
|
||||
/// <summary>RynthCore folder when nothing is set (launcher, Runtime\, Logs\, NavData\, AcClient\).</summary>
|
||||
public const string DefaultCoreDir = @"C:\Games\RynthCore";
|
||||
|
||||
/// <summary>RynthSuite folder when nothing is set (plugins and their data, e.g. RynthAi\).</summary>
|
||||
public const string DefaultSuiteDir = @"C:\Games\RynthSuite";
|
||||
|
||||
public const string CoreEnvironmentVariable = "RYNTHCORE_DIR";
|
||||
public const string SuiteEnvironmentVariable = "RYNTHSUITE_DIR";
|
||||
|
||||
/// <summary>Key under HKCU / HKLM.</summary>
|
||||
public const string RegistryKey = @"Software\Rynth";
|
||||
public const string CoreValueName = "CoreDir";
|
||||
public const string SuiteValueName = "SuiteDir";
|
||||
|
||||
private static string? _coreDir;
|
||||
private static string? _suiteDir;
|
||||
|
||||
/// <summary>The RynthCore install folder. Resolved once per process.</summary>
|
||||
public static string CoreDir =>
|
||||
_coreDir ??= Resolve(CoreEnvironmentVariable, CoreValueName, DefaultCoreDir, SystemInstallSettings.Instance);
|
||||
|
||||
/// <summary>The RynthSuite install folder. Resolved once per process.</summary>
|
||||
public static string SuiteDir =>
|
||||
_suiteDir ??= Resolve(SuiteEnvironmentVariable, SuiteValueName, DefaultSuiteDir, SystemInstallSettings.Instance);
|
||||
|
||||
/// <summary><CoreDir>\Logs - the unified log folder.</summary>
|
||||
public static string CoreLogsDir => Path.Combine(CoreDir, "Logs");
|
||||
|
||||
/// <summary><SuiteDir>\RynthAi - RynthAi's home and data root.</summary>
|
||||
public static string RynthAiDir => Path.Combine(SuiteDir, "RynthAi");
|
||||
|
||||
/// <summary>
|
||||
/// The first usable folder from <paramref name="source"/>: environment, then HKCU,
|
||||
/// then HKLM, else <paramref name="fallback"/> exactly as given. Never throws.
|
||||
/// </summary>
|
||||
internal static string Resolve(string environmentVariable, string valueName, string fallback, IInstallSettingSource source)
|
||||
{
|
||||
string? found = Normalize(Ask(() => source.EnvironmentVariable(environmentVariable)))
|
||||
?? Normalize(Ask(() => source.CurrentUser(valueName)))
|
||||
?? Normalize(Ask(() => source.LocalMachine(valueName)));
|
||||
return found ?? fallback;
|
||||
}
|
||||
|
||||
private static readonly char[] BadNameChars = { '*', '?', '<', '>', '"', '|' };
|
||||
|
||||
private static string? Ask(Func<string?> read)
|
||||
{
|
||||
try { return read(); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An absolute folder path, tidied (whitespace and surrounding quotes trimmed,
|
||||
/// trailing separators dropped except on a drive root); null when the value is
|
||||
/// empty, relative or not a valid path.
|
||||
/// </summary>
|
||||
internal static string? Normalize(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return null;
|
||||
string path = value.Trim().Trim('"').Trim();
|
||||
if (path.Length == 0) return null;
|
||||
// .NET accepts some names Windows folders can't have; refuse them here.
|
||||
if (path.IndexOfAny(Path.GetInvalidPathChars()) >= 0 || path.IndexOfAny(BadNameChars) >= 0) return null;
|
||||
if (path.Length > 2 && path.IndexOf(':', 2) >= 0) return null; // a colon only after the drive letter
|
||||
try
|
||||
{
|
||||
if (!Path.IsPathFullyQualified(path)) return null;
|
||||
string full = Path.GetFullPath(path);
|
||||
string root = Path.GetPathRoot(full) ?? string.Empty;
|
||||
string trimmed = full.TrimEnd('\\', '/');
|
||||
return trimmed.Length < root.Length ? root : trimmed;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The real environment and registry (read only, advapi32 directly: NativeAOT and trim safe).</summary>
|
||||
internal sealed class SystemInstallSettings : IInstallSettingSource
|
||||
{
|
||||
public static readonly SystemInstallSettings Instance = new();
|
||||
|
||||
private SystemInstallSettings() { }
|
||||
|
||||
public string? EnvironmentVariable(string name) => Environment.GetEnvironmentVariable(name);
|
||||
|
||||
public string? CurrentUser(string valueName) => ReadString(HKEY_CURRENT_USER, valueName, 0);
|
||||
|
||||
public string? LocalMachine(string valueName) => ReadString(HKEY_LOCAL_MACHINE, valueName, RRF_SUBKEY_WOW6432KEY);
|
||||
|
||||
private static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001));
|
||||
private static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002));
|
||||
private const uint RRF_RT_REG_SZ = 0x00000002;
|
||||
private const uint RRF_RT_REG_EXPAND_SZ = 0x00000004;
|
||||
private const uint RRF_SUBKEY_WOW6432KEY = 0x00020000;
|
||||
private const int ERROR_SUCCESS = 0;
|
||||
private const int MaxValueBytes = 64 * 1024;
|
||||
|
||||
// Every argument is a pointer or an integer, so no marshalling stub is needed.
|
||||
[DllImport("advapi32.dll", ExactSpelling = true)]
|
||||
private static extern int RegGetValueW(IntPtr hkey, IntPtr subKey, IntPtr valueName, uint flags,
|
||||
IntPtr type, IntPtr data, IntPtr dataBytes);
|
||||
|
||||
private static string? ReadString(IntPtr root, string valueName, uint viewFlag)
|
||||
{
|
||||
IntPtr subKey = IntPtr.Zero, name = IntPtr.Zero, size = IntPtr.Zero, data = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
subKey = Marshal.StringToHGlobalUni(RynthInstallPaths.RegistryKey);
|
||||
name = Marshal.StringToHGlobalUni(valueName);
|
||||
size = Marshal.AllocHGlobal(sizeof(uint));
|
||||
uint flags = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | viewFlag;
|
||||
|
||||
Marshal.WriteInt32(size, 0);
|
||||
if (RegGetValueW(root, subKey, name, flags, IntPtr.Zero, IntPtr.Zero, size) != ERROR_SUCCESS)
|
||||
return null;
|
||||
int bytes = Marshal.ReadInt32(size);
|
||||
if (bytes < 2 || bytes > MaxValueBytes) return null;
|
||||
|
||||
data = Marshal.AllocHGlobal(bytes + 2);
|
||||
Marshal.WriteInt32(size, bytes);
|
||||
if (RegGetValueW(root, subKey, name, flags, IntPtr.Zero, data, size) != ERROR_SUCCESS)
|
||||
return null;
|
||||
int written = Math.Min(Marshal.ReadInt32(size), bytes);
|
||||
Marshal.WriteInt16(data, written - (written % 2), 0); // terminate even if the value wasn't
|
||||
return Marshal.PtrToStringUni(data);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null; // no advapi32, access denied, ... -> the next source / the default
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (data != IntPtr.Zero) Marshal.FreeHGlobal(data);
|
||||
if (size != IntPtr.Zero) Marshal.FreeHGlobal(size);
|
||||
if (name != IntPtr.Zero) Marshal.FreeHGlobal(name);
|
||||
if (subKey != IntPtr.Zero) Marshal.FreeHGlobal(subKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -80,6 +80,10 @@ internal static class UseAudit
|
|||
_windowStart = long.MinValue;
|
||||
_windowLines = 0;
|
||||
_windowDropped = 0;
|
||||
_worldUseId = 0;
|
||||
_worldUseSentMs = 0;
|
||||
_worldUseSeqAtSend = 0;
|
||||
AfterSend = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -93,7 +97,95 @@ internal static class UseAudit
|
|||
return false;
|
||||
}
|
||||
Write(host, objectId, subsystem, $"0x{objectId:X8} {what} macro={MacroText} {KindText(kind)} - {why}", force: false);
|
||||
return host.UseObject(objectId);
|
||||
int seqBefore = 0;
|
||||
bool track = TrackWorldUses && doorOrCorpse;
|
||||
var after = AfterSend;
|
||||
if (track || after != null)
|
||||
{
|
||||
try { seqBefore = host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { }
|
||||
}
|
||||
bool sent = host.UseObject(objectId);
|
||||
if (track && sent)
|
||||
MarkWorldUse(objectId, seqBefore);
|
||||
if (sent && after != null)
|
||||
{
|
||||
try { after(host, new SentUse(objectId, 0, subsystem, what, doorOrCorpse, seqBefore, kind)); } catch { }
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
/// <summary>What went out (for <see cref="AfterSend"/>).</summary>
|
||||
internal readonly record struct SentUse(uint ObjectId, uint TargetId, string Subsystem, string What,
|
||||
bool DoorOrCorpse, int UseDoneSeqBefore, UseKind Kind);
|
||||
|
||||
/// <summary>
|
||||
/// Called after every use / use-on this plugin sent (RynthAi records it as the server action it
|
||||
/// waits on, Plugins/Shared/ActionPacer.cs). Null in plugins that don't pace. Cleared by Reset.
|
||||
/// </summary>
|
||||
public static Action<RynthCoreHost, SentUse>? AfterSend;
|
||||
|
||||
// ── A door or corpse use the server hasn't answered yet (2026-10-06) ──────────
|
||||
// The server walks/turns the character to a used door or corpse, and any movement packet
|
||||
// from the client cancels that (ACE: a MoveToState stops the move-to chain, and a combat
|
||||
// mode change cancels the move-to too). MoveAudit holds the plugin's own movement while
|
||||
// one is in flight. Opt-in per plugin (TrackWorldUses); off = nothing changes.
|
||||
|
||||
/// <summary>Opt-in: remember door/corpse uses so MoveAudit can hold movement until the server answers.</summary>
|
||||
public static volatile bool TrackWorldUses;
|
||||
|
||||
/// <summary>Longest a use counts as in flight when the server doesn't answer (a long walk to it).</summary>
|
||||
public const long WorldUseInFlightMaxMs = 1500;
|
||||
|
||||
private static uint _worldUseId;
|
||||
private static long _worldUseSentMs;
|
||||
private static int _worldUseSeqAtSend;
|
||||
|
||||
/// <summary>Records a door/corpse use that went out (internal for the tests).</summary>
|
||||
internal static void MarkWorldUse(uint objectId, int useDoneSeqBefore)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_worldUseId = objectId;
|
||||
_worldUseSentMs = NowMs();
|
||||
_worldUseSeqAtSend = useDoneSeqBefore;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True while the last door/corpse use is waiting for the server: sent less than
|
||||
/// WorldUseInFlightMaxMs ago and no UseDone has arrived since (when the engine counts them;
|
||||
/// without the count, the time alone). Always false unless TrackWorldUses.
|
||||
/// </summary>
|
||||
public static bool WorldUseInFlight(RynthCoreHost host, out uint objectId)
|
||||
{
|
||||
objectId = 0;
|
||||
if (!TrackWorldUses) return false;
|
||||
long sentMs; int seqAtSend; uint id;
|
||||
lock (Gate)
|
||||
{
|
||||
sentMs = _worldUseSentMs;
|
||||
seqAtSend = _worldUseSeqAtSend;
|
||||
id = _worldUseId;
|
||||
}
|
||||
if (sentMs == 0 || NowMs() - sentMs >= WorldUseInFlightMaxMs) return false;
|
||||
try
|
||||
{
|
||||
if (host.HasUseDoneSeq && host.GetUseDoneSeq() != seqAtSend) return false;
|
||||
}
|
||||
catch { }
|
||||
objectId = id;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Forget the in-flight use (Reset, tests).</summary>
|
||||
internal static void ClearWorldUse()
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
_worldUseId = 0;
|
||||
_worldUseSentMs = 0;
|
||||
_worldUseSeqAtSend = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>UseObjectOn (item on a target) with a log line and the same guard on the target.</summary>
|
||||
|
|
@ -107,7 +199,18 @@ internal static class UseAudit
|
|||
return false;
|
||||
}
|
||||
Write(host, targetId, subsystem, $"0x{sourceId:X8} {src} on 0x{targetId:X8} {tgt} macro={MacroText} {KindText(kind)} - {why}", force: false);
|
||||
return host.UseObjectOn(sourceId, targetId);
|
||||
var after = AfterSend;
|
||||
int seqBefore = 0;
|
||||
if (after != null)
|
||||
{
|
||||
try { seqBefore = host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { }
|
||||
}
|
||||
bool sent = host.UseObjectOn(sourceId, targetId);
|
||||
if (sent && after != null)
|
||||
{
|
||||
try { after(host, new SentUse(sourceId, targetId, subsystem, $"{src} on {tgt}", doorOrCorpse, seqBefore, kind)); } catch { }
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
private static string MacroText => MacroRunning switch { true => "on", false => "off", null => "n/a" };
|
||||
|
|
|
|||
|
|
@ -14,10 +14,10 @@ namespace RynthCore.LootEditor;
|
|||
|
||||
public class MainViewModel : INotifyPropertyChanged
|
||||
{
|
||||
private const string DefaultFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||
private static readonly string DefaultFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
|
||||
// RynthAi's AutoVendor reads <Vendor Name>.utl / default.utl from here (and from
|
||||
// AutoVendor folders per server and per character, which IsAutoVendorPath also covers).
|
||||
private const string AutoVendorFolder = @"C:\Games\RynthSuite\RynthAi\AutoVendor";
|
||||
private static readonly string AutoVendorFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "AutoVendor");
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
|
||||
|
|
|
|||
|
|
@ -22,4 +22,9 @@
|
|||
<ProjectReference Include="..\..\Shared\RynthCore.LootSdk\RynthCore.LootSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -5,5 +5,6 @@ namespace RynthCore.MonsterEditor;
|
|||
|
||||
[JsonSerializable(typeof(List<MonsterRule>))]
|
||||
[JsonSerializable(typeof(EditorSettings))]
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true)]
|
||||
// Case-insensitive like the plugin's RynthAiJsonContext, which reads the same files.
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, IncludeFields = true, PropertyNameCaseInsensitive = true)]
|
||||
internal partial class EditorJsonContext : JsonSerializerContext { }
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
xmlns:local="clr-namespace:RynthCore.MonsterEditor"
|
||||
x:Class="RynthCore.MonsterEditor.MainWindow"
|
||||
Title="RynthAi — Monster Rules Editor"
|
||||
Width="1060" Height="520" MinWidth="800" MinHeight="300">
|
||||
Width="1300" Height="520" MinWidth="800" MinHeight="300">
|
||||
|
||||
<DockPanel LastChildFill="True">
|
||||
|
||||
|
|
@ -138,6 +138,28 @@
|
|||
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<!-- Category (the plugin's rule group label) -->
|
||||
<DataGridTemplateColumn Header="Category" Width="90" MinWidth="60">
|
||||
<DataGridTemplateColumn.CellTemplate><DataTemplate>
|
||||
<TextBlock Text="{Binding Category}" Padding="3,1" VerticalAlignment="Center"/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate><DataTemplate>
|
||||
<TextBox Text="{Binding Category, Mode=TwoWay}" Padding="3,1"/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<!-- Match expression (empty = match by name only) -->
|
||||
<DataGridTemplateColumn Header="Match" Width="150" MinWidth="80">
|
||||
<DataGridTemplateColumn.CellTemplate><DataTemplate>
|
||||
<TextBlock Text="{Binding MatchExpression}" Padding="3,1" VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
ToolTip.Tip="Match expression: when set, the rule matches when it is true (and the name, if any, is in the target's name). Empty = by name only."/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate><DataTemplate>
|
||||
<TextBox Text="{Binding MatchExpression, Mode=TwoWay}" Padding="3,1"/>
|
||||
</DataTemplate></DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<!-- Priority -->
|
||||
<DataGridTemplateColumn Header="P" Width="32" MinWidth="30">
|
||||
<DataGridTemplateColumn.CellTemplate><DataTemplate>
|
||||
|
|
|
|||
|
|
@ -33,6 +33,8 @@ public partial class MainWindow : Window
|
|||
private string _charFolder = string.Empty;
|
||||
private string _monstersPath = string.Empty;
|
||||
private bool _initialized;
|
||||
// Set when the monsters file couldn't be read: saving would replace it with what's on screen.
|
||||
private bool _loadFailed;
|
||||
|
||||
public MainWindow()
|
||||
{
|
||||
|
|
@ -51,7 +53,7 @@ public partial class MainWindow : Window
|
|||
|
||||
string[] args = Environment.GetCommandLineArgs();
|
||||
if (args.Length > 1)
|
||||
OpenCharFolder(args[1].Trim('"'));
|
||||
Open(args[1].Trim('"'));
|
||||
else
|
||||
await PromptOpenFileAsync();
|
||||
}
|
||||
|
|
@ -65,11 +67,11 @@ public partial class MainWindow : Window
|
|||
|
||||
var pick = await sp.OpenFilePickerAsync(new FilePickerOpenOptions
|
||||
{
|
||||
Title = "Open monsters.json",
|
||||
Title = "Open a monster rules file (RynthAi > MonsterProfiles > character.json)",
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter = new[]
|
||||
{
|
||||
new FilePickerFileType("Monster Rules") { Patterns = new[] { "monsters.json" } },
|
||||
new FilePickerFileType("Monster Rules") { Patterns = new[] { "*.json" } },
|
||||
new FilePickerFileType("All Files") { Patterns = new[] { "*" } },
|
||||
}
|
||||
});
|
||||
|
|
@ -83,14 +85,21 @@ public partial class MainWindow : Window
|
|||
|
||||
string? path = file.TryGetLocalPath();
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
OpenCharFolder(Path.GetDirectoryName(path)!);
|
||||
Open(path);
|
||||
}
|
||||
|
||||
private void OpenCharFolder(string charFolder)
|
||||
/// <summary>Opens a monsters file, or a character's settings folder (what the plugin passes):
|
||||
/// the folder maps to the file the plugin reads, MonsterProfiles\(server)\(character).json
|
||||
/// (MonsterRulesFile.ResolveRulesPath). Before 2026-10-05 the editor always used
|
||||
/// monsters.json in that folder, which the plugin now moves to MonsterProfiles at load, so the
|
||||
/// editor opened empty and its saves were never read once the plugin's own file existed.</summary>
|
||||
private void Open(string pathOrFolder)
|
||||
{
|
||||
_charFolder = charFolder;
|
||||
_monstersPath = Path.Combine(charFolder, "monsters.json");
|
||||
Title = $"RynthAi — Monster Rules — {Path.GetFileName(charFolder)}";
|
||||
_monstersPath = MonsterRulesFile.ResolveRulesPath(pathOrFolder);
|
||||
_charFolder = Directory.Exists(pathOrFolder) ? pathOrFolder : MonsterRulesFile.CharFolderForRulesPath(_monstersPath);
|
||||
string who = Path.GetFileNameWithoutExtension(_monstersPath);
|
||||
if (who.Equals("monsters", StringComparison.OrdinalIgnoreCase)) who = Path.GetFileName(_charFolder);
|
||||
Title = $"RynthAi — Monster Rules — {who}";
|
||||
|
||||
LoadWeaponOptions();
|
||||
LoadRules();
|
||||
|
|
@ -128,17 +137,17 @@ public partial class MainWindow : Window
|
|||
{
|
||||
foreach (var r in Rules) r.PropertyChanged -= Rule_Changed;
|
||||
Rules.Clear();
|
||||
_loadFailed = false;
|
||||
|
||||
if (File.Exists(_monstersPath))
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
string json = File.ReadAllText(_monstersPath);
|
||||
var rules = JsonSerializer.Deserialize(json, EditorJsonContext.Default.ListMonsterRule);
|
||||
if (rules != null)
|
||||
foreach (var r in rules) AddRule(r);
|
||||
}
|
||||
catch (Exception ex) { SetStatus($"Load error: {ex.Message}", error: true); return; }
|
||||
foreach (var r in MonsterRulesFile.Load(_monstersPath)) AddRule(r);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_loadFailed = true;
|
||||
SetStatus($"Load error: {ex.Message} - not saving over {_monstersPath}; fix the file and reopen it.", error: true);
|
||||
return;
|
||||
}
|
||||
|
||||
EnsureDefault();
|
||||
|
|
@ -187,12 +196,10 @@ public partial class MainWindow : Window
|
|||
|
||||
private void Save()
|
||||
{
|
||||
if (string.IsNullOrEmpty(_monstersPath)) return;
|
||||
if (string.IsNullOrEmpty(_monstersPath) || _loadFailed) return;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_charFolder);
|
||||
string json = JsonSerializer.Serialize(new List<MonsterRule>(Rules), EditorJsonContext.Default.ListMonsterRule);
|
||||
File.WriteAllText(_monstersPath, json);
|
||||
MonsterRulesFile.Save(_monstersPath, Rules);
|
||||
SetStatus($"Saved {Rules.Count} rule(s) — {DateTime.Now:HH:mm:ss}");
|
||||
}
|
||||
catch (Exception ex) { SetStatus($"Save error: {ex.Message}", error: true); }
|
||||
|
|
|
|||
|
|
@ -1,13 +1,19 @@
|
|||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace RynthCore.MonsterEditor;
|
||||
|
||||
/// <summary>The editor's copy of RynthAi's MonsterRule (Plugins/RynthCore.Plugin.RynthAi/LegacyUi/
|
||||
/// LegacyUiSettings.cs), read from and saved to the same monsters file. A field the plugin has and
|
||||
/// this class doesn't still survives a save, through <see cref="ExtraFields"/>.</summary>
|
||||
public class MonsterRule : INotifyPropertyChanged
|
||||
{
|
||||
private string _name = "New Monster";
|
||||
private string _category = "";
|
||||
private string _matchExpression = "";
|
||||
private int _priority = 1;
|
||||
private string _damageType = "Auto";
|
||||
private int _weaponId;
|
||||
|
|
@ -18,6 +24,14 @@ public class MonsterRule : INotifyPropertyChanged
|
|||
private string _petDamage = "PAuto";
|
||||
|
||||
public string Name { get => _name; set { _name = value; OnPropertyChanged(); } }
|
||||
/// <summary>The plugin's rule group label. Kept and editable here (before 2026-10-05 an
|
||||
/// editor save dropped it).</summary>
|
||||
public string Category { get => _category; set { _category = value ?? ""; OnPropertyChanged(); } }
|
||||
/// <summary>The plugin's match expression (CombatManager.GetRuleForTarget): when set, the
|
||||
/// rule matches when the expression is true (and the name, if any, is in the target's).
|
||||
/// Empty = match by name only. Kept and editable here (before 2026-10-05 an editor save
|
||||
/// dropped it, so expression rules fell back to name-only).</summary>
|
||||
public string MatchExpression { get => _matchExpression; set { _matchExpression = value ?? ""; OnPropertyChanged(); } }
|
||||
public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(); } }
|
||||
public string DamageType { get => _damageType; set { _damageType = value; OnPropertyChanged(); } }
|
||||
public int WeaponId { get => _weaponId; set { _weaponId = value; OnPropertyChanged(); } }
|
||||
|
|
@ -36,6 +50,11 @@ public class MonsterRule : INotifyPropertyChanged
|
|||
public int OffhandId { get => _offhandId; set { _offhandId = value; OnPropertyChanged(); } }
|
||||
public string PetDamage { get => _petDamage; set { _petDamage = value; OnPropertyChanged(); } }
|
||||
|
||||
/// <summary>Every field in the file this class doesn't know (e.g. the plugin's CustomDebuffs,
|
||||
/// or one added later), written back unchanged.</summary>
|
||||
[JsonExtensionData]
|
||||
public Dictionary<string, JsonElement>? ExtraFields { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public bool IsDefault => string.Equals(_name, "Default", System.StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
|
|
|
|||
99
Tools/RynthCore.MonsterEditor/MonsterRulesFile.cs
Normal file
99
Tools/RynthCore.MonsterEditor/MonsterRulesFile.cs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.MonsterEditor;
|
||||
|
||||
/// <summary>
|
||||
/// Reading and writing a monsters file (a JSON array of MonsterRule, the format RynthAi's
|
||||
/// LegacyDashboardRenderer reads and writes), and finding the file the plugin uses. No UI:
|
||||
/// Tools/RynthCore.RynthAiHostTests compiles this file in and round-trips a file through it and
|
||||
/// the plugin's own serializer.
|
||||
/// </summary>
|
||||
public static class MonsterRulesFile
|
||||
{
|
||||
private const string SettingsProfilesDir = "SettingsProfiles";
|
||||
private const string MonsterProfilesDir = "MonsterProfiles";
|
||||
// RynthAi's LegacyServerFolder: its monsters live straight in MonsterProfiles\.
|
||||
private const string LegacyServerFolder = "ACEmulator";
|
||||
private const string LegacyFileName = "monsters.json";
|
||||
|
||||
/// <summary>The rules in <paramref name="path"/>; empty when the file doesn't exist.
|
||||
/// Throws on a file that isn't a JSON array of rules (the caller shows the error and
|
||||
/// doesn't save over it).</summary>
|
||||
public static List<MonsterRule> Load(string path)
|
||||
{
|
||||
if (!File.Exists(path)) return new List<MonsterRule>();
|
||||
string json = File.ReadAllText(path);
|
||||
return JsonSerializer.Deserialize(json, EditorJsonContext.Default.ListMonsterRule) ?? new List<MonsterRule>();
|
||||
}
|
||||
|
||||
/// <summary>Writes <paramref name="rules"/> in place (File.WriteAllText, as before: the
|
||||
/// plugin's FileSystemWatcher reloads on a LastWrite change).</summary>
|
||||
public static void Save(string path, IEnumerable<MonsterRule> rules)
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(new List<MonsterRule>(rules), EditorJsonContext.Default.ListMonsterRule));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The monsters file for what the editor was given: a .json file is edited as is. A
|
||||
/// character's settings folder (RynthAi\SettingsProfiles\<server>\<character>, what the
|
||||
/// plugin passes) maps to the plugin's file, RynthAi\MonsterProfiles\<server>\<character>.json
|
||||
/// (MonsterProfiles\<character>.json for the ACEmulator folder). The old
|
||||
/// <folder>\monsters.json is used only when that file doesn't exist and the old one does
|
||||
/// (the plugin moves it across at its next load).
|
||||
/// </summary>
|
||||
public static string ResolveRulesPath(string pathOrFolder)
|
||||
{
|
||||
string p = pathOrFolder.Trim().Trim('"').TrimEnd('\\', '/');
|
||||
if (File.Exists(p) || p.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
return p;
|
||||
|
||||
string legacy = Path.Combine(p, LegacyFileName);
|
||||
string? current = PluginRulesPathForCharFolder(p);
|
||||
if (current == null) return legacy;
|
||||
if (File.Exists(current)) return current;
|
||||
return File.Exists(legacy) ? legacy : current;
|
||||
}
|
||||
|
||||
/// <summary>RynthAi's MonsterProfiles file for a SettingsProfiles character folder; null when
|
||||
/// the folder isn't laid out that way.</summary>
|
||||
public static string? PluginRulesPathForCharFolder(string charFolder)
|
||||
{
|
||||
var character = new DirectoryInfo(charFolder.TrimEnd('\\', '/'));
|
||||
DirectoryInfo? server = character.Parent;
|
||||
DirectoryInfo? profiles = server?.Parent;
|
||||
DirectoryInfo? root = profiles?.Parent;
|
||||
if (server == null || profiles == null || root == null) return null;
|
||||
if (!profiles.Name.Equals(SettingsProfilesDir, StringComparison.OrdinalIgnoreCase)) return null;
|
||||
|
||||
string monsters = Path.Combine(root.FullName, MonsterProfilesDir);
|
||||
return server.Name.Equals(LegacyServerFolder, StringComparison.OrdinalIgnoreCase)
|
||||
? Path.Combine(monsters, character.Name + ".json")
|
||||
: Path.Combine(monsters, server.Name, character.Name + ".json");
|
||||
}
|
||||
|
||||
/// <summary>The character's settings folder (where active_profile.txt and the profile with
|
||||
/// the weapon list live) for a monsters file: the file's own folder for an old
|
||||
/// monsters.json, the matching SettingsProfiles folder for a MonsterProfiles file, else the
|
||||
/// file's own folder.</summary>
|
||||
public static string CharFolderForRulesPath(string rulesPath)
|
||||
{
|
||||
var file = new FileInfo(rulesPath);
|
||||
string folder = file.DirectoryName ?? "";
|
||||
if (file.Name.Equals(LegacyFileName, StringComparison.OrdinalIgnoreCase))
|
||||
return folder;
|
||||
|
||||
string character = Path.GetFileNameWithoutExtension(file.Name);
|
||||
DirectoryInfo? dir = file.Directory;
|
||||
if (dir == null) return folder;
|
||||
if (dir.Name.Equals(MonsterProfilesDir, StringComparison.OrdinalIgnoreCase) && dir.Parent != null)
|
||||
return Path.Combine(dir.Parent.FullName, SettingsProfilesDir, LegacyServerFolder, character);
|
||||
if (dir.Parent is { } monsters && monsters.Name.Equals(MonsterProfilesDir, StringComparison.OrdinalIgnoreCase) && monsters.Parent != null)
|
||||
return Path.Combine(monsters.Parent.FullName, SettingsProfilesDir, dir.Name, character);
|
||||
return folder;
|
||||
}
|
||||
}
|
||||
|
|
@ -48,6 +48,9 @@ internal static unsafe class FakeHost
|
|||
/// <summary>Item id -> container id. When it has entries at Create() time the host also gets
|
||||
/// GetObjectOwnershipInfo (opt-in, so tests written without it see no ownership, as before).</summary>
|
||||
public static readonly Dictionary<uint, uint> Containers = new();
|
||||
/// <summary>Item id -> the creature wielding it (GetObjectOwnershipInfo's wielder). Entries here
|
||||
/// also install GetObjectOwnershipInfo; an id in neither map reads as unknown ownership.</summary>
|
||||
public static readonly Dictionary<uint, uint> Wielders = new();
|
||||
/// <summary>Object id -> PublicWeenieDesc bitfield (0x2000 corpse, 0x8 player, ...). When it has
|
||||
/// entries at Create() time the host also gets GetObjectBitfield (opt-in, as Containers).</summary>
|
||||
public static readonly Dictionary<uint, uint> Bitfields = new();
|
||||
|
|
@ -118,6 +121,9 @@ internal static unsafe class FakeHost
|
|||
public static int CastBusy;
|
||||
public static int VTankSeq;
|
||||
public static int CombatModeValue = 1;
|
||||
/// <summary>Opt-in (set before Create): ChangeCombatMode, recorded in <see cref="CombatModeRequests"/>.</summary>
|
||||
public static bool CombatModeCalls;
|
||||
public static readonly List<int> CombatModeRequests = new();
|
||||
/// <summary>Opt-in (set before Create): WieldItem (a wield into a named slot, API v70+). The
|
||||
/// host then reports API version 73, so only tests that ask for it see the newer calls.</summary>
|
||||
public static bool WieldCalls;
|
||||
|
|
@ -149,23 +155,40 @@ internal static unsafe class FakeHost
|
|||
public static uint GroundContainer;
|
||||
/// <summary>The item selected in the game (GetSelectedItemId); 0 = none.</summary>
|
||||
public static uint SelectedItem;
|
||||
/// <summary>Opt-in (set before Create): UseObjectOn (an item used on another, e.g. a spirit on a
|
||||
/// pet essence); every call lands in <see cref="UsesOn"/>.</summary>
|
||||
public static bool UseOnCalls;
|
||||
/// <summary>Every UseObjectOn (source, target), in order (opt-in with <see cref="UseOnCalls"/>).</summary>
|
||||
public static readonly List<(uint Source, uint Target)> UsesOn = new();
|
||||
/// <summary>Opt-in: install SendPluginCommand (the engine's plugin-command broker, API v64).</summary>
|
||||
public static bool PluginCommandCalls;
|
||||
/// <summary>What SendPluginCommand answers: true = delivered (the target plugin is loaded).</summary>
|
||||
public static bool PluginCommandDelivered = true;
|
||||
/// <summary>Every SendPluginCommand (plugin, action, value), in order.</summary>
|
||||
public static readonly List<(string Plugin, string Action, string Value)> PluginCommands = new();
|
||||
/// <summary>Opt-in (set before Create): ForceResetBusyCount (counted in <see cref="ForceResets"/>)
|
||||
/// and GetBusyState (answering <see cref="BusyStateValue"/>).</summary>
|
||||
public static bool BusyCalls;
|
||||
public static int ForceResets;
|
||||
public static int BusyStateValue;
|
||||
|
||||
// ANSI strings handed back to tested code stay alive for the whole run.
|
||||
private static readonly Dictionary<string, IntPtr> _ansi = new();
|
||||
|
||||
/// <summary>Opt-in: install the Nav3D calls (clear, ring, line, triangle) and record them.</summary>
|
||||
public static bool Nav3DCalls;
|
||||
public static readonly List<(float X, float Y, float Z, float Radius, uint Color)> Nav3DRings = new();
|
||||
public static readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float Thick, uint Color)> Nav3DLines = new();
|
||||
public static readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, float X3, float Y3, float Z3, uint Color)> Nav3DTriangles = new();
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
Nav3DCalls = false; Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear();
|
||||
Names.Clear(); Positions.Clear(); ItemTypes.Clear();
|
||||
Ints.Clear(); Doubles.Clear(); Quads.Clear(); Bools.Clear(); Strings.Clear();
|
||||
Skills.Clear(); SkillLevels.Clear(); Attributes.Clear();
|
||||
SpellIds.Clear(); DataIds.Clear(); Palettes.Clear(); KnownSpells.Clear(); NotAttackable.Clear(); Enchantments.Clear();
|
||||
Containers.Clear(); Bitfields.Clear();
|
||||
Containers.Clear(); Wielders.Clear(); Bitfields.Clear();
|
||||
ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true;
|
||||
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
|
||||
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
|
||||
|
|
@ -179,7 +202,10 @@ internal static unsafe class FakeHost
|
|||
RefuseSalvageAdd.Clear(); OnSalvageExecute = null; Wielded.Clear(); _panelItems.Clear();
|
||||
CloseContainerCalls = false; Closes.Clear(); GroundContainer = 0;
|
||||
SelectedItem = 0;
|
||||
UseOnCalls = false; UsesOn.Clear();
|
||||
PluginCommandCalls = false; PluginCommandDelivered = true; PluginCommands.Clear();
|
||||
CombatModeCalls = false; CombatModeRequests.Clear();
|
||||
BusyCalls = false; ForceResets = 0; BusyStateValue = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -212,7 +238,7 @@ internal static unsafe class FakeHost
|
|||
PlayerIdValue = playerId;
|
||||
if (playerId != 0)
|
||||
api.GetPlayerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetPlayerId;
|
||||
if (Containers.Count > 0)
|
||||
if (Containers.Count > 0 || Wielders.Count > 0)
|
||||
api.GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)&GetObjectOwnershipInfo;
|
||||
if (Bitfields.Count > 0)
|
||||
api.GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&GetObjectBitfield;
|
||||
|
|
@ -222,6 +248,13 @@ internal static unsafe class FakeHost
|
|||
api.CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&CastSpell;
|
||||
if (StopCalls)
|
||||
api.StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&StopCompletely;
|
||||
if (Nav3DCalls)
|
||||
{
|
||||
api.Nav3DClearFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nav3DClear;
|
||||
api.Nav3DAddRingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, uint, void>)&Nav3DAddRing;
|
||||
api.Nav3DAddLineFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, float, float, uint, void>)&Nav3DAddLine;
|
||||
api.Nav3DAddTriangleFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, float, float, float, float, float, float, float, float, uint, void>)&Nav3DAddTriangle;
|
||||
}
|
||||
if (GiveCalls)
|
||||
api.GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&GiveObjectTo;
|
||||
if (WeaponCalls)
|
||||
|
|
@ -241,6 +274,15 @@ internal static unsafe class FakeHost
|
|||
api.SalvagePanelExecuteFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&SalvagePanelExecute;
|
||||
api.GetObjectWielderInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, int>)&GetObjectWielderInfo;
|
||||
}
|
||||
if (CombatModeCalls)
|
||||
api.ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ChangeCombatMode;
|
||||
if (BusyCalls)
|
||||
{
|
||||
api.ForceResetBusyCountFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&ForceResetBusyCount;
|
||||
api.GetBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&GetBusyState;
|
||||
}
|
||||
if (UseOnCalls)
|
||||
api.UseObjectOnFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&UseObjectOn;
|
||||
if (WieldCalls)
|
||||
{
|
||||
api.Version = 73;
|
||||
|
|
@ -402,9 +444,11 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetObjectOwnershipInfo(uint id, uint* container, uint* wielder, uint* location)
|
||||
{
|
||||
if (!Containers.TryGetValue(id, out uint c)) return 0;
|
||||
bool inPack = Containers.TryGetValue(id, out uint c);
|
||||
bool worn = Wielders.TryGetValue(id, out uint w);
|
||||
if (!inPack && !worn) return 0;
|
||||
*container = c;
|
||||
*wielder = 0;
|
||||
*wielder = w;
|
||||
*location = 0;
|
||||
return 1;
|
||||
}
|
||||
|
|
@ -543,6 +587,20 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint GetPlayerId() => PlayerIdValue;
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void Nav3DClear() { Nav3DRings.Clear(); Nav3DLines.Clear(); Nav3DTriangles.Clear(); }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void Nav3DAddRing(float x, float y, float z, float radius, float thick, uint color) => Nav3DRings.Add((x, y, z, radius, color));
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void Nav3DAddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thick, uint color)
|
||||
=> Nav3DLines.Add((x1, y1, z1, x2, y2, z2, thick, color));
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void Nav3DAddTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint color)
|
||||
=> Nav3DTriangles.Add((x1, y1, z1, x2, y2, z2, x3, y3, z3, color));
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static uint GetSelectedItemId() => SelectedItem;
|
||||
|
||||
|
|
@ -561,14 +619,23 @@ internal static unsafe class FakeHost
|
|||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int StopCompletely() { Stops++; return 1; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static void ForceResetBusyCount() { ForceResets++; BusyStateValue = 0; }
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetBusyState() => BusyStateValue;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GiveObjectTo(uint item, uint target, int amount) { Gives.Add((item, target, amount)); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int GetCurrentCombatMode() => CombatModeValue;
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int ChangeCombatMode(int mode) { CombatModeRequests.Add(mode); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int UseObject(uint id) { Uses.Add(id); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int UseObjectOn(uint source, uint target) { UsesOn.Add((source, target)); return 1; }
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int WieldItem(uint id, uint mask) { Wields.Add((id, mask)); return 1; }
|
||||
|
||||
|
|
|
|||
|
|
@ -17,6 +17,9 @@ internal static class Program
|
|||
/// <summary>Scratch folder next to the exe for files tests write. Emptied at start.</summary>
|
||||
public static string TempRoot { get; } = Path.Combine(AppContext.BaseDirectory, "scratch");
|
||||
|
||||
/// <summary>DungeonHazardStore's folder before Main pointed it at the scratch folder.</summary>
|
||||
public static string LiveHazardFolder { get; private set; } = "";
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
|
||||
|
|
@ -30,6 +33,9 @@ internal static class Program
|
|||
ExpressionEngine.ItemGiverDir = Path.Combine(TempRoot, "ItemGiver");
|
||||
// The dungeon map bake writes floor plans under C:\Games\RynthSuite\RynthAi\Maps.
|
||||
RynthCore.Plugin.RynthAi.Maps.DungeonMapBake.CacheDir = Path.Combine(TempRoot, "Maps");
|
||||
// A sighted lava/acid hotspot is persisted under C:\Games\RynthSuite\RynthAi\DungeonHazards.
|
||||
LiveHazardFolder = RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder;
|
||||
RynthCore.Plugin.RynthAi.DungeonHazardStore.Folder = Path.Combine(TempRoot, "DungeonHazards");
|
||||
|
||||
// Spell names (item spells, spell expiry by name) come from the plugin's embedded table.
|
||||
SpellDatabase.Load();
|
||||
|
|
@ -39,8 +45,10 @@ internal static class Program
|
|||
VTankLootTests.Register(runner);
|
||||
ExpressionTests.Register(runner);
|
||||
MetaTests.Register(runner);
|
||||
NoKillTests.Register(runner);
|
||||
MetaSchedulerTests.Register(runner);
|
||||
NavEngineTests.Register(runner);
|
||||
NavReachTests.Register(runner);
|
||||
PatrolDoorwayTests.Register(runner);
|
||||
BuffTests.Register(runner);
|
||||
CombatMathTests.Register(runner);
|
||||
|
|
@ -53,6 +61,7 @@ internal static class Program
|
|||
LootSalvageTests.Register(runner);
|
||||
LootCorpseTests.Register(runner);
|
||||
OwnCorpseTests.Register(runner);
|
||||
UseRefusalTests.Register(runner);
|
||||
VitalsTests.Register(runner);
|
||||
CastSafetyTests.Register(runner);
|
||||
HealLatencyTests.Register(runner);
|
||||
|
|
@ -64,6 +73,13 @@ internal static class Program
|
|||
LootAddItemTests.Register(runner);
|
||||
GiveTests.Register(runner);
|
||||
DungeonMapBakeTests.Register(runner);
|
||||
MonsterEditorTests.Register(runner);
|
||||
InstallPathsTests.Register(runner);
|
||||
PetRefillTests.Register(runner);
|
||||
WorldCacheTypedTests.Register(runner);
|
||||
ItemInfoTests.Register(runner);
|
||||
NavOverlayTests.Register(runner);
|
||||
ActionPacingTests.Register(runner);
|
||||
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,6 +50,17 @@
|
|||
RynthAi's JSON against the engine's real reader. Same relative engine path the plugin
|
||||
itself references. -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\RadarSnapshotJson.cs" Link="Engine\RadarSnapshotJson.cs" />
|
||||
<!-- The Meta editor's "Set current" landblock / landcell text (self-contained), so MetaTests
|
||||
check that MetaManager matches what the editor writes (engine 2026-10-05). -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\Data\MetaLocation.cs" Link="Engine\MetaLocation.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- The standalone Monster Editor's model and file code (no Avalonia in these), so its
|
||||
load/save is checked against the plugin's own serializer (MonsterEditorTests). -->
|
||||
<Compile Include="..\RynthCore.MonsterEditor\Models.cs" Link="MonsterEditor\Models.cs" />
|
||||
<Compile Include="..\RynthCore.MonsterEditor\JsonContext.cs" Link="MonsterEditor\JsonContext.cs" />
|
||||
<Compile Include="..\RynthCore.MonsterEditor\MonsterRulesFile.cs" Link="MonsterEditor\MonsterRulesFile.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
622
Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
Normal file
622
Tools/RynthCore.RynthAiHostTests/Tests/ActionPacingTests.cs
Normal file
|
|
@ -0,0 +1,622 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// One server action at a time (2026-10-06, ops\overnight\2026-10-06-action-pacing.md).
|
||||
// Drakkon's stuck uses and stuck casts on DreamWeave: every stall began with a combat-mode change
|
||||
// sent while a corpse use was still unanswered, and once the server held an action RynthAi fired
|
||||
// the next cast or use every 0.4-2.5 s on top of it (it paced on a busy count it kept zeroing, and
|
||||
// on the enchantment rather than the server's UseDone). These tests replay those sequences against
|
||||
// Plugins/Shared/ActionPacer.cs and the RynthAi code wired to it:
|
||||
// - the pacer itself: answers (UseDone, a refusal, a wield, a stance read), time limits, the heal
|
||||
// rules, and that nothing is ever force-cleared;
|
||||
// - the onset sequence (corpse use -> idle peace swap 3-677 ms later) and the movement hold;
|
||||
// - BuffManager: a cast whose result is in but whose UseDone isn't waits (one cast, not a flood),
|
||||
// heals still go first, and the emergency stance settle is unchanged;
|
||||
// - looting: one open per answer; Drakkon's stall is still found and reported once;
|
||||
// - CombatManager's idle peace swap waits for an unanswered kit;
|
||||
// - the busy mirror is reset without touching the client's count.
|
||||
internal static class ActionPacingTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint Corpse = 0x80068ACE;
|
||||
private const uint CorpseB = 0x80072023;
|
||||
private const uint Kit = 0x8004BEF8;
|
||||
private const uint Wand = 0x8007467A;
|
||||
private const uint Pack = 0x50000E01; // the player's main pack is the player
|
||||
private const uint ItemTypeContainer = 0x200;
|
||||
private const uint LongDescKey = 16;
|
||||
private const uint TooBusy = 0x1D;
|
||||
private const string Me = "Drakkon";
|
||||
private static readonly (uint Cell, float X, float Y, float Z) Me0 = (0xA9B40019u, 100f, 100f, 0f);
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("pacing: a use is the server action until its UseDone; a refusal answers it too; a wield answers by wielding", UseAnswers);
|
||||
r.Add("pacing: the stall onset replayed - the idle peace swap waits for the corpse use's answer, then goes; no swap to the mode you're in", OnsetModeChangeHeld);
|
||||
r.Add("pacing: moves, turns and redundant stops wait while the server answers; a real stop and the cast nudge go through", MovesHeld);
|
||||
r.Add("pacing: no answer - each kind's time limit lets the next action go, logged, and nothing is force-cleared", TimeLimits);
|
||||
r.Add("pacing: heals keep their priority (1 s behind a corpse use, 300 ms at Emergency, one behind a cast's result, 300 ms after the stance reads)", HealRules);
|
||||
r.Add("pacing (vitals): Drakkon 07:03 - a cast whose result is in waits for its UseDone: one cast, not a too-busy flood", CastWaitsForUseDone);
|
||||
r.Add("pacing (vitals): a heal goes 1 s behind an unanswered corpse use; the emergency stance settle is unchanged", HealLatencyKept);
|
||||
r.Add("pacing (looting): one open per server answer, never re-sent on top of an unanswered one", LootOneOpenPerAnswer);
|
||||
r.Add("pacing (looting): Drakkon's stall is still found and said once with pacing on", LootStallStillDetected);
|
||||
r.Add("pacing (combat): the idle peace swap waits while a kit is unanswered", CombatPeaceWaitsForKit);
|
||||
r.Add("pacing (arbiter): the activity-change StopCompletely only when RynthAi itself has the character moving", ArbiterStopOnlyWhenMoving);
|
||||
r.Add("busy mirror: follows the engine's count (1.5 s), never reset while the engine says busy; old engines: the mirror only; never a force-clear", MirrorResetOnly);
|
||||
}
|
||||
|
||||
// ── Pacer rig ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static long _t;
|
||||
|
||||
/// <summary>Turns the pacing on with RynthAi's use recorder and a hand-moved clock.</summary>
|
||||
private static void PaceOn()
|
||||
{
|
||||
_t = 10_000_000;
|
||||
ActionPacer.Reset();
|
||||
ActionPacer.Enabled = true;
|
||||
ActionPacer.NowMs = () => _t;
|
||||
UseAudit.Reset("RynthAi", () => true);
|
||||
UseAudit.NowMs = () => _t;
|
||||
MoveAudit.Reset();
|
||||
MoveAudit.NowMs = () => _t;
|
||||
var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!;
|
||||
UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u });
|
||||
}
|
||||
|
||||
private static void PaceOff()
|
||||
{
|
||||
ActionPacer.Enabled = false;
|
||||
ActionPacer.Reset();
|
||||
ActionPacer.NowMs = () => Environment.TickCount64;
|
||||
UseAudit.Reset("?", null);
|
||||
UseAudit.NowMs = () => Environment.TickCount64;
|
||||
MoveAudit.Reset();
|
||||
MoveAudit.NowMs = () => Environment.TickCount64;
|
||||
}
|
||||
|
||||
private static void Paced(Action body)
|
||||
{
|
||||
PaceOn();
|
||||
try { body(); }
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
private static RynthCoreHost World(int combatMode = 2)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true; // UseObject, GetCurrentCombatMode
|
||||
FakeHost.SalvageCalls = true; // GetObjectWielderInfo
|
||||
FakeHost.ServerGates = true; // GetUseDoneSeq
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.UseOnCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.BusyCalls = true;
|
||||
FakeHost.CombatModeValue = combatMode;
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Names[Corpse] = "Corpse of Olthoi Swarm Worker";
|
||||
FakeHost.Names[Kit] = "Peerless Healing Kit";
|
||||
FakeHost.Names[Wand] = "Academy Wand";
|
||||
FakeHost.Bitfields[Corpse] = 0x2000;
|
||||
FakeHost.Containers[Kit] = Pack;
|
||||
FakeHost.Containers[Wand] = Pack;
|
||||
return FakeHost.Create(Player);
|
||||
}
|
||||
|
||||
private static bool Logged(string part) => FakeHost.Logs.Any(l => l.Contains(part, StringComparison.Ordinal));
|
||||
|
||||
// ── The pacer ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static void UseAnswers() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
Check.True(host.UseFor(Corpse, "Loot", "open the claimed corpse"), "the open goes out");
|
||||
var a = ActionPacer.Current(host);
|
||||
Check.True(a != null && a.Kind == PacedKind.WorldUse, "a corpse is a world use the server walks to");
|
||||
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out string why), "nothing else starts meanwhile");
|
||||
Check.True(why.Contains("Corpse of Olthoi Swarm Worker") && why.Contains("RynthAi/Loot"), "why names the corpse and the sender: " + why);
|
||||
_t += 690; // the healthy median answer
|
||||
Check.True(ActionPacer.Current(host) != null, "still unanswered at 690 ms");
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(ActionPacer.Current(host) == null, "its UseDone answers it");
|
||||
Check.True(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "the next action may go");
|
||||
|
||||
// A kit on yourself is an item use; "You're too busy" (0x1D) is an answer as well.
|
||||
Check.True(host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself"), "the kit goes out");
|
||||
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "a kit on yourself is an item use");
|
||||
FakeHost.UseDone(TooBusy);
|
||||
Check.True(ActionPacer.Current(host) == null, "a refusal answers it (the server is busy with something else; the caller backs off)");
|
||||
|
||||
// A wield gets no UseDone at all (0 of 18 wand wields on 10-05/10-06): it answers by wielding.
|
||||
Check.True(host.UseFor(Wand, "Buff", "buffing: wield the wand"), "the wield goes out");
|
||||
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.ItemUse, "an item use");
|
||||
_t += 400;
|
||||
Check.True(ActionPacer.Current(host) != null, "not wielded yet: waiting");
|
||||
FakeHost.Wielded[Wand] = 0x1000000;
|
||||
Check.True(ActionPacer.Current(host) != null, "wielded: a short settle first");
|
||||
_t += ActionPacer.WieldSettleMs;
|
||||
Check.True(ActionPacer.Current(host) == null, "wielded and settled: answered");
|
||||
Check.Eq(ActionPacer.TimedOut, 0L, "no time limit was needed");
|
||||
});
|
||||
|
||||
private static void OnsetModeChangeHeld() => Paced(() =>
|
||||
{
|
||||
// 06:18:44.549 corpse use in melee stance, 06:18:44.552 RequestCombatMode(peace).
|
||||
var host = World(combatMode: 2);
|
||||
host.UseFor(Corpse, "Loot", "open the claimed corpse");
|
||||
_t += 3;
|
||||
Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "3 ms later: the peace swap is held");
|
||||
_t += 674;
|
||||
Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "677 ms later (10-05 13:18:31): still held");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no mode change reached the server while the use was unanswered");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("change to Peace mode held")), 1, "logged once");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(host.ChangeCombatModeFor(CombatMode.NonCombat, "Combat", "idle: no target"), "answered: the swap goes out");
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "one request, to peace");
|
||||
Check.True(ActionPacer.Current(host)?.Kind == PacedKind.CombatMode, "the stance change is now the action the server is answering");
|
||||
|
||||
// The next corpse waits for the stance: the client reads peace, then the animation.
|
||||
FakeHost.CombatModeValue = 1;
|
||||
_t += 500;
|
||||
Check.False(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "500 ms: the stance animation is still running");
|
||||
_t += ActionPacer.ModeSettleMs - 500;
|
||||
Check.True(ActionPacer.MayStart(host, "Loot", HealNeed.None, out _), "800 ms: settled, the next open may go");
|
||||
|
||||
// No request for the mode the client already reads (the engine pushed a raw 0x53 anyway).
|
||||
FakeHost.CombatModeRequests.Clear();
|
||||
Check.False(host.ChangeCombatModeFor(CombatMode.NonCombat, "Loot/Wedge", "loot wedge reset"), "already in peace: nothing to send");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "nothing sent");
|
||||
Check.True(host.ChangeCombatModeFor(CombatMode.NonCombat, "Command", "/ra panic", force: true), "a typed command forces it");
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 1, "forced: sent");
|
||||
});
|
||||
|
||||
private static void MovesHeld() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
host.UseFor(Corpse, "Loot", "open the claimed corpse");
|
||||
Check.False(host.SetAutoRunBy("Nav", true), "nav can't start running");
|
||||
Check.False(host.TurnToHeadingBy("Nav", 90f), "nor turn");
|
||||
Check.False(host.SetMotionBy("Combat", 0x6500000D, true), "nor start a turn motion");
|
||||
Check.False(host.StopCompletelyBy("Arbiter"), "a stop with nothing of ours moving is a redundant movement packet: held");
|
||||
Check.False(host.SetMotionBy("Combat", 0x6500000D, false), "Combat's turn-off with no turn on: held");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "no autorun reached the client");
|
||||
Check.Eq(FakeHost.Stops, 0, "no stop either");
|
||||
Check.True(Logged("held (move/turn): the server is still answering the use of"), "the hold is logged");
|
||||
|
||||
Check.True(host.SetAutoRunBy("Buff/Nudge", true) && host.SetAutoRunBy("Buff/Nudge", false), "the held-cast nudge is deliberate: it goes through");
|
||||
Check.True(host.StopCompletelyBy("MacroStop"), "a macro stop goes through");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
Check.True(host.SetAutoRunBy("Nav", true), "answered: nav runs again");
|
||||
host.UseFor(CorpseB, "Loot", "open the claimed corpse");
|
||||
FakeHost.Names[CorpseB] = "Corpse of Olthoi Swarm Drone";
|
||||
Check.True(host.StopCompletelyBy("Arbiter"), "while we really run, a stop always goes through");
|
||||
Check.False(MoveAudit.OwnMovementActive, "and we are not moving any more");
|
||||
});
|
||||
|
||||
private static void TimeLimits() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
void Expect(PacedKind kind, long limit, Action send)
|
||||
{
|
||||
long before = ActionPacer.TimedOut;
|
||||
send();
|
||||
Check.True(ActionPacer.Current(host)?.Kind == kind, $"{kind}: outstanding");
|
||||
_t += limit - 1;
|
||||
Check.True(ActionPacer.Current(host) != null, $"{kind}: still waiting 1 ms before {limit} ms");
|
||||
_t += 1;
|
||||
Check.True(ActionPacer.Current(host) == null, $"{kind}: the time limit lets the next action go");
|
||||
Check.Eq(ActionPacer.TimedOut, before + 1, $"{kind}: counted");
|
||||
}
|
||||
Expect(PacedKind.WorldUse, ActionPacer.WorldUseMaxMs, () => host.UseFor(Corpse, "Loot", "open"));
|
||||
Expect(PacedKind.ItemUse, ActionPacer.ItemUseMaxMs, () => host.UseOnFor(Kit, Player, "Buff", "kit"));
|
||||
Expect(PacedKind.Cast, ActionPacer.CastMaxMs, () => host.CastSpellFor(Player, 1426, "Buff", "Focus Self VI"));
|
||||
FakeHost.CombatModeValue = 2;
|
||||
Expect(PacedKind.CombatMode, ActionPacer.ModeMaxMs, () => host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand"));
|
||||
Check.True(Logged("no answer from the server to the cast of Focus Self VI") && Logged("nothing cleared"), "each is logged, and says nothing was cleared");
|
||||
Check.Eq(FakeHost.ForceResets, 0, "the client's busy count was never force-cleared");
|
||||
});
|
||||
|
||||
private static void HealRules() => Paced(() =>
|
||||
{
|
||||
var host = World();
|
||||
host.UseFor(Corpse, "Loot", "open");
|
||||
_t += 900;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a heal 900 ms behind an unanswered corpse use waits");
|
||||
_t += 100;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "at 1 s it goes ahead (the server cancels the walk cleanly)");
|
||||
Check.True(Logged("the heal goes ahead of the use of"), "logged");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
host.UseFor(Corpse, "Loot", "open");
|
||||
_t += 300;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "at Emergency Heal At: 300 ms");
|
||||
Check.False(ActionPacer.MayStart(host, "Combat", HealNeed.None, out _), "anything else still waits");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
host.CastSpellFor(Player, 1426, "Buff", "Focus Self VI");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "a cast before its result: the heal waits (the server would refuse it)");
|
||||
ActionPacer.NoteCastResult();
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "its result is in: one heal may queue behind the recoil");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Heal, out _), "only one");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff waits for the UseDone");
|
||||
|
||||
FakeHost.UseDone(0);
|
||||
FakeHost.CombatModeValue = 2;
|
||||
host.ChangeCombatModeFor(CombatMode.Magic, "Buff", "wand wielded: Magic mode");
|
||||
_t += 60;
|
||||
FakeHost.CombatModeValue = 8;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "the client reads Magic: not yet");
|
||||
_t += 299;
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "299 ms after the read: not yet");
|
||||
_t += 1;
|
||||
Check.True(ActionPacer.MayStart(host, "Buff", HealNeed.Emergency, out _), "300 ms after the read: the heal goes");
|
||||
Check.False(ActionPacer.MayStart(host, "Buff", HealNeed.None, out _), "a buff waits for the full 800 ms settle");
|
||||
});
|
||||
|
||||
// ── BuffManager ──────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class BuffRig
|
||||
{
|
||||
public DateTime T0 = new(2026, 10, 6, 7, 3, 23);
|
||||
public DateTime NowAt;
|
||||
public readonly BuffManager B;
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly PlayerVitalsCache V;
|
||||
public RynthCoreHost Host;
|
||||
|
||||
public BuffRig(int combatMode = CombatMode.Magic)
|
||||
{
|
||||
Host = World(combatMode);
|
||||
FakeHost.Containers.Clear();
|
||||
foreach (var row in SpellTable.Rows) FakeHost.Spellbook.Add((uint)row.Id);
|
||||
FakeHost.Skills[(Player, 33)] = (400, 2);
|
||||
Host = FakeHost.Create(Player);
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, HealAt = 0, TopOffHP = 0, EmergencyHealAt = 0, StaminaToHealthAt = 0,
|
||||
GetManaAt = 50, TopOffMana = 50, RestamAt = 0, TopOffStam = 0, UsePotions = false,
|
||||
EnableBuffing = false, SpellCastIntervalMs = 0,
|
||||
};
|
||||
var skills = new CharacterSkills(Host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(Host, S);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
V = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 100, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 10 };
|
||||
B = new BuffManager(Host, S, sm, V);
|
||||
B.SetCharacterSkills(skills);
|
||||
NowAt = T0;
|
||||
B.Clock = () => NowAt;
|
||||
B.MarkLiveBuffsReadyForTests();
|
||||
_t = 10_000_000;
|
||||
ActionPacer.NowMs = () => _t + (long)(NowAt - T0).TotalMilliseconds;
|
||||
MoveAudit.NowMs = ActionPacer.NowMs;
|
||||
}
|
||||
|
||||
public void At(double seconds) => NowAt = T0.AddSeconds(seconds);
|
||||
public void Chat(string text, int type = 0) => B.OnChatWindowText(text, type);
|
||||
public string CastName => SpellTable.ById(FakeHost.Casts.Last().SpellId)?.Name ?? "";
|
||||
}
|
||||
|
||||
private static void CastWaitsForUseDone()
|
||||
{
|
||||
// Without the pacing (as before): the result line ends the cast, and with mana still low the
|
||||
// next Stamina to Mana goes straight out - on a server holding the first one, "too busy".
|
||||
int Script(bool pacing)
|
||||
{
|
||||
PaceOn();
|
||||
ActionPacer.Enabled = pacing;
|
||||
try
|
||||
{
|
||||
var r = new BuffRig();
|
||||
r.At(0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, $"pacing={pacing}: Stamina to Mana goes out");
|
||||
string name = r.CastName;
|
||||
r.At(0.1); r.Chat("You say, \"Puish Zharil\"", 17);
|
||||
// 07:03:26.799: the result is in 3.3 s later; the server's UseDone never comes.
|
||||
r.At(2.3); r.Chat($"You cast {name} on yourself and lose 35 points of stamina and also gain 47 points of mana");
|
||||
for (double s = 2.4; s < 4.0; s += 0.1) { r.At(s); r.B.OnHeartbeat(); }
|
||||
int before = FakeHost.Casts.Count;
|
||||
if (pacing)
|
||||
{
|
||||
Check.True(r.B.PacerHolds > 0, "the vitals step waited for the server's answer");
|
||||
FakeHost.UseDone(0);
|
||||
r.At(4.0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 2, "the UseDone arrives: the next cast goes at once");
|
||||
}
|
||||
return before;
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
int unpaced = Script(pacing: false);
|
||||
int paced = Script(pacing: true);
|
||||
Check.True(unpaced >= 2, $"without pacing a second cast went out before the server answered ({unpaced} casts by 4 s)");
|
||||
Check.Eq(paced, 1, "with pacing: one cast until the server answers it");
|
||||
}
|
||||
|
||||
private static void HealLatencyKept()
|
||||
{
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
// A heal behind a corpse use the server walks to: it waits 1 s, not the whole walk.
|
||||
var r = new BuffRig();
|
||||
r.S.HealAt = 60; r.S.TopOffHP = 60; r.S.GetManaAt = 0; r.S.TopOffMana = 0;
|
||||
r.V.CurrentHealth = 50; r.V.CurrentMana = 100;
|
||||
r.At(0);
|
||||
r.Host.UseFor(Corpse, "Loot", "open the claimed corpse");
|
||||
r.B.BusyCount = 1; // the open's +1 on the client's count, as the engine reports it
|
||||
for (double s = 0; s < 0.95; s += 0.1) { r.At(s); r.B.OnHeartbeat(); }
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "under 1 s behind the unanswered open: no heal yet");
|
||||
r.At(1.0); r.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "at 1 s the heal goes (the open's busy count doesn't hold it again)");
|
||||
string healName = SpellTable.ById(FakeHost.Casts[0].SpellId)?.Name ?? "";
|
||||
Check.True(healName.StartsWith("Heal Self") || healName == "Adja's Intervention", "and it is the heal spell: " + healName);
|
||||
|
||||
// Nothing outstanding: the heal goes on the first heartbeat, as before.
|
||||
PaceOff(); PaceOn();
|
||||
var q = new BuffRig();
|
||||
q.S.HealAt = 60; q.S.TopOffHP = 60; q.S.GetManaAt = 0; q.S.TopOffMana = 0;
|
||||
q.V.CurrentHealth = 50; q.V.CurrentMana = 100;
|
||||
q.At(0); q.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "nothing outstanding: Heal Self on the first heartbeat");
|
||||
|
||||
// The emergency settle after a stance change (CastSafetyTests.EmergencyStanceWait) with the
|
||||
// pacing on: the stance change is the outstanding action, and the heal still goes 300 ms
|
||||
// after the client reads Magic.
|
||||
PaceOff(); PaceOn();
|
||||
var e = new BuffRig(CombatMode.NonCombat);
|
||||
e.S.EmergencyHealAt = 30; e.S.HealAt = 60; e.S.TopOffHP = 60; e.S.GetManaAt = 0; e.S.TopOffMana = 0;
|
||||
e.V.CurrentHealth = 20; e.V.CurrentMana = 100;
|
||||
e.At(0); e.B.OnHeartbeat();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "8", "out of Magic: the stance request goes out");
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "no cast before the stance");
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
e.At(0.06); e.B.OnHeartbeat();
|
||||
e.At(0.30); e.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 0, "240 ms after Magic: still settling");
|
||||
e.At(0.37); e.B.OnHeartbeat();
|
||||
Check.Eq(FakeHost.Casts.Count, 1, "310 ms after Magic (370 ms after the request): Heal Self goes, as without pacing");
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
// ── Looting ──────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void LootWorld()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true;
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.ServerGates = true;
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.BusyCalls = true;
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
foreach ((uint id, float dx) in new[] { (Corpse, 1.0f), (CorpseB, 1.5f) })
|
||||
{
|
||||
FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker";
|
||||
FakeHost.ItemTypes[id] = ItemTypeContainer;
|
||||
FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(id);
|
||||
FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true, EnableLooting = true, EnableCombat = false, LootOwnership = 0,
|
||||
LootContentSettleMs = 0, LootEmptyCorpseMs = 0, StopLootingWhenPackFull = false,
|
||||
};
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
Set("_objectCache", cache);
|
||||
Set("_playerId", Player);
|
||||
cache.OnCreateObject(Corpse);
|
||||
cache.OnCreateObject(CorpseB);
|
||||
cache.Tick();
|
||||
string profile = Path.Combine(Program.TempRoot, "action-pacing-test.json");
|
||||
new LootProfile { Name = "nothing" }.Save(profile);
|
||||
S.CurrentLootPath = profile;
|
||||
}
|
||||
|
||||
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 object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
public void Tick() { Set("_activity", BotActivity.Looting); Call("TickCorpseOpening"); }
|
||||
}
|
||||
|
||||
/// <summary>The loot clock and the pacer clock on one fake time.</summary>
|
||||
private static void WithClock(Action<Func<long>, Action<long>> body)
|
||||
{
|
||||
long now = 50_000_000;
|
||||
var saved = RynthAiPlugin.CorpseClock;
|
||||
RynthAiPlugin.CorpseClock = () => now;
|
||||
ActionPacer.NowMs = () => now;
|
||||
UseAudit.NowMs = () => now;
|
||||
MoveAudit.NowMs = () => now;
|
||||
try { body(() => now, ms => now += ms); }
|
||||
finally { RynthAiPlugin.CorpseClock = saved; }
|
||||
}
|
||||
|
||||
private static void LootOneOpenPerAnswer()
|
||||
{
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
for (int i = 0; i < 10 && FakeHost.Uses.Count == 0; i++) { bot.Tick(); advance(100); }
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "the open goes out");
|
||||
// A long walk: no answer for 3 s. Before, the open was re-sent every LootOpenRetryMs,
|
||||
// and each re-send restarted the server's walk and failed the first open's callback.
|
||||
for (int i = 0; i < 30; i++) { bot.Tick(); advance(100); }
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "not re-sent while the server hasn't answered");
|
||||
Check.True(Logged("[Pace] Loot waits: the use of"), "the wait is logged once");
|
||||
FakeHost.UseDone(0);
|
||||
bot.P.OnViewObjectContents(FakeHost.Uses.Last());
|
||||
Check.True(ActionPacer.Current(host) == null, "answered: nothing outstanding");
|
||||
// The empty corpse is done; the next one is opened - once, and only now.
|
||||
for (int i = 0; i < 20; i++) { bot.Tick(); advance(100); }
|
||||
Check.Eq(FakeHost.Uses.Count, 2, "the next corpse's open went out after the answer, once");
|
||||
Check.Eq(FakeHost.Uses.Last(), CorpseB, "it is the other corpse");
|
||||
Check.True(ActionPacer.Current(host)?.Id == CorpseB, "and it is the action the server is answering now");
|
||||
Check.Eq(FakeHost.ForceResets, 0, "no force-clear");
|
||||
});
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
private static void LootStallStillDetected()
|
||||
{
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
long answerAt = 0;
|
||||
int maxOutstanding = 0;
|
||||
void Step()
|
||||
{
|
||||
int uses = FakeHost.Uses.Count;
|
||||
bot.Tick();
|
||||
if (FakeHost.Uses.Count > uses) answerAt = now() + 60;
|
||||
maxOutstanding = Math.Max(maxOutstanding, FakeHost.Uses.Count - FakeHost.UseDoneSeq);
|
||||
advance(100);
|
||||
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; }
|
||||
}
|
||||
int steps = 0;
|
||||
while (FakeHost.Chat.Count(c => c.Contains("isn't letting this character use objects")) == 0 && steps++ < 900) Step();
|
||||
Check.Eq(FakeHost.Chat.Count(c => c.Contains("isn't letting this character use objects")), 1,
|
||||
$"the stall is found and said once ({steps / 10.0} s)");
|
||||
Check.True(steps <= 600, $"within a minute ({steps / 10.0} s)");
|
||||
Check.True(maxOutstanding <= 1, $"never more than one open unanswered (max {maxOutstanding})");
|
||||
});
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
// ── Combat ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void CombatPeaceWaitsForKit() => Paced(() =>
|
||||
{
|
||||
var host = World(combatMode: 2);
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 };
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
var combat = new CombatManager(host, s, cache);
|
||||
combat.SetPlayerId(Player);
|
||||
|
||||
// 07:00:11.8: a kit on yourself in melee stance; the server answers 2.4 s later.
|
||||
host.UseOnFor(Kit, Player, "Buff", "vitals: healing kit on yourself");
|
||||
for (int i = 0; i < 5; i++) { combat.Think(); _t += 400; }
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no peace swap while the kit is unanswered");
|
||||
FakeHost.UseDone(0);
|
||||
combat.Think();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "the kit answered: the idle swap goes out");
|
||||
});
|
||||
|
||||
private static void ArbiterStopOnlyWhenMoving()
|
||||
{
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
PaceOn();
|
||||
try
|
||||
{
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
bot.Call("StopNavFor", BotActivity.Looting);
|
||||
Check.Eq(FakeHost.Stops, 0, "nothing of ours moving: no StopCompletely (another plugin's movement isn't cut off)");
|
||||
host.SetAutoRunBy("Nav", true);
|
||||
bot.Call("StopNavFor", BotActivity.Buffing);
|
||||
Check.Eq(FakeHost.Stops, 1, "our autorun on: the stop goes out");
|
||||
ActionPacer.Enabled = false;
|
||||
bot.Call("StopNavFor", BotActivity.Combat);
|
||||
Check.Eq(FakeHost.Stops, 2, "pacing off: as before, always");
|
||||
});
|
||||
}
|
||||
finally { PaceOff(); }
|
||||
}
|
||||
|
||||
// ── Busy mirror ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static void MirrorResetOnly()
|
||||
{
|
||||
// The engine's count is the owner: a mirror left up follows it down after 1.5 s.
|
||||
LootWorld();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
FakeHost.BusyStateValue = 0; // the engine has seen the UseDones
|
||||
bot.Set("_busyCount", 2);
|
||||
bot.Set("_busyCountBecamePositiveAt", now());
|
||||
bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 2, "a fresh disagreement waits (events may be on their way)");
|
||||
advance(1_600);
|
||||
bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 0, "1.6 s later: the mirror follows the engine's 0");
|
||||
Check.True(Logged("following the engine's count"), "logged");
|
||||
|
||||
FakeHost.BusyStateValue = 1; // the server owes an answer: the mirror follows that too
|
||||
bot.Call("CheckBusyTimeout"); advance(1_600); bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 1, "and up, while the server still owes an answer");
|
||||
advance(30_000); bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 1, "never reset on a timer while the engine says busy");
|
||||
Check.Eq(FakeHost.ForceResets, 0, "the client's busy count is left to the client");
|
||||
});
|
||||
|
||||
// An engine without GetBusyState: the old timer, resetting the mirror only.
|
||||
LootWorld();
|
||||
FakeHost.BusyCalls = false;
|
||||
host = FakeHost.Create(Player);
|
||||
bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
bot.Set("_busyCount", 2);
|
||||
bot.Set("_busyCountBecamePositiveAt", now());
|
||||
advance(10_500);
|
||||
bot.Call("CheckBusyTimeout");
|
||||
Check.Eq(bot.Get<int>("_busyCount"), 0, "old engine: our mirror is reset after 10 s");
|
||||
Check.True(Logged("resetting the mirror only"), "and the line says so");
|
||||
});
|
||||
}
|
||||
}
|
||||
144
Tools/RynthCore.RynthAiHostTests/Tests/InstallPathsTests.cs
Normal file
144
Tools/RynthCore.RynthAiHostTests/Tests/InstallPathsTests.cs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Install;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// RynthInstallPaths (Plugins/Shared/RynthInstallPaths.cs, compiled into RynthAi): where RynthSuite
|
||||
// lives. Order is environment, HKCU, HKLM, then C:\Games\RynthSuite. The environment and the
|
||||
// registry are a fake here; the real registry is only READ, for a value that does not exist.
|
||||
// Idea from Silentkelpie (rynth PR #1); re-implemented here.
|
||||
internal static class InstallPathsTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("install paths: nothing set gives C:\\Games\\RynthSuite and C:\\Games\\RynthCore", NothingSet);
|
||||
r.Add("install paths: environment beats HKCU beats HKLM beats the default", Order);
|
||||
r.Add("install paths: empty, relative and broken values are skipped", Unusable);
|
||||
r.Add("install paths: folders with spaces", Spaces);
|
||||
r.Add("install paths: a source that throws falls through to the default", Throwing);
|
||||
r.Add("install paths: real registry, missing value reads as null (read only)", RealRegistryRead);
|
||||
r.Add("install paths: on a default install RynthAi's folders are exactly the old ones", DefaultInstallUnchanged);
|
||||
r.Add("install paths: same file as RynthCore src\\Shared (when the sibling is checked out)", SameAsRynthCore);
|
||||
}
|
||||
|
||||
private sealed class Fake : IInstallSettingSource
|
||||
{
|
||||
public readonly Dictionary<string, string?> Env = new();
|
||||
public readonly Dictionary<string, string?> User = new();
|
||||
public readonly Dictionary<string, string?> Machine = new();
|
||||
public int Asked;
|
||||
public bool Throw;
|
||||
|
||||
public string? EnvironmentVariable(string name) { Asked++; if (Throw) throw new InvalidOperationException(); return Env.GetValueOrDefault(name); }
|
||||
public string? CurrentUser(string valueName) { Asked++; if (Throw) throw new UnauthorizedAccessException(); return User.GetValueOrDefault(valueName); }
|
||||
public string? LocalMachine(string valueName) { Asked++; if (Throw) throw new IOException(); return Machine.GetValueOrDefault(valueName); }
|
||||
}
|
||||
|
||||
private static string Suite(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.SuiteEnvironmentVariable,
|
||||
RynthInstallPaths.SuiteValueName, RynthInstallPaths.DefaultSuiteDir, f);
|
||||
|
||||
private static string Core(Fake f) => RynthInstallPaths.Resolve(RynthInstallPaths.CoreEnvironmentVariable,
|
||||
RynthInstallPaths.CoreValueName, RynthInstallPaths.DefaultCoreDir, f);
|
||||
|
||||
private static void NothingSet()
|
||||
{
|
||||
var f = new Fake();
|
||||
Check.Eq(Suite(f), @"C:\Games\RynthSuite", "suite default");
|
||||
Check.Eq(Core(f), @"C:\Games\RynthCore", "core default");
|
||||
Check.Eq(f.Asked, 6, "env, HKCU and HKLM asked for each folder");
|
||||
}
|
||||
|
||||
private static void Order()
|
||||
{
|
||||
var f = new Fake();
|
||||
f.Machine["SuiteDir"] = @"D:\Machine\RynthSuite";
|
||||
Check.Eq(Suite(f), @"D:\Machine\RynthSuite", "HKLM beats the default");
|
||||
f.User["SuiteDir"] = @"E:\User\RynthSuite";
|
||||
Check.Eq(Suite(f), @"E:\User\RynthSuite", "HKCU beats HKLM");
|
||||
f.Env["RYNTHSUITE_DIR"] = @"F:\Dev\RynthSuite";
|
||||
Check.Eq(Suite(f), @"F:\Dev\RynthSuite", "environment beats HKCU");
|
||||
Check.Eq(Core(f), @"C:\Games\RynthCore", "suite settings leave the core folder alone");
|
||||
}
|
||||
|
||||
private static void Unusable()
|
||||
{
|
||||
foreach (string? bad in new[] { null, "", " ", "RynthSuite", @"..\RynthSuite", "C:", "D:\\a|b", "D:\\a*", "D:\\x:y" })
|
||||
{
|
||||
var f = new Fake();
|
||||
f.Env["RYNTHSUITE_DIR"] = bad;
|
||||
f.User["SuiteDir"] = bad;
|
||||
f.Machine["SuiteDir"] = bad;
|
||||
Check.Eq(Suite(f), @"C:\Games\RynthSuite", $"'{bad}' everywhere -> default");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Spaces()
|
||||
{
|
||||
var f = new Fake();
|
||||
f.User["SuiteDir"] = @"C:\Program Files (x86)\Rynth Suite\";
|
||||
Check.Eq(Suite(f), @"C:\Program Files (x86)\Rynth Suite", "HKCU value with spaces, trailing separator dropped");
|
||||
Check.Eq(Path.Combine(Suite(f), "RynthAi", "LootProfiles"), @"C:\Program Files (x86)\Rynth Suite\RynthAi\LootProfiles", "joined");
|
||||
var g = new Fake();
|
||||
g.Env["RYNTHSUITE_DIR"] = " \"D:\\My Games\\Rynth Suite\" ";
|
||||
Check.Eq(Suite(g), @"D:\My Games\Rynth Suite", "quoted, padded environment value with spaces");
|
||||
}
|
||||
|
||||
private static void Throwing()
|
||||
{
|
||||
var f = new Fake { Throw = true };
|
||||
Check.Eq(Suite(f), @"C:\Games\RynthSuite", "every source throws -> default");
|
||||
Check.Eq(f.Asked, 3, "all three tried");
|
||||
}
|
||||
|
||||
private static void RealRegistryRead()
|
||||
{
|
||||
string missing = "NoSuchValue-" + Guid.NewGuid().ToString("N");
|
||||
Check.Null(SystemInstallSettings.Instance.CurrentUser(missing), "HKCU missing value");
|
||||
Check.Null(SystemInstallSettings.Instance.LocalMachine(missing), "HKLM missing value");
|
||||
Check.True(Path.IsPathFullyQualified(RynthInstallPaths.SuiteDir), "live SuiteDir is absolute: " + RynthInstallPaths.SuiteDir);
|
||||
}
|
||||
|
||||
private static void DefaultInstallUnchanged()
|
||||
{
|
||||
if (RynthInstallPaths.SuiteDir != RynthInstallPaths.DefaultSuiteDir)
|
||||
{
|
||||
Console.WriteLine($" (this machine sets the RynthSuite folder to {RynthInstallPaths.SuiteDir}; default-install check skipped)");
|
||||
return;
|
||||
}
|
||||
Check.Eq(RynthInstallPaths.RynthAiDir, @"C:\Games\RynthSuite\RynthAi", "RynthAi folder");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.Loot.LootEditorBridge.LootFolder, @"C:\Games\RynthSuite\RynthAi\LootProfiles", "loot profiles");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.Vendor.AutoVendorManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoVendor", "AutoVendor");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.Trade.AutoTradeManager.MainProfileDir, @"C:\Games\RynthSuite\RynthAi\AutoTrade", "AutoTrade");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data");
|
||||
Check.Eq(RynthCore.Plugin.RynthAi.CreatureData.CreatureWeakness.WeaknessFile, @"C:\Games\RynthSuite\RynthAi\Data\creature_weakness.json", "weakness file");
|
||||
Check.Eq(PrivateStatic(typeof(RynthCore.Plugin.RynthAi.RadarWallRenderer), "ExploredDir"), @"C:\Games\RynthSuite\RynthAi\ExploredDungeons", "explored dungeons");
|
||||
// The tests point the store at their scratch folder (Program.Main); this is its value before that.
|
||||
Check.Eq(Program.LiveHazardFolder, @"C:\Games\RynthSuite\RynthAi\DungeonHazards", "dungeon hazards");
|
||||
}
|
||||
|
||||
private static string? PrivateStatic(Type type, string field)
|
||||
=> type.GetField(field, BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null) as string;
|
||||
|
||||
private static void SameAsRynthCore()
|
||||
{
|
||||
string here = Path.GetFullPath(Path.Combine(ThisFile(), "..", "..", "..", "..", "Plugins", "Shared", "RynthInstallPaths.cs"));
|
||||
string sibling = Path.GetFullPath(Path.Combine(ThisFile(), "..", "..", "..", "..", "..", "RynthCore", "src", "Shared", "RynthInstallPaths.cs"));
|
||||
Check.True(File.Exists(here), "RynthSuite copy found at " + here);
|
||||
if (!File.Exists(sibling))
|
||||
{
|
||||
Console.WriteLine($" (no RynthCore sibling at {sibling}; comparison skipped)");
|
||||
return;
|
||||
}
|
||||
Check.True(Text(here) == Text(sibling),
|
||||
"Plugins\\Shared\\RynthInstallPaths.cs matches RynthCore src\\Shared\\RynthInstallPaths.cs");
|
||||
}
|
||||
|
||||
private static string Text(string path) => File.ReadAllText(path).Replace("\r\n", "\n");
|
||||
|
||||
private static string ThisFile([CallerFilePath] string path = "") => path;
|
||||
}
|
||||
349
Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs
Normal file
349
Tools/RynthCore.RynthAiHostTests/Tests/ItemInfoTests.cs
Normal file
|
|
@ -0,0 +1,349 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.ItemInfo;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// /ra iteminfo (Silentkelpie's rynth PR #1 idea, re-implemented): a Mag-Tools style one-line
|
||||
// description of the selected or named item, identified first when the client hasn't
|
||||
// appraised it. The formatter is checked on fake appraisal data; the command end to end on
|
||||
// FakeHost (selection, ID request, the print when the ID lands, the timeout, name lookup).
|
||||
internal static class ItemInfoTests
|
||||
{
|
||||
private const uint Player = 0x50000F21;
|
||||
private const uint Sword = 0x80300001, Ring = 0x80300002, Scarab = 0x80300003, Scarab2 = 0x80300004;
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("iteminfo: a weapon's damage, mods, imbue, slayer, spells and wield line", WeaponLine);
|
||||
r.Add("iteminfo: armor's set, AL, ratings, tinks and wield level", ArmorLine);
|
||||
r.Add("iteminfo: jewelry with mana, diff and craft; a bare item stays short", JewelryAndBareItem);
|
||||
r.Add("iteminfo: a selected item already appraised prints at once, no ID", SelectedAppraised);
|
||||
r.Add("iteminfo: an unappraised item is identified, then printed when the ID lands", IdentifiesThenPrints);
|
||||
r.Add("iteminfo: no reply prints what the client has after the timeout", TimeoutPrints);
|
||||
r.Add("iteminfo: a name picks the inventory item, exact before partial", NameLookup);
|
||||
r.Add("iteminfo: nothing selected or no such item says so", NothingSelected);
|
||||
r.Add("iteminfo on select: the player's pick prints quietly; the bot's own picks and the setting off do not", OnSelect);
|
||||
}
|
||||
|
||||
// ── Fake appraisal data ─────────────────────────────────────────────
|
||||
|
||||
private sealed class Fake : IItemInfoSource
|
||||
{
|
||||
public string Name { get; init; } = "";
|
||||
public Dictionary<uint, int> Ints { get; } = new();
|
||||
public Dictionary<uint, double> Floats { get; } = new();
|
||||
public List<int> Spells { get; } = new();
|
||||
public IReadOnlyList<int> SpellIds => Spells;
|
||||
public bool TryInt(uint key, out int value) => Ints.TryGetValue(key, out value);
|
||||
public bool TryFloat(uint key, out double value) => Floats.TryGetValue(key, out value);
|
||||
}
|
||||
|
||||
private static string Spell(int id) => SpellDatabase.GetSpellName(id);
|
||||
|
||||
/// <summary>Each part appears, in this order.</summary>
|
||||
private static void InOrder(string text, string[] parts, string what)
|
||||
{
|
||||
int at = 0;
|
||||
foreach (string p in parts)
|
||||
{
|
||||
int i = text.IndexOf(p, at, StringComparison.Ordinal);
|
||||
Check.True(i >= 0, $"{what}: has \"{p}\" after position {at} in: {text}");
|
||||
if (i >= 0) at = i + p.Length;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WeaponLine()
|
||||
{
|
||||
var w = new Fake { Name = "Ornate Katar" };
|
||||
w.Ints[ItemInfoText.IntItemType] = 0x1;
|
||||
w.Ints[ItemInfoText.IntMaterial] = 61; // Iron
|
||||
w.Ints[ItemInfoText.IntWeaponSkill] = 44; // Heavy Weapons
|
||||
w.Ints[ItemInfoText.IntDamage] = 77;
|
||||
w.Floats[ItemInfoText.FloatDamageVariance] = 0.4;
|
||||
w.Ints[ItemInfoText.IntDamageType] = 16; // Fire
|
||||
w.Ints[ItemInfoText.IntWeaponTime] = 30;
|
||||
w.Floats[ItemInfoText.FloatWeaponOffense] = 1.18;
|
||||
w.Floats[ItemInfoText.FloatMeleeDefense] = 1.20;
|
||||
w.Floats[ItemInfoText.FloatMagicDefense] = 1.0; // +0%: left out
|
||||
w.Ints[ItemInfoText.IntImbued] = 0x2 | 0x200; // Crippling Blow, Fire Rending
|
||||
w.Ints[ItemInfoText.IntSlayerType] = 14; // Undead
|
||||
w.Ints[ItemInfoText.IntTinks] = 2;
|
||||
w.Spells.AddRange(new[] { 2531, 6107, 2531 }); // a repeat is named once
|
||||
w.Ints[ItemInfoText.IntWieldReq] = 1;
|
||||
w.Ints[ItemInfoText.IntWieldSkill] = 44;
|
||||
w.Ints[ItemInfoText.IntWieldDiff] = 375;
|
||||
w.Ints[ItemInfoText.IntWieldReq2] = 7;
|
||||
w.Ints[ItemInfoText.IntWieldDiff2] = 150;
|
||||
w.Ints[ItemInfoText.IntItemDifficulty] = 300;
|
||||
w.Ints[ItemInfoText.IntWorkmanship] = 9;
|
||||
w.Ints[ItemInfoText.IntValue] = 12345;
|
||||
w.Ints[ItemInfoText.IntEncumbrance] = 350;
|
||||
w.Ints[ItemInfoText.Ratings[0].Key] = 2; // D2
|
||||
|
||||
string s = ItemInfoText.Describe(w, Spell);
|
||||
InOrder(s, new[]
|
||||
{
|
||||
"Iron Ornate Katar (Melee Weapon)", "[D2]", "Heavy Weapons", "Dmg 46-77 Fire", "Speed 30",
|
||||
"(+18% atk, +20% md)", "Crippling Blow, Fire Rending", "Undead Slayer", "Tinks 2",
|
||||
"Spells: Major Heavy Weapon Aptitude, Legendary Strength", "Heavy Weapons 375 to wield",
|
||||
"Wield Lvl 150", "Diff 300", "Craft 9", "Mat Iron", "Value 12,345", "BU 350",
|
||||
}, "weapon");
|
||||
Check.False(s.Contains("mgd"), "a +0% mod is left out");
|
||||
Check.Eq(s.Split("Major Heavy Weapon Aptitude").Length, 2, "each spell named once");
|
||||
Check.False(s.Contains("not identified"), "identified: no note");
|
||||
}
|
||||
|
||||
private static void ArmorLine()
|
||||
{
|
||||
var a = new Fake { Name = "Chainmail Tassets" };
|
||||
a.Ints[ItemInfoText.IntItemType] = 0x2;
|
||||
a.Ints[ItemInfoText.IntSetId] = 16; // Defender's
|
||||
a.Ints[ItemInfoText.IntArmorLevel] = 584;
|
||||
a.Ints[371] = 1; // DR1
|
||||
a.Ints[375] = 2; // CDR2
|
||||
a.Ints[ItemInfoText.IntTinks] = 3;
|
||||
a.Ints[ItemInfoText.IntWieldReq] = 7;
|
||||
a.Ints[ItemInfoText.IntWieldDiff] = 180;
|
||||
a.Ints[ItemInfoText.IntMaterial] = 64; // Steel
|
||||
string s = ItemInfoText.Describe(a, Spell);
|
||||
InOrder(s, new[] { "Steel Chainmail Tassets (Armor)", "Defender's Set", "AL 584", "[DR1 CDR2]", "Tinks 3", "Wield Lvl 180", "Mat Steel" }, "armor");
|
||||
Check.False(s.Contains("Dmg"), "armor shows no damage");
|
||||
Check.False(s.Contains("Speed"), "or speed");
|
||||
}
|
||||
|
||||
private static void JewelryAndBareItem()
|
||||
{
|
||||
var j = new Fake { Name = "Gold Ring" };
|
||||
j.Ints[ItemInfoText.IntItemType] = 0x8;
|
||||
j.Ints[ItemInfoText.IntMaterial] = 60; // Gold: already in the name
|
||||
j.Ints[ItemInfoText.IntCurMana] = 1200;
|
||||
j.Ints[ItemInfoText.IntMaxMana] = 1500;
|
||||
j.Ints[ItemInfoText.IntItemDifficulty] = 285;
|
||||
j.Ints[ItemInfoText.IntWorkmanship] = 7;
|
||||
j.Ints[ItemInfoText.IntAttuned] = 1;
|
||||
j.Spells.Add(3964);
|
||||
string s = ItemInfoText.Describe(j, Spell);
|
||||
InOrder(s, new[] { "Gold Ring (Jewelry)", "Spells: Epic Focus", "Diff 285", "Mana 1200/1500", "Craft 7", "Mat Gold", "Attuned" }, "jewelry");
|
||||
Check.False(s.Contains("Gold Gold"), "the material isn't doubled");
|
||||
Check.False(s.Contains("AL "), "jewelry with no armor shows no AL");
|
||||
|
||||
var bare = new Fake { Name = "Mana Scarab" };
|
||||
bare.Ints[ItemInfoText.IntStackSize] = 25;
|
||||
string b = ItemInfoText.Describe(bare, Spell, identified: false);
|
||||
Check.True(b.StartsWith("Mana Scarab x25", StringComparison.Ordinal), $"a stack shows its size: {b}");
|
||||
Check.True(b.EndsWith("(not identified: no reply from the server)", StringComparison.Ordinal), "unidentified note last");
|
||||
Check.Eq(b.Split(", ").Length, 2, "nothing else is made up");
|
||||
}
|
||||
|
||||
// ── The command on FakeHost ─────────────────────────────────────────
|
||||
|
||||
private sealed class World
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly WorldObjectCache Cache;
|
||||
public long Now = 1_000_000;
|
||||
|
||||
public World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Names[Player] = "Reader";
|
||||
FakeHost.PlayerIdValue = Player;
|
||||
FakeHost.Positions[Player] = (0x1048002Au, 100f, 100f, 0f);
|
||||
FakeHost.PlayerPose = (0x1048002Au, 100f, 100f, 0f);
|
||||
Item(Sword, "Ornate Katar", 0x1);
|
||||
Item(Ring, "Gold Ring", 0x8);
|
||||
Item(Scarab, "Mana Scarab", 0x80);
|
||||
Item(Scarab2, "Platinum Scarab", 0x80);
|
||||
FakeHost.Ints[(Sword, ItemInfoText.IntDamage)] = 77;
|
||||
FakeHost.Ints[(Sword, ItemInfoText.IntWorkmanship)] = 9;
|
||||
FakeHost.Ints[(Ring, ItemInfoText.IntWorkmanship)] = 7;
|
||||
FakeHost.SpellIds[Ring] = new uint[] { 3964 };
|
||||
FakeHost.WeaponCalls = true; // RequestId + HasAppraisalData
|
||||
var host = FakeHost.Create(playerId: Player);
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, new LegacyUiSettings());
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Set("_initialized", true);
|
||||
Set("_loginComplete", true);
|
||||
foreach (uint id in new[] { Sword, Ring, Scarab, Scarab2 }) Cache.OnCreateObject(id);
|
||||
Cache.Tick();
|
||||
RynthAiPlugin.ItemInfoClock = () => Now;
|
||||
}
|
||||
|
||||
private static void Item(uint id, string name, uint type)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Containers[id] = Player;
|
||||
FakeHost.ItemTypes[id] = type;
|
||||
FakeHost.Ints[(id, ItemInfoText.IntItemType)] = (int)type;
|
||||
}
|
||||
|
||||
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
|
||||
|
||||
public void Command(string text)
|
||||
{
|
||||
string[] parts = text.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
typeof(RynthAiPlugin).GetMethod("HandleItemInfoCommand", Any)!.Invoke(P, new object[] { parts });
|
||||
}
|
||||
|
||||
public void Tick() => typeof(RynthAiPlugin).GetMethod("TickItemInfo", Any)!.Invoke(P, null);
|
||||
|
||||
public string[] InfoLines => FakeHost.Chat.Where(c => c.StartsWith("[RynthAi] ", StringComparison.Ordinal)).ToArray();
|
||||
}
|
||||
|
||||
private static void Done() => RynthAiPlugin.ItemInfoClock = () => Environment.TickCount64;
|
||||
|
||||
private static void OnSelect()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
void Select(uint id) => typeof(RynthAiPlugin).GetMethod("QueueItemInfoOnSelect", Any)!
|
||||
.Invoke(w.P, new object?[] { id, w.Cache[unchecked((int)id)] });
|
||||
|
||||
FakeHost.Appraised.Add(Ring);
|
||||
Select(Ring);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 1, "the player's pick prints once");
|
||||
Check.True(w.InfoLines[0].Contains("Gold Ring (Jewelry)"), $"the ring's line: {w.InfoLines.FirstOrDefault()}");
|
||||
|
||||
Select(Sword);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 1, "unappraised: no 'identifying' chatter on select");
|
||||
Check.True(FakeHost.IdRequests.Contains(Sword), "but the ID is asked for");
|
||||
FakeHost.Appraised.Add(Sword);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "printed when the appraisal lands");
|
||||
|
||||
SelfSelect.Mark(Ring);
|
||||
Select(Ring);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "an item RynthAi selected itself (the looter, a meta) prints nothing");
|
||||
|
||||
var dash = (LegacyDashboardRenderer)typeof(RynthAiPlugin).GetField("_dashboard", Any)!.GetValue(w.P)!;
|
||||
dash.Settings.ItemInfoOnSelect = false;
|
||||
Select(Scarab);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "setting off: nothing");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void SelectedAppraised()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
FakeHost.SelectedItem = Ring;
|
||||
FakeHost.Appraised.Add(Ring);
|
||||
w.Command("/ra iteminfo");
|
||||
Check.Eq(FakeHost.Chat.Count, 0, "the command only queues (the tick prints)");
|
||||
w.Tick();
|
||||
Check.Eq(FakeHost.IdRequests.Count, 0, "appraised: no ID request");
|
||||
Check.Eq(w.InfoLines.Length, 1, "one line");
|
||||
Check.True(w.InfoLines[0].Contains("Gold Ring (Jewelry)") && w.InfoLines[0].Contains("Spells: Epic Focus") && w.InfoLines[0].Contains("Craft 7"),
|
||||
$"the ring's line: {w.InfoLines.FirstOrDefault()}");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void IdentifiesThenPrints()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
FakeHost.SelectedItem = Sword;
|
||||
w.Command("/ra iteminfo");
|
||||
w.Tick();
|
||||
Check.True(FakeHost.IdRequests.SequenceEqual(new[] { Sword }), "one ID request for the sword");
|
||||
Check.Eq(w.InfoLines.Length, 1, "just the 'identifying' line so far");
|
||||
Check.True(w.InfoLines[0].Contains("identifying Ornate Katar"), "says it is identifying");
|
||||
w.Now += 1000;
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 1, "still waiting a second later");
|
||||
FakeHost.Appraised.Add(Sword);
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "printed when the appraisal arrives");
|
||||
Check.True(w.InfoLines[1].Contains("Ornate Katar (Melee Weapon)") && w.InfoLines[1].Contains("Dmg 77") && !w.InfoLines[1].Contains("not identified"),
|
||||
$"the sword's line: {w.InfoLines[1]}");
|
||||
w.Now += 10_000;
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "printed once");
|
||||
Check.Eq(FakeHost.IdRequests.Count, 1, "never asked twice");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void TimeoutPrints()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
FakeHost.SelectedItem = Sword;
|
||||
w.Command("/ra iteminfo");
|
||||
w.Tick();
|
||||
w.Now += RynthAiPlugin.ItemInfoTimeoutMs - 1;
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 1, "not before the timeout");
|
||||
w.Now += 1;
|
||||
w.Tick();
|
||||
Check.Eq(w.InfoLines.Length, 2, "printed at the timeout");
|
||||
Check.True(w.InfoLines[1].Contains("Ornate Katar") && w.InfoLines[1].EndsWith("(not identified: no reply from the server)", StringComparison.Ordinal),
|
||||
$"with what the client has and the note: {w.InfoLines[1]}");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void NameLookup()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
FakeHost.Appraised.Add(Scarab);
|
||||
FakeHost.Appraised.Add(Scarab2);
|
||||
FakeHost.Appraised.Add(Ring);
|
||||
w.Command("/ra iteminfo mana scarab");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Mana Scarab", StringComparison.Ordinal), $"exact name, any case: {w.InfoLines.Last()}");
|
||||
w.Command("/ra iteminfo Scarab");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Last().Contains("Scarab") && !w.InfoLines.Last().Contains("not in your"), "a partial name finds a scarab");
|
||||
w.Command("/ra iteminfo ring");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Last().StartsWith("[RynthAi] Gold Ring", StringComparison.Ordinal), "partial: Gold Ring");
|
||||
Check.Eq(FakeHost.SelectedItem, 0u, "a named lookup doesn't need a selection");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
|
||||
private static void NothingSelected()
|
||||
{
|
||||
var w = new World();
|
||||
try
|
||||
{
|
||||
w.Command("/ra iteminfo");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Length == 1 && w.InfoLines[0].Contains("nothing selected"), "nothing selected says so");
|
||||
w.Command("/ra iteminfo Shield of Nowhere");
|
||||
w.Tick();
|
||||
Check.True(w.InfoLines.Last().Contains("no \"Shield of Nowhere\" in your inventory"), $"unknown name says so: {w.InfoLines.Last()}");
|
||||
Check.Eq(FakeHost.IdRequests.Count, 0, "and nothing is identified");
|
||||
}
|
||||
finally { Done(); }
|
||||
}
|
||||
}
|
||||
|
|
@ -42,7 +42,7 @@ internal static class LootAddItemTests
|
|||
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);
|
||||
r.Add("loot add: the popup says when RynthAi's built-in looting takes the item (Mana Tap, mana stones)", BuiltInReasons);
|
||||
r.Add("loot: Mana Tap never loots a wand (ACE won't drain one, so it was kept for good)", ManaTapSkipsWands);
|
||||
r.Add("loot: Mana Tap takes a high-mana wand like any other item (they drain)", ManaTapTakesWands);
|
||||
}
|
||||
|
||||
// ── World and plugin ──────────────────────────────────────────────────────
|
||||
|
|
@ -445,16 +445,13 @@ internal static class LootAddItemTests
|
|||
Check.Eq(File.ReadAllText(path), SellGems, "preview saves nothing");
|
||||
}
|
||||
|
||||
private static void ManaTapSkipsWands()
|
||||
private static void ManaTapTakesWands()
|
||||
{
|
||||
var bot = TapWorld();
|
||||
bot.S.CurrentLootPath = Temp("wand.utl", SellGems);
|
||||
var wand = LootEval(bot, Sceptre);
|
||||
Check.False(wand.Taken, $"a 3,001-mana sceptre is left: [{wand.Action}] {wand.Rule}");
|
||||
Check.Eq(bot.Get<System.Collections.Generic.HashSet<int>>("_pendingManaTapIds")?.Count, 0, "not counted against the tap quota");
|
||||
Check.True(wand.Taken && wand.Action == "ManaTap", $"a 3,001-mana sceptre is tapped: [{wand.Action}] {wand.Rule}");
|
||||
var ring = LootEval(bot, Ring);
|
||||
Check.True(ring.Taken && ring.Action == "ManaTap", "a ring with the same mana is still tapped: " + ring.Action);
|
||||
Send(bot.P.LootEditor, new LootEditCommand { Op = "item_preview", Item = new LootEditItemRequest { ItemId = Sceptre, Seq = 1 } });
|
||||
Check.Eq(State(bot.P.LootEditor).ItemDraft?.BuiltInReason, "", "the popup has no built-in reason for the wand");
|
||||
Check.False(ring.Taken, "the one empty stone is now spoken for by the wand, so the ring waits: " + ring.Action);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,6 +59,127 @@ internal static class MetaTests
|
|||
SecondsInStatePPersists);
|
||||
r.Add("meta: MainHealthPHE / MainManaPHE mean 'percent >='", PercentConditionsAreGE); // was a known failure; fixed by a7c4618
|
||||
r.Add("meta: a negative vital threshold never holds", NegativeVitalThreshold); // was a known failure; fixed by 6f72b67
|
||||
r.Add("meta edit: saving a rule keeps the running meta's state, clocks and latch", EditKeepsRunningMeta);
|
||||
r.Add("meta edit: a saved rule keeps CallState's return state and ChatCapture's colours", EditKeepsHiddenFields);
|
||||
r.Add("meta edit: the editor's Set current text matches the landblock / landcell", SetCurrentMatches);
|
||||
r.Add("meta edit: a new state's Never -> None rule keeps it through a save and reload", NewStateSurvivesReload);
|
||||
}
|
||||
|
||||
private static void SetCurrentMatches()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
foreach (uint cell in new uint[] { 0xA9B4001Cu, 0x00070143u, 0x8B370105u, 0x0001FFFEu })
|
||||
{
|
||||
FakeHost.PlayerPose = (cell, 10f, 10f, 0f);
|
||||
var rig = new Rig(FakeHost.Create(), Player);
|
||||
string block = RynthCore.Engine.UI.Data.MetaLocation.Text(RynthCore.Engine.UI.Data.MetaLocation.LandblockCondition, cell)!;
|
||||
string here = RynthCore.Engine.UI.Data.MetaLocation.Text(RynthCore.Engine.UI.Data.MetaLocation.LandcellCondition, cell)!;
|
||||
Check.True(rig.Holds(C.Landblock_EQ, block), $"Landblock == {block} holds at {cell:X8}");
|
||||
Check.True(rig.Holds(C.Landcell_EQ, here), $"Landcell == {here} holds at {cell:X8}");
|
||||
FakeHost.PlayerPose = (cell + 0x00010000u, 10f, 10f, 0f);
|
||||
Check.False(rig.Holds(C.Landblock_EQ, block), $"not in the next landblock ({cell:X8})");
|
||||
FakeHost.PlayerPose = (cell + 1, 10f, 10f, 0f);
|
||||
Check.False(rig.Holds(C.Landcell_EQ, here), $"not in the next cell ({cell:X8})");
|
||||
}
|
||||
}
|
||||
|
||||
private static void NewStateSurvivesReload()
|
||||
{
|
||||
// What "+ New state..." adds (engine MetaRuleEdit.Placeholder): Never -> None in the new state.
|
||||
var rules = new List<MetaRule>
|
||||
{
|
||||
Rule("Default", C.Always, "", A.SetMetaState, "Loot"),
|
||||
new() { State = "Loot", Condition = C.Never, Action = A.None },
|
||||
};
|
||||
string text = AfFileWriter.SaveToString(rules, new Dictionary<string, List<string>>());
|
||||
var back = AfFileParser.LoadFromText(text);
|
||||
Check.Eq(back.Rules.Count, 2, "both rules back");
|
||||
var loot = back.Rules.FirstOrDefault(x => x.State == "Loot");
|
||||
Check.NotNull(loot, "the new state is still there");
|
||||
if (loot != null)
|
||||
{
|
||||
Check.Eq(loot.Condition, C.Never, "Never");
|
||||
Check.Eq(loot.Action, A.None, "None");
|
||||
}
|
||||
|
||||
// It never fires, and SetState into it just sits there.
|
||||
var rig = new Rig(rules: new[] { Rule("Default", C.Always, "", A.SetMetaState, "Loot"), Mark("Loot", C.Never, "", "x") });
|
||||
rig.Tick();
|
||||
rig.Tick(5);
|
||||
Check.Eq(rig.S.CurrentState, "Loot", "moved into the new state");
|
||||
Check.False(rig.Has("x"), "its Never rule never fires");
|
||||
}
|
||||
|
||||
// ── Panel edits on a running meta (MetaRuleEdits, update_rule; 2026-10-05 autosave) ─────
|
||||
|
||||
private static void EditKeepsRunningMeta()
|
||||
{
|
||||
var rig = new Rig(rules: new[]
|
||||
{
|
||||
Mark("Default", C.Always, "", "a"),
|
||||
Mark("Default", C.SecondsInState_GE, "10", "t"),
|
||||
});
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("a"), "1", "the Always rule fired on entry");
|
||||
rig.Tick(6);
|
||||
|
||||
// What the editor's autosave sends: an edited copy of rule 0, then the structural bump
|
||||
// TryAutoSaveMetaCmd makes.
|
||||
MetaRule edited = Mark("Default", C.Always, "", "a");
|
||||
edited.ActionData = "setvar[a, getvar[a]+10]";
|
||||
Check.True(MetaRuleEdits.Replace(rig.S.MetaRules, 0, edited), "replaced");
|
||||
rig.S.MetaRulesStructuralVersion++;
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("a"), "1", "the edited rule did not fire again (latch kept)");
|
||||
Check.Eq(rig.S.CurrentState, "Default", "state unchanged");
|
||||
Check.Near(rig.M.GetStateSnapshot().SecondsInState, 6, 1e-9, "seconds in state not restarted");
|
||||
rig.Tick(4.5);
|
||||
Check.Eq(rig.Var("t"), "1", "the 10 s rule fired on the original clock");
|
||||
|
||||
// A real state entry re-arms it, now with the edited action.
|
||||
rig.S.ForceStateReset = true;
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("a"), "11", "re-armed by a state entry, runs the edited action");
|
||||
|
||||
// Out of range: nothing changes.
|
||||
Check.False(MetaRuleEdits.Replace(rig.S.MetaRules, 5, Mark("Default", C.Never, "", "z")), "bad index refused");
|
||||
Check.Eq(rig.S.MetaRules.Count, 2, "rule count unchanged");
|
||||
|
||||
// Before the fix (a plain replace) the same edit fired the rule again.
|
||||
var old = new Rig(rules: new[] { Mark("Default", C.Always, "", "a") });
|
||||
old.Tick();
|
||||
old.S.MetaRules[0] = Mark("Default", C.Always, "", "a");
|
||||
old.S.MetaRulesStructuralVersion++;
|
||||
old.Tick();
|
||||
Check.Eq(old.Var("a"), "2", "a plain replace re-fires (what MetaRuleEdits prevents)");
|
||||
}
|
||||
|
||||
private static void EditKeepsHiddenFields()
|
||||
{
|
||||
var call = new MetaRule
|
||||
{
|
||||
State = "Default", Condition = C.ChatMessageCapture, ConditionData = "x", ChatColors = "2;4",
|
||||
Action = A.CallMetaState, ActionData = "Buff", CallReturnState = "Hunt",
|
||||
};
|
||||
var rules = new List<MetaRule> { call };
|
||||
// The panel's DTO carries neither field.
|
||||
var edited = new MetaRule { State = "Default", Condition = C.ChatMessageCapture, ConditionData = "y", Action = A.CallMetaState, ActionData = "Buff2" };
|
||||
MetaRuleEdits.Replace(rules, 0, edited);
|
||||
Check.Eq(rules[0].CallReturnState, "Hunt", "CallState return kept");
|
||||
Check.Eq(rules[0].ChatColors, "2;4", "ChatCapture colours kept");
|
||||
Check.Eq(rules[0].ActionData, "Buff2", "the edit applied");
|
||||
|
||||
// Changing the action / condition drops them.
|
||||
var other = new MetaRule { State = "Default", Condition = C.Always, Action = A.SetMetaState, ActionData = "Buff" };
|
||||
MetaRuleEdits.Replace(rules, 0, other);
|
||||
Check.Eq(rules[0].CallReturnState, "", "not a CallState any more");
|
||||
Check.Eq(rules[0].ChatColors, "", "not a ChatCapture any more");
|
||||
|
||||
// Nested: an All's ChatCapture child by position.
|
||||
var parent = new MetaRule { Condition = C.All, Children = { new MetaRule { Condition = C.ChatMessageCapture, ChatColors = "7" } } };
|
||||
var parentEdit = new MetaRule { Condition = C.All, Children = { new MetaRule { Condition = C.ChatMessageCapture, ConditionData = "z" } } };
|
||||
MetaRuleEdits.KeepHidden(parent, parentEdit);
|
||||
Check.Eq(parentEdit.Children[0].ChatColors, "7", "child colours kept");
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
|
|
|||
200
Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs
Normal file
200
Tools/RynthCore.RynthAiHostTests/Tests/MonsterEditorTests.cs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using RynthCore.MonsterEditor;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using EditorRule = RynthCore.MonsterEditor.MonsterRule;
|
||||
using PluginRule = RynthCore.Plugin.RynthAi.LegacyUi.MonsterRule;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The standalone Monster Editor (Tools/RynthCore.MonsterEditor; Models.cs, JsonContext.cs and
|
||||
// MonsterRulesFile.cs compiled in) reads and writes the plugin's monsters file. Before 2026-10-05
|
||||
// its MonsterRule had no Category or MatchExpression (or CustomDebuffs), so an editor save
|
||||
// dropped them and an expression rule fell back to matching by name only. Spotted by
|
||||
// Silentkelpie (rynth PR #1); re-implemented here. Every file goes through the plugin's own
|
||||
// serializer (RynthAiJsonContext) on the way in and out.
|
||||
internal static class MonsterEditorTests
|
||||
{
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("monster editor: a plugin file round-trips through the editor (every field kept)", RoundTripKeepsEveryField);
|
||||
r.Add("monster editor: Category and MatchExpression load, edit and save", CategoryAndMatchEditable);
|
||||
r.Add("monster editor: unknown fields survive, files without the new fields still load", UnknownAndOldFields);
|
||||
r.Add("monster editor: a character folder opens the plugin's MonsterProfiles file", FindsThePluginsFile);
|
||||
}
|
||||
|
||||
private static string Dir(string name)
|
||||
{
|
||||
string dir = Path.Combine(Program.TempRoot, "monster-editor", name);
|
||||
Directory.CreateDirectory(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static List<PluginRule> PluginRules() => new()
|
||||
{
|
||||
new PluginRule { Name = "Default", Priority = 1 },
|
||||
new PluginRule
|
||||
{
|
||||
Name = "Olthoi", Category = "Olthoi nest", MatchExpression = "getcharintprop[25]>=200",
|
||||
Priority = 3, DamageType = "Acid", WeaponId = 0x50001234, Fester = true, Broadside = true,
|
||||
GravityWell = true, Imperil = true, Yield = true, Vuln = true, UseArc = true, UseRing = true,
|
||||
UseStreak = true, UseBolt = false, UseBlast = true, ExVuln = "Fire", OffhandId = 2,
|
||||
PetDamage = "Cold", CustomDebuffs = "Corrosion Vulnerability Other, Fire Vulnerability Other VII",
|
||||
},
|
||||
new PluginRule { Name = "", Category = "Expression only", MatchExpression = "wobjectfindnearestbytemplatetype[1]" },
|
||||
};
|
||||
|
||||
private static string WriteAsPlugin(string dir, List<PluginRule> rules)
|
||||
{
|
||||
string path = Path.Combine(dir, "Toon.json");
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(rules, RynthAiJsonContext.Default.MonsterRuleList));
|
||||
return path;
|
||||
}
|
||||
|
||||
private static List<PluginRule> ReadAsPlugin(string path) =>
|
||||
JsonSerializer.Deserialize(File.ReadAllText(path), RynthAiJsonContext.Default.MonsterRuleList)!;
|
||||
|
||||
/// <summary>Every public property of the plugin's rule, compared one by one.</summary>
|
||||
private static void SameRules(List<PluginRule> actual, List<PluginRule> expected, string what)
|
||||
{
|
||||
Check.Eq(actual.Count, expected.Count, what + ": rule count");
|
||||
PropertyInfo[] props = typeof(PluginRule).GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
||||
Check.True(props.Any(p => p.Name == "MatchExpression") && props.Any(p => p.Name == "Category"), "the plugin's rule has both fields");
|
||||
for (int i = 0; i < Math.Min(actual.Count, expected.Count); i++)
|
||||
foreach (PropertyInfo p in props)
|
||||
Check.Eq(p.GetValue(actual[i])?.ToString(), p.GetValue(expected[i])?.ToString(), $"{what}: rule {i} {p.Name}");
|
||||
}
|
||||
|
||||
private static void RoundTripKeepsEveryField()
|
||||
{
|
||||
List<PluginRule> original = PluginRules();
|
||||
string path = WriteAsPlugin(Dir("roundtrip"), original);
|
||||
|
||||
// Open in the editor, change one thing (as a grid edit does), save.
|
||||
List<EditorRule> rules = MonsterRulesFile.Load(path);
|
||||
Check.Eq(rules.Count, 3, "editor loads every rule");
|
||||
rules[1].Priority = 4;
|
||||
MonsterRulesFile.Save(path, rules);
|
||||
|
||||
List<PluginRule> back = ReadAsPlugin(path);
|
||||
original[1].Priority = 4;
|
||||
SameRules(back, original, "after an editor save");
|
||||
|
||||
// A second save with no edits changes nothing more.
|
||||
MonsterRulesFile.Save(path, MonsterRulesFile.Load(path));
|
||||
SameRules(ReadAsPlugin(path), original, "after a second save");
|
||||
string json = File.ReadAllText(path);
|
||||
Check.Eq(CountOf(json, "\"MatchExpression\""), 3, "MatchExpression written once per rule");
|
||||
Check.Eq(CountOf(json, "\"CustomDebuffs\""), 3, "CustomDebuffs written once per rule");
|
||||
}
|
||||
|
||||
private static void CategoryAndMatchEditable()
|
||||
{
|
||||
string path = WriteAsPlugin(Dir("edit"), PluginRules());
|
||||
List<EditorRule> rules = MonsterRulesFile.Load(path);
|
||||
Check.Eq(rules[1].Category, "Olthoi nest", "Category read");
|
||||
Check.Eq(rules[1].MatchExpression, "getcharintprop[25]>=200", "MatchExpression read");
|
||||
|
||||
var changed = new List<string>();
|
||||
rules[1].PropertyChanged += (_, e) => changed.Add(e.PropertyName ?? "");
|
||||
rules[1].MatchExpression = ""; // back to matching by name
|
||||
rules[1].Category = null!; // a cleared grid cell
|
||||
Check.True(changed.Contains("MatchExpression") && changed.Contains("Category"), "edits raise PropertyChanged (the editor saves on it)");
|
||||
rules[2].MatchExpression = "true";
|
||||
MonsterRulesFile.Save(path, rules);
|
||||
|
||||
List<PluginRule> back = ReadAsPlugin(path);
|
||||
Check.Eq(back[1].MatchExpression, "", "cleared expression saved");
|
||||
Check.Eq(back[1].Category, "", "a null Category is saved as empty");
|
||||
Check.Eq(back[2].MatchExpression, "true", "edited expression saved");
|
||||
Check.Eq(back[2].Category, "Expression only", "untouched Category kept");
|
||||
|
||||
// A rule added in the editor carries the plugin's defaults for the new fields.
|
||||
var added = new EditorRule { Name = "Drudge" };
|
||||
Check.Eq(added.Category, "", "new rule: empty Category");
|
||||
Check.Eq(added.MatchExpression, "", "new rule: empty MatchExpression (by name)");
|
||||
}
|
||||
|
||||
private static void UnknownAndOldFields()
|
||||
{
|
||||
string dir = Dir("unknown");
|
||||
string path = Path.Combine(dir, "Toon.json");
|
||||
// A field neither side knows yet (a later plugin), a nested value, and a file from before
|
||||
// Category/MatchExpression existed (no such keys at all).
|
||||
File.WriteAllText(path, """
|
||||
[
|
||||
{ "Name": "Default", "Priority": 1 },
|
||||
{ "Name": "Mosswart", "Priority": 2, "FutureField": { "A": [1, 2], "B": null }, "Shout": "hi" }
|
||||
]
|
||||
""");
|
||||
List<EditorRule> rules = MonsterRulesFile.Load(path);
|
||||
Check.Eq(rules[1].Category, "", "old file: Category empty");
|
||||
Check.Eq(rules[1].MatchExpression, "", "old file: MatchExpression empty");
|
||||
MonsterRulesFile.Save(path, rules);
|
||||
|
||||
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
|
||||
JsonElement mosswart = doc.RootElement[1];
|
||||
Check.True(mosswart.TryGetProperty("FutureField", out JsonElement future), "unknown field kept");
|
||||
Check.Eq(future.GetRawText().Replace(" ", "").Replace("\r", "").Replace("\n", ""), """{"A":[1,2],"B":null}""", "unknown field value unchanged");
|
||||
Check.Eq(mosswart.GetProperty("Shout").GetString(), "hi", "unknown string kept");
|
||||
Check.Eq(ReadAsPlugin(path)[1].Priority, 2, "the plugin still reads the file");
|
||||
}
|
||||
|
||||
// The plugin launches the editor with the character's settings folder
|
||||
// (SettingsProfiles\<server>\<character>) but reads MonsterProfiles\<server>\<character>.json
|
||||
// (LegacyDashboardRenderer.MonstersFilePath); the editor used to open <folder>\monsters.json.
|
||||
private static void FindsThePluginsFile()
|
||||
{
|
||||
string root = Dir("paths");
|
||||
string Rel(params string[] parts) => Path.Combine(new[] { root }.Concat(parts).ToArray());
|
||||
string aelChar = Rel("SettingsProfiles", "Aelrynth", "Toon");
|
||||
string aceChar = Rel("SettingsProfiles", "ACEmulator", "Toon");
|
||||
Directory.CreateDirectory(aelChar);
|
||||
Directory.CreateDirectory(aceChar);
|
||||
string aelFile = Rel("MonsterProfiles", "Aelrynth", "Toon.json");
|
||||
string aceFile = Rel("MonsterProfiles", "Toon.json");
|
||||
|
||||
// Not there yet: the plugin's path (a save creates it where the plugin reads).
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), aelFile, "server folder -> MonsterProfiles\\<server>\\<char>.json");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aceChar + "\\"), aceFile, "ACEmulator -> MonsterProfiles\\<char>.json (trailing slash ok)");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath("\"" + aelChar + "\""), aelFile, "quoted argument");
|
||||
|
||||
// Only the old file exists: that one (the plugin moves it across at its next load).
|
||||
string legacy = Path.Combine(aelChar, "monsters.json");
|
||||
File.WriteAllText(legacy, "[]");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), legacy, "only the old monsters.json: use it");
|
||||
|
||||
// Both: the plugin's.
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(aelFile)!);
|
||||
File.WriteAllText(aelFile, "[]");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aelChar), aelFile, "both exist: the plugin's file");
|
||||
|
||||
// A file is edited as given; a folder outside SettingsProfiles keeps the old behaviour.
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(aelFile), aelFile, "a file opens as is");
|
||||
string loose = Rel("Elsewhere", "Toon");
|
||||
Check.Eq(MonsterRulesFile.ResolveRulesPath(loose), Path.Combine(loose, "monsters.json"), "unknown layout: <folder>\\monsters.json");
|
||||
|
||||
// And back: the settings folder for the weapon list.
|
||||
Check.Eq(MonsterRulesFile.CharFolderForRulesPath(aelFile), aelChar, "MonsterProfiles\\<server> file -> its settings folder");
|
||||
Check.Eq(MonsterRulesFile.CharFolderForRulesPath(aceFile), aceChar, "MonsterProfiles file -> SettingsProfiles\\ACEmulator");
|
||||
Check.Eq(MonsterRulesFile.CharFolderForRulesPath(legacy), aelChar, "old monsters.json -> its own folder");
|
||||
Check.Eq(MonsterRulesFile.CharFolderForRulesPath(Rel("Elsewhere", "x.json")), Rel("Elsewhere"), "unknown layout -> the file's folder");
|
||||
|
||||
// The plugin's own path for this character agrees.
|
||||
Check.Eq(MonsterRulesFile.PluginRulesPathForCharFolder(aelChar), aelFile, "PluginRulesPathForCharFolder");
|
||||
Check.Null(MonsterRulesFile.PluginRulesPathForCharFolder(loose), "not under SettingsProfiles: null");
|
||||
}
|
||||
|
||||
private static int CountOf(string text, string what)
|
||||
{
|
||||
int n = 0;
|
||||
for (int i = text.IndexOf(what, StringComparison.Ordinal); i >= 0; i = text.IndexOf(what, i + what.Length, StringComparison.Ordinal))
|
||||
n++;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
|
@ -54,7 +54,7 @@ internal static class NavEngineTests
|
|||
|
||||
r.Add("nav point reach: values under 1.5 yd work (it used to be floored at 1.5)", ReachBelowOneAndAHalf);
|
||||
r.Add("nav point reach: a doorway point is reached within 1 yd, its sweep pass within 1.5 yd", DoorwayPointTight);
|
||||
r.Add("nav point reach: no lookahead corner cut at a doorway point", DoorwayNoLookahead);
|
||||
r.Add("nav point reach: no lookahead corner cut at a doorway point (or at a small reach)", DoorwayNoLookahead);
|
||||
r.Add("nav point reach: Follow stops within it and moves again 3 yd farther out", FollowUsesReach);
|
||||
r.Add("nav point reach: metas set it as FollowNavMin (yd) or VTank's NavCloseStopRange (x240)", ReachFromMetas);
|
||||
|
||||
|
|
@ -746,18 +746,27 @@ internal static class NavEngineTests
|
|||
|
||||
private static void DoorwayNoLookahead()
|
||||
{
|
||||
// 3 yd short of a point, the next one due east: a plain point blends the aim east
|
||||
// (4 yd lookahead), a doorway point keeps aiming straight at itself.
|
||||
// 3 yd short of a point, the next one due east, with a 2.8 yd reach (big enough to round
|
||||
// corners: 3.6 yd of lookahead): a plain point blends the aim east, a doorway point keeps
|
||||
// aiming straight at itself. At the 1.5 yd default reach there is no rounding at all
|
||||
// (the lookahead scales with the reach since 2026-10-05, see NavReachTests).
|
||||
foreach (bool doorway in new[] { false, true })
|
||||
{
|
||||
FakeHost.Reset(); At(7, 0); Face(10, 0);
|
||||
var first = doorway ? Door(10, 0) : Pt(10, 0);
|
||||
var nav = new Nav(Route(RT.Circular, first, Pt(10, 10)));
|
||||
nav.S.FollowNavMin = 2.8f;
|
||||
nav.Tick();
|
||||
double h = FakeHost.HeadingDeg;
|
||||
if (doorway) Check.True(h < 1.0 || h > 359.0, $"doorway point: still heading north ({h:F1})");
|
||||
else Check.True(h > 3.0 && h < 90.0, $"plain point: turning east early ({h:F1})");
|
||||
}
|
||||
|
||||
FakeHost.Reset(); At(8, 0); Face(10, 0);
|
||||
var dflt = new Nav(Route(RT.Circular, Pt(10, 0), Pt(10, 10)));
|
||||
dflt.Tick();
|
||||
double hd = FakeHost.HeadingDeg;
|
||||
Check.True(hd < 1.0 || hd > 359.0, $"1.5 yd default reach, 2 yd short: a plain point is walked straight at too ({hd:F1})");
|
||||
}
|
||||
|
||||
private static void FollowUsesReach()
|
||||
|
|
|
|||
263
Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs
Normal file
263
Tools/RynthCore.RynthAiHostTests/Tests/NavOverlayTests.cs
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType;
|
||||
using RT = RynthCore.Plugin.RynthAi.LegacyUi.NavRouteType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Nav3D waypoint labels and guide line (Silentkelpie's rynth PR #1 idea, re-implemented on our
|
||||
// pump-thread Nav3D markers). Both settings are off by default and then change nothing. Labels
|
||||
// are filled strokes (Nav3D triangles) on an upright plane facing the character; the guide is
|
||||
// one Nav3D line from the character's feet to the waypoint nav is heading for. The frame is
|
||||
// built from the route on the plugin tick and the emit reads only the frame.
|
||||
internal static class NavOverlayTests
|
||||
{
|
||||
private const double NS0 = 42.0, EW0 = 33.0;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("nav overlay: both settings off by default - markers draw exactly as before", OffByDefault);
|
||||
r.Add("nav overlay: number labels over nearby waypoints, upright, facing the character, readable left to right", NumberLabels);
|
||||
r.Add("nav overlay: names mode names jumps and checkpoints and hangs actions on the point before", NamesMode);
|
||||
r.Add("nav overlay: labels only within range, active point first, nearest next, capped", LabelRangeAndCap);
|
||||
r.Add("nav overlay: the guide line runs from the character's feet to the active waypoint, not to an action point", GuideLine);
|
||||
r.Add("nav overlay: the frame is a snapshot - emptying the route afterwards changes nothing", FrameIsSnapshot);
|
||||
r.Add("nav overlay: the label triangle budget holds for long names", TriangleBudget);
|
||||
r.Add("nav overlay: settings round-trip; an older engine's payload leaves them alone", SettingsRoundTrip);
|
||||
}
|
||||
|
||||
// ── Rig ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static NavPoint Pt(double north, double east, T type = T.Point)
|
||||
=> new() { Type = type, NS = NS0 + north / 240.0, EW = EW0 + east / 240.0 };
|
||||
|
||||
private static NavRouteParser Route(params NavPoint[] pts)
|
||||
{
|
||||
var r = new NavRouteParser { RouteType = RT.Linear };
|
||||
r.Points.AddRange(pts);
|
||||
return r;
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly NavMarkerRenderer R;
|
||||
public readonly float Px, Py; // the player's landblock-local metres (east, north)
|
||||
|
||||
public Rig(NavRouteParser route, int labels = 0, bool guide = false, int active = 0)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.Nav3DCalls = true;
|
||||
FakeHost.SetNavPosition(NS0, EW0);
|
||||
Px = FakeHost.PlayerPose.X;
|
||||
Py = FakeHost.PlayerPose.Y;
|
||||
S = new LegacyUiSettings { CurrentRoute = route, ActiveNavIndex = active, NavHeightOffset = 0f, NavSlopeSink = 0f };
|
||||
if (labels != 0) S.NavLabelMode = labels;
|
||||
if (guide) S.NavGuideLine = true;
|
||||
R = new NavMarkerRenderer(FakeHost.Create(), S);
|
||||
}
|
||||
|
||||
public void Submit()
|
||||
{
|
||||
FakeHost.Nav3DRings.Clear(); FakeHost.Nav3DLines.Clear(); FakeHost.Nav3DTriangles.Clear();
|
||||
R.SubmitNav3D();
|
||||
}
|
||||
|
||||
/// <summary>World position (Nav3D frame) of a point north/east of the player, in metres.</summary>
|
||||
public (float X, float Z) At(double north, double east) => (Px + (float)east, Py + (float)north);
|
||||
}
|
||||
|
||||
private sealed class Recorder : INav3DSink
|
||||
{
|
||||
public readonly List<float[]> Lines = new();
|
||||
public readonly List<float[]> Tris = new();
|
||||
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float t, uint c) => Lines.Add(new[] { x1, y1, z1, x2, y2, z2 });
|
||||
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint c)
|
||||
=> Tris.Add(new[] { x1, y1, z1, x2, y2, z2, x3, y3, z3 });
|
||||
}
|
||||
|
||||
private static IEnumerable<(float X, float Y, float Z)> Vertices(IEnumerable<float[]> tris)
|
||||
{
|
||||
foreach (float[] t in tris)
|
||||
for (int i = 0; i < 9; i += 3) yield return (t[i], t[i + 1], t[i + 2]);
|
||||
}
|
||||
|
||||
// ── Tests ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void OffByDefault()
|
||||
{
|
||||
var d = new LegacyUiSettings();
|
||||
Check.Eq(d.NavLabelMode, NavLabelModes.Off, "labels default off");
|
||||
Check.False(d.NavGuideLine, "guide line default off");
|
||||
|
||||
var rig = new Rig(Route(Pt(5, 0), Pt(10, 0), Pt(10, 6)));
|
||||
rig.Submit();
|
||||
Check.Eq(FakeHost.Nav3DRings.Count, 3, "three rings");
|
||||
Check.Eq(FakeHost.Nav3DLines.Count, 2, "two route lines, nothing more");
|
||||
Check.Eq(FakeHost.Nav3DTriangles.Count, 0, "no label triangles");
|
||||
Check.True(FakeHost.Nav3DLines.All(l => l.Color == 0xFF0088FF), "only route-coloured lines");
|
||||
}
|
||||
|
||||
private static void NumberLabels()
|
||||
{
|
||||
// One waypoint 10 m north, one 10 m east.
|
||||
var rig = new Rig(Route(Pt(10, 0), Pt(0, 10)), labels: NavLabelModes.Numbers);
|
||||
rig.Submit();
|
||||
Check.True(FakeHost.Nav3DTriangles.Count > 0, "labels drawn as triangles");
|
||||
Check.Eq(FakeHost.Nav3DLines.Count, 1, "the route line only (labels use no lines)");
|
||||
|
||||
var (nx, nz) = rig.At(10, 0);
|
||||
var (ex, ez) = rig.At(0, 10);
|
||||
var north = FakeHost.Nav3DTriangles.Where(t => Math.Abs(t.Z1 - nz) < 2f && Math.Abs(t.X1 - nx) < 2f).ToList();
|
||||
var east = FakeHost.Nav3DTriangles.Where(t => Math.Abs(t.X1 - ex) < 2f && Math.Abs(t.Z1 - ez) < 2f).ToList();
|
||||
Check.Eq(north.Count + east.Count, FakeHost.Nav3DTriangles.Count, "every triangle belongs to one of the two labels");
|
||||
Check.True(north.Count > 0 && east.Count > 0, "both waypoints labelled");
|
||||
// Facing the character: the north label's plane is east-west (one Z), the east one's north-south (one X).
|
||||
Check.True(north.All(t => Math.Abs(t.Z1 - nz) < 1e-3 && Math.Abs(t.Z2 - nz) < 1e-3 && Math.Abs(t.Z3 - nz) < 1e-3), "north label faces south, toward you");
|
||||
Check.True(east.All(t => Math.Abs(t.X1 - ex) < 1e-3 && Math.Abs(t.X2 - ex) < 1e-3 && Math.Abs(t.X3 - ex) < 1e-3), "east label faces west, toward you");
|
||||
// Upright and above the ring.
|
||||
Check.True(north.All(t => t.Y1 >= 0.9f && t.Y2 >= 0.9f && t.Y3 >= 0.9f), "above the ring");
|
||||
float minY = north.Min(t => Math.Min(t.Y1, Math.Min(t.Y2, t.Y3))), maxY = north.Max(t => Math.Max(t.Y1, Math.Max(t.Y2, t.Y3)));
|
||||
Check.True(maxY - minY > 0.3f, "has height (upright)");
|
||||
|
||||
// Readable from the character: "12" north of you runs west to east ('1' left of '2').
|
||||
var rec = new Recorder();
|
||||
var frame = new NavOverlayFrame(new[] { new NavLabel(0f, 0f, 10f, "12", 0, NavOverlay.LabelColor) }, null, 0f, 0f, 0f);
|
||||
NavOverlay.EmitLabels(frame, rec);
|
||||
int oneTris = NavStrokeFont.Glyph('1')!.Sum(p => p.Length / 2 - 1) * 2;
|
||||
float oneX = Vertices(rec.Tris.Take(oneTris)).Average(v => v.X);
|
||||
float twoX = Vertices(rec.Tris.Skip(oneTris)).Average(v => v.X);
|
||||
Check.True(oneX < twoX, $"'1' is west of '2' seen from the south ({oneX:0.00} < {twoX:0.00})");
|
||||
// Seen looking east, left-to-right is north to south.
|
||||
rec = new Recorder();
|
||||
NavOverlay.EmitLabels(new NavOverlayFrame(new[] { new NavLabel(10f, 0f, 0f, "12", 0, NavOverlay.LabelColor) }, null, 0f, 0f, 0f), rec);
|
||||
float oneZ = Vertices(rec.Tris.Take(oneTris)).Average(v => v.Z), twoZ = Vertices(rec.Tris.Skip(oneTris)).Average(v => v.Z);
|
||||
Check.True(oneZ > twoZ, "looking east, '1' is north of '2'");
|
||||
// Far labels are bigger.
|
||||
Check.True(NavOverlay.LineHeight(50f) > NavOverlay.LineHeight(5f), "a far label is drawn taller");
|
||||
}
|
||||
|
||||
private static void NamesMode()
|
||||
{
|
||||
var pts = new List<NavPoint>
|
||||
{
|
||||
Pt(5, 0), // 0
|
||||
new() { Type = T.Chat, ChatCommand = "/vt stop" }, // 1
|
||||
new() { Type = T.Recall, SpellId = 2645 }, // 2
|
||||
Pt(10, 0, T.Checkpoint), // 3
|
||||
Pt(12, 0, T.Jump), // 4
|
||||
new() { Type = T.PortalNPC, TargetName = "Gateway" }, // 5
|
||||
new() { Type = T.Pause, PauseTimeMs = 2500 }, // 6
|
||||
new() { Type = T.Npc, TargetName = "Town Crier" }, // 7
|
||||
new() { Type = T.OpenVendor, TargetName = "Shopkeeper" }, // 8
|
||||
};
|
||||
var text = NavOverlay.BuildText(pts, pts, NavLabelModes.Names, id => id == 2645 ? "Portal Recall" : "?");
|
||||
Check.Eq(text.Own[0], "0", "plain point: its number");
|
||||
Check.True(text.Own[1] == null && text.Own[2] == null, "action points get no label of their own");
|
||||
Check.Eq(string.Join("|", text.Actions[0] ?? Array.Empty<string>()), "1 CHAT /VT STOP|2 PORTAL RECALL", "actions hang on the point before");
|
||||
Check.Eq(text.Own[3], "3 CHECKPOINT", "checkpoint named");
|
||||
Check.Eq(text.Own[4], "4 JUMP", "jump named");
|
||||
Check.Eq(string.Join("|", text.Actions[4] ?? Array.Empty<string>()), "5 PORTAL GATEWAY|6 PAUSE 2.5S|7 NPC TOWN CRIER|...",
|
||||
"at most three action lines, then ...");
|
||||
|
||||
var numbers = NavOverlay.BuildText(pts, pts, NavLabelModes.Numbers, _ => "");
|
||||
Check.Eq(numbers.Own[4], "4", "numbers mode: just the number");
|
||||
Check.True(numbers.Actions.All(a => a == null), "numbers mode: no action lines");
|
||||
|
||||
// Drawn: the action lines stack above the point's own line.
|
||||
var rig = new Rig(Route(pts.ToArray()), labels: NavLabelModes.Names);
|
||||
var frame = rig.R.BuildOverlay(rig.S.CurrentRoute!, rig.Px, rig.Py, 0f, NS0, EW0, 0f);
|
||||
var at0 = frame.Labels.Where(l => l.Text.StartsWith("0", StringComparison.Ordinal) || l.Text.StartsWith("1 ", StringComparison.Ordinal) || l.Text.StartsWith("2 ", StringComparison.Ordinal)).ToList();
|
||||
Check.Eq(string.Join("|", at0.Select(l => $"{l.Row}:{l.Text}")), "0:0|1:1 CHAT /VT STOP|2:2 PORTAL RECALL", "rows 0, 1, 2 over point 0");
|
||||
Check.True(at0.Skip(1).All(l => l.Color == NavOverlay.ActionLabelColor), "action lines in their own colour");
|
||||
}
|
||||
|
||||
private static void LabelRangeAndCap()
|
||||
{
|
||||
// 40 points in a line northwards, 2 m apart (0..78 m): 31 of them within 60 m.
|
||||
var pts = Enumerable.Range(0, 40).Select(i => Pt(2 * i, 0)).ToArray();
|
||||
var rig = new Rig(Route(pts), labels: NavLabelModes.Numbers, active: 5);
|
||||
var frame = rig.R.BuildOverlay(rig.S.CurrentRoute!, rig.Px, rig.Py, 0f, NS0, EW0, 0f);
|
||||
Check.Eq(frame.Labels.Count, NavOverlay.MaxLabelLines, "capped at the line budget");
|
||||
Check.Eq(frame.Labels[0].Text, "5", "the active point first");
|
||||
Check.Eq(frame.Labels[0].Color, NavOverlay.ActiveLabelColor, "in the active colour");
|
||||
Check.Eq(frame.Labels[1].Text, "0", "then the nearest");
|
||||
Check.True(frame.Labels.All(l => Math.Abs(l.Z - rig.Py) <= NavOverlay.LabelRange + 0.01f), "all within range");
|
||||
|
||||
var few = new Rig(Route(Pt(10, 0), Pt(100, 0)), labels: NavLabelModes.Numbers);
|
||||
var f2 = few.R.BuildOverlay(few.S.CurrentRoute!, few.Px, few.Py, 0f, NS0, EW0, 0f);
|
||||
Check.Eq(string.Join(",", f2.Labels.Select(l => l.Text)), "0", "a point 100 m away gets no label");
|
||||
}
|
||||
|
||||
private static void GuideLine()
|
||||
{
|
||||
var rig = new Rig(Route(Pt(5, 0), Pt(10, 4)), guide: true, active: 1);
|
||||
rig.Submit();
|
||||
Check.Eq(FakeHost.Nav3DLines.Count, 2, "the route line plus the guide");
|
||||
var g = FakeHost.Nav3DLines[0];
|
||||
Check.Eq(g.Color, NavOverlay.GuideColor, "the guide goes in first (never crowded out)");
|
||||
var (tx, tz) = rig.At(10, 4);
|
||||
Check.True(Math.Abs(g.X1 - rig.Px) < 1e-3 && Math.Abs(g.Z1 - rig.Py) < 1e-3, "starts at the character");
|
||||
Check.True(Math.Abs(g.X2 - tx) < 1e-3 && Math.Abs(g.Z2 - tz) < 1e-3, "ends at the active waypoint");
|
||||
Check.True(g.Y1 > 0f && g.Y1 < 0.5f, "at the feet, lifted a little");
|
||||
Check.Eq(FakeHost.Nav3DTriangles.Count, 0, "labels stay off");
|
||||
|
||||
var chat = new Rig(Route(Pt(5, 0), new NavPoint { Type = T.Chat, ChatCommand = "hi" }, Pt(10, 0)), guide: true, active: 1);
|
||||
chat.Submit();
|
||||
Check.False(FakeHost.Nav3DLines.Any(l => l.Color == NavOverlay.GuideColor), "no guide to an action point (placeholder coordinates)");
|
||||
}
|
||||
|
||||
private static void FrameIsSnapshot()
|
||||
{
|
||||
var route = Route(Pt(5, 0), Pt(10, 0), Pt(15, 0));
|
||||
var rig = new Rig(route, labels: NavLabelModes.Numbers, guide: true, active: 2);
|
||||
NavOverlayFrame frame = rig.R.BuildOverlay(route, rig.Px, rig.Py, 0f, NS0, EW0, 0f);
|
||||
var before = new Recorder();
|
||||
NavOverlay.EmitGuide(frame, before, 0.06f);
|
||||
NavOverlay.EmitLabels(frame, before);
|
||||
|
||||
route.Points.Clear(); // what a reload or an edit on another thread would do
|
||||
var after = new Recorder();
|
||||
NavOverlay.EmitGuide(frame, after, 0.06f);
|
||||
NavOverlay.EmitLabels(frame, after);
|
||||
Check.Eq(after.Tris.Count, before.Tris.Count, "same label triangles from the frame");
|
||||
Check.Eq(after.Lines.Count, 1, "same guide line");
|
||||
Check.True(before.Tris.Zip(after.Tris).All(p => p.First.SequenceEqual(p.Second)), "identical geometry");
|
||||
Check.False(frame.Labels is List<NavLabel>, "labels are not a list anyone can grow");
|
||||
|
||||
rig.Submit();
|
||||
Check.Eq(FakeHost.Nav3DTriangles.Count + FakeHost.Nav3DLines.Count + FakeHost.Nav3DRings.Count, 0, "an empty route draws nothing next tick");
|
||||
}
|
||||
|
||||
private static void TriangleBudget()
|
||||
{
|
||||
var labels = Enumerable.Range(0, NavOverlay.MaxLabelLines)
|
||||
.Select(i => new NavLabel(0f, 0f, 5f + i, "WWWWWWWWWWWWWWWWWWWWWW", 0, NavOverlay.LabelColor)).ToArray();
|
||||
var rec = new Recorder();
|
||||
int used = NavOverlay.EmitLabels(new NavOverlayFrame(labels, null, 0f, 0f, 0f), rec);
|
||||
Check.True(used <= NavOverlay.MaxLabelTriangles && rec.Tris.Count == used, $"at most {NavOverlay.MaxLabelTriangles} triangles ({used})");
|
||||
Check.True(used > NavOverlay.MaxLabelTriangles - 20, "and the budget is used, not cut short");
|
||||
}
|
||||
|
||||
private static void SettingsRoundTrip()
|
||||
{
|
||||
var s = new LegacyUiSettings { NavLabelMode = NavLabelModes.Names, NavGuideLine = true };
|
||||
string json = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
var back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings)!;
|
||||
Check.Eq(back.NavLabelMode, NavLabelModes.Names, "label mode saved per character");
|
||||
Check.True(back.NavGuideLine, "guide line saved per character");
|
||||
|
||||
var old = JsonSerializer.Deserialize("{\"NavRingThickness\":6}", RynthAiJsonContext.Default.SettingsBridgePayload)!;
|
||||
Check.Eq(old.NavLabelMode, -1, "an older engine's payload: label mode absent (-1, kept)");
|
||||
Check.Null(old.NavGuideLine, "an older engine's payload: guide line absent (null, kept)");
|
||||
|
||||
Check.Eq(NavLabelModes.Clamp(7), NavLabelModes.Off, "a bad mode reads as off");
|
||||
}
|
||||
}
|
||||
261
Tools/RynthCore.RynthAiHostTests/Tests/NavReachTests.cs
Normal file
261
Tools/RynthCore.RynthAiHostTests/Tests/NavReachTests.cs
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
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;
|
||||
using T = RynthCore.Plugin.RynthAi.LegacyUi.NavPointType;
|
||||
using RT = RynthCore.Plugin.RynthAi.LegacyUi.NavRouteType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// The nav point reach (FollowNavMin) really decides how close nav gets to each point before it
|
||||
// turns for the next (Tom, 2026-10-05: "at 1.0 it should pretty much go directly to it. It gets
|
||||
// to it, passes it and turns around to go back"; "it's turning too early and running into walls").
|
||||
//
|
||||
// Unlike NavEngineTests, where the fake character only moves when a test puts it somewhere, these
|
||||
// walk it: each nav tick (33 ms) the character runs forward along FakeHost.HeadingDeg while nav
|
||||
// has autorun on (using the autorun state from the tick before, so a stop takes a tick to land,
|
||||
// as in the game). Nav turns it with TurnToHeading, rate-limited to the turn-rate setting.
|
||||
//
|
||||
// The corner: a corridor 2 yd wide runs north from the origin to a point 20 yd north, then east.
|
||||
// Its inside wall corner is at (19 N, 1 E): any step with north < 19 and east > 1 went through it.
|
||||
internal static class NavReachTests
|
||||
{
|
||||
private const double NS0 = 42.0, EW0 = 33.0;
|
||||
private static long _now;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("nav reach: 1 yd at a 90 degree corner by a wall - touches the point, then turns, no corner cut", CornerTightReach);
|
||||
r.Add("nav reach: the corner rounding scales with the reach - none up to the 1.5 yd default, the Lookahead setting at 3 yd+", CornerRoundingScales);
|
||||
r.Add("nav reach: 5 yd still rounds a corner (moves on 5 yd out and heads across)", CornerWideReach);
|
||||
r.Add("nav reach: going past a point on the side counts as reached - no turning round", PassBySide);
|
||||
r.Add("nav reach: a corner cut never counts as passing (the point must be behind)", CutIsNotAPass);
|
||||
r.Add("nav reach: fast run at a low frame rate skips over a 0.5 yd reach - counted, no turning round", FastRunSkipsOver);
|
||||
r.Add("nav reach: the sweep pass uses the closest approach, not the last tick", SweepUsesClosest);
|
||||
r.Add("nav reach: doorway points unchanged - 1 yd reach, no pass-through, no rounding", DoorwayUnchanged);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private static NavPoint Pt(double north, double east, bool doorway = false)
|
||||
=> new() { Type = T.Point, NS = NS0 + north / 240.0, EW = EW0 + east / 240.0, Doorway = doorway };
|
||||
|
||||
private static NavRouteParser Route(RT type, params NavPoint[] pts)
|
||||
{
|
||||
var r = new NavRouteParser { RouteType = type };
|
||||
r.Points.AddRange(pts);
|
||||
return r;
|
||||
}
|
||||
|
||||
private sealed class Walk
|
||||
{
|
||||
public readonly LegacyUiSettings S;
|
||||
public readonly NavigationEngine E;
|
||||
public double N, E_;
|
||||
public double SpeedYdPerS = 11.0; // a good run skill
|
||||
public int TickMs = 33;
|
||||
public readonly List<(double N, double E, int Idx, bool Run)> Path = new();
|
||||
|
||||
public Walk(NavRouteParser route, float reach, double north, double east, double faceDeg)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
_now = 1_000_000;
|
||||
NavigationEngine.Clock = static () => _now;
|
||||
N = north; E_ = east;
|
||||
FakeHost.SetNavPosition(NS0 + N / 240.0, EW0 + E_ / 240.0);
|
||||
FakeHost.HeadingDeg = faceDeg;
|
||||
S = new LegacyUiSettings
|
||||
{
|
||||
IsMacroRunning = true, EnableNavigation = true, CurrentRoute = route, ActiveNavIndex = 0,
|
||||
FollowNavMin = reach,
|
||||
};
|
||||
E = new NavigationEngine(FakeHost.Create(), S);
|
||||
}
|
||||
|
||||
public int Idx => S.ActiveNavIndex;
|
||||
|
||||
/// <summary>One nav tick, then the character moves for one tick if autorun is on.</summary>
|
||||
public void Step()
|
||||
{
|
||||
_now += TickMs;
|
||||
bool run = FakeHost.AutoRun; // what the client was doing going into this tick
|
||||
E.Tick();
|
||||
if (run)
|
||||
{
|
||||
double h = FakeHost.HeadingDeg * Math.PI / 180.0, d = SpeedYdPerS * TickMs / 1000.0;
|
||||
N += d * Math.Cos(h);
|
||||
E_ += d * Math.Sin(h);
|
||||
FakeHost.SetNavPosition(NS0 + N / 240.0, EW0 + E_ / 240.0);
|
||||
}
|
||||
Path.Add((N, E_, Idx, FakeHost.AutoRun));
|
||||
}
|
||||
|
||||
public void RunUntil(Func<bool> done, double maxSeconds = 20)
|
||||
{
|
||||
int n = (int)(maxSeconds * 1000 / TickMs);
|
||||
for (int i = 0; i < n && !done(); i++) Step();
|
||||
}
|
||||
}
|
||||
|
||||
private static double Dist(double n0, double e0, double n1, double e1) => Math.Sqrt((n1 - n0) * (n1 - n0) + (e1 - e0) * (e1 - e0));
|
||||
|
||||
private static int LogCount(string contains) => FakeHost.Logs.Count(l => l.Contains(contains));
|
||||
|
||||
/// <summary>Corridor north 20 yd then east 20 yd; returns the walk after it moved on from the corner.</summary>
|
||||
private static Walk Corner(float reach, float lookahead = 4.0f)
|
||||
{
|
||||
var w = new Walk(Route(RT.Once, Pt(20, 0), Pt(20, 20), Pt(20, 40)), reach, 0, 0, 0);
|
||||
w.S.NavLookaheadYards = lookahead;
|
||||
w.RunUntil(() => w.Idx >= 1 && w.E_ > 6);
|
||||
return w;
|
||||
}
|
||||
|
||||
private static double ClosestToCorner(Walk w) => w.Path.Min(p => Dist(p.N, p.E, 20, 0));
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private static void CornerTightReach()
|
||||
{
|
||||
var w = Corner(1.0f);
|
||||
Check.True(w.Idx >= 1, "moved on to the east leg");
|
||||
var onCorner = w.Path.Where(p => p.Idx == 0).ToList();
|
||||
var first = w.Path.FirstOrDefault(p => p.Idx >= 1);
|
||||
double atAdvance = Dist(first.N, first.E, 20, 0);
|
||||
Check.True(atAdvance <= 1.0, $"moved on within 1 yd of the corner point ({atAdvance:F2} yd)");
|
||||
double closest = ClosestToCorner(w);
|
||||
Check.True(closest <= 0.5, $"touched the point: came within {closest:F2} yd of it");
|
||||
// While the corner is the target the character runs straight up the corridor centre:
|
||||
// no turning east early.
|
||||
double drift = onCorner.Max(p => Math.Abs(p.E));
|
||||
Check.True(drift < 0.05, $"no early turn toward the next point ({drift:F2} yd off the centre line before arriving)");
|
||||
Check.False(w.Path.Any(p => p.N < 19 && p.E > 1), "never inside the corridor's inside wall corner (19 N, 1 E)");
|
||||
double over = w.Path.Max(p => p.N);
|
||||
Check.True(over < 21.0, $"no overshoot into the far wall at 21 N (got to {over:F2} N)");
|
||||
// No turning round: north never drops back more than a hair after its highest.
|
||||
double maxN = 0, back = 0;
|
||||
foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); }
|
||||
Check.True(back < 0.1, $"never walked back south ({back:F2} yd)");
|
||||
Check.Eq(LogCount("sweep-pass"), 0, "reached properly, not by a sweep pass");
|
||||
}
|
||||
|
||||
private static void CornerRoundingScales()
|
||||
{
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 0.5), 0.0, 1e-9, "0.5 yd: no rounding");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 1.0), 0.0, 1e-9, "1 yd: no rounding");
|
||||
Check.True(NavigationEngine.CornerLookaheadYards(4.0, 1.5) <= 1.5, "1.5 yd default: rounding inside the reach, so none");
|
||||
Check.True(NavigationEngine.CornerLookaheadYards(4.0, 2.0) <= 2.0, "2 yd: still inside the reach, so none");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 3.0), 4.0, 1e-9, "3 yd: the 4 yd Lookahead setting");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(4.0, 5.0), 4.0, 1e-9, "5 yd: the 4 yd Lookahead setting (as before)");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(0.0, 5.0), 0.0, 1e-9, "Lookahead 0 is still off");
|
||||
Check.Near(NavigationEngine.CornerLookaheadYards(6.0, 5.0), 6.0, 1e-9, "a bigger Lookahead setting is used at a big reach");
|
||||
|
||||
// The default reach walks the corner like the 1 yd one: straight to the point.
|
||||
var w = Corner(1.5f);
|
||||
var onCorner = w.Path.Where(p => p.Idx == 0).ToList();
|
||||
Check.True(onCorner.Max(p => Math.Abs(p.E)) < 0.05, "1.5 yd: no early turn");
|
||||
var first = w.Path.First(p => p.Idx >= 1);
|
||||
Check.True(Dist(first.N, first.E, 20, 0) <= 1.5, "1.5 yd: moved on within 1.5 yd");
|
||||
Check.False(w.Path.Any(p => p.N < 19 && p.E > 1), "1.5 yd: no corner cut");
|
||||
}
|
||||
|
||||
private static void CornerWideReach()
|
||||
{
|
||||
// A 5 yd reach moves on 5 yd short of the corner and heads across it for the next point:
|
||||
// the open-area corner rounding a big reach has always given.
|
||||
var w = Corner(5.0f);
|
||||
Check.True(w.Idx >= 1, "moved on");
|
||||
var first = w.Path.First(p => p.Idx >= 1);
|
||||
double atAdvance = Dist(first.N, first.E, 20, 0);
|
||||
Check.True(atAdvance > 4.0 && atAdvance <= 5.0, $"moved on 4-5 yd short of the corner ({atAdvance:F2})");
|
||||
Check.True(w.Path.Any(p => p.N < 19 && p.E > 1), "rounded the corner (inside the 2 yd corridor's corner: fine in the open)");
|
||||
double maxN = 0, back = 0;
|
||||
foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); }
|
||||
Check.True(back < 0.1, $"never walked back south ({back:F2} yd)");
|
||||
}
|
||||
|
||||
private static void PassBySide()
|
||||
{
|
||||
// The character is carried past [0] 1.2 yd to its east (outside a 1 yd reach); the old
|
||||
// code saw the distance shrink then grow by under 0.3 yd a tick, so it turned round.
|
||||
var w = new Walk(Route(RT.Circular, Pt(10, 0), Pt(30, 0)), 1.0f, 0, 1.2, 0);
|
||||
void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
foreach (double n in new[] { 2.0, 5.0, 8.0, 9.5, 10.0 }) { At(n, 1.2); FakeHost.HeadingDeg = 0; w.Step(); }
|
||||
Check.Eq(w.Idx, 0, "level with the point, 1.2 yd off: not yet");
|
||||
At(10.4, 1.2); FakeHost.HeadingDeg = 0; w.Step();
|
||||
Check.Eq(w.Idx, 1, "just past it: counted as reached");
|
||||
Check.Eq(LogCount("passed [0]"), 1, "logged as a pass");
|
||||
At(10.8, 1.2); w.Step();
|
||||
Check.True(FakeHost.AutoRun, "still running");
|
||||
double h = FakeHost.HeadingDeg;
|
||||
Check.True(h < 20 || h > 340, $"heading on north to [1], not back to [0] ({h:F0})");
|
||||
|
||||
// Too far to the side is not a pass (2.5 yd sweep radius at a 1 yd reach).
|
||||
var far = new Walk(Route(RT.Circular, Pt(10, 0), Pt(30, 0)), 1.0f, 0, 3.0, 0);
|
||||
void AtF(double n, double e) { far.N = n; far.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
foreach (double n in new[] { 2.0, 6.0, 9.0, 10.5, 12.0 }) { AtF(n, 3.0); FakeHost.HeadingDeg = 0; far.Step(); }
|
||||
Check.Eq(far.Idx, 0, "3 yd to the side: not passed");
|
||||
}
|
||||
|
||||
private static void CutIsNotAPass()
|
||||
{
|
||||
// Heading for the corner (20 N, 0 E) from the south, the character drifts east toward the
|
||||
// next point while still short of the corner: beyond the corner along the NEXT leg, but
|
||||
// the corner is not behind it, so it is not a pass.
|
||||
var w = new Walk(Route(RT.Once, Pt(20, 0), Pt(20, 20)), 1.0f, 0, 0, 0);
|
||||
void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
foreach (var (n, e) in new[] { (5.0, 0.0), (12.0, 0.5), (17.0, 1.5), (18.5, 2.0), (19.0, 2.2) })
|
||||
{
|
||||
At(n, e); w.Step();
|
||||
}
|
||||
Check.Eq(w.Idx, 0, "cutting toward the next point short of the corner never counts");
|
||||
Check.Eq(LogCount("passed [0]"), 0, "no pass logged");
|
||||
}
|
||||
|
||||
private static void FastRunSkipsOver()
|
||||
{
|
||||
// 15 yd/s at 10 frames a second: 1.5 yd a tick, three times the 0.5 yd reach's width.
|
||||
var w = new Walk(Route(RT.Once, Pt(20, 0.3), Pt(40, 0.3), Pt(60, 0.3)), 0.5f, 0, 0.3, 0);
|
||||
w.SpeedYdPerS = 15.0; w.TickMs = 100;
|
||||
w.RunUntil(() => w.Idx >= 1 && w.N > 25, 10);
|
||||
Check.True(w.Idx >= 1, "moved on");
|
||||
double maxN = 0, back = 0;
|
||||
foreach (var p in w.Path) { maxN = Math.Max(maxN, p.N); back = Math.Max(back, maxN - p.N); }
|
||||
Check.True(back < 0.1, $"never turned round ({back:F2} yd back)");
|
||||
}
|
||||
|
||||
private static void SweepUsesClosest()
|
||||
{
|
||||
// A slow pass by at about 2.3 yd (inside the 2.5 yd sweep radius of a 1 yd reach): the distance
|
||||
// grows 0.1 yd a tick, never 0.3 in one tick. The old check never fired.
|
||||
var w = new Walk(Route(RT.Circular, Pt(10, 0), Pt(10, 30)), 1.0f, 8, 2, 90);
|
||||
void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
// Coming from the south-east toward the point, then sliding away east (pushed along a wall).
|
||||
At(8.2, 1.4); w.Step(); // first tick: the approach starts here (2.3 yd)
|
||||
At(8.4, 1.6); w.Step();
|
||||
At(8.4, 1.8); w.Step();
|
||||
At(8.4, 2.0); w.Step();
|
||||
At(8.4, 2.2); w.Step();
|
||||
Check.Eq(w.Idx, 1, "0.3 yd beyond the closest approach (inside 2.5 yd): sweep pass");
|
||||
Check.Eq(LogCount("sweep-pass"), 1, "logged as a sweep pass");
|
||||
}
|
||||
|
||||
private static void DoorwayUnchanged()
|
||||
{
|
||||
// Doorway reach 1 yd, sweep 1.5 yd; the pass-through rule does not apply.
|
||||
var w = new Walk(Route(RT.Circular, Pt(10, 0, doorway: true), Pt(10, 10)), 1.5f, 0, 1.2, 0);
|
||||
void At(double n, double e) { w.N = n; w.E_ = e; FakeHost.SetNavPosition(NS0 + n / 240.0, EW0 + e / 240.0); }
|
||||
foreach (double n in new[] { 4.0, 8.0, 9.5, 10.4 }) { At(n, 1.2); FakeHost.HeadingDeg = 0; w.Step(); }
|
||||
Check.Eq(w.Idx, 0, "1.2 yd beside a doorway point and past it: not reached (doorways line up properly)");
|
||||
|
||||
// With the 5 yd reach a plain point would round the corner; a doorway point is walked straight.
|
||||
var d = new Walk(Route(RT.Once, Pt(20, 0, doorway: true), Pt(20, 20), Pt(20, 40)), 5.0f, 0, 0, 0);
|
||||
d.RunUntil(() => d.Idx >= 1 && d.E_ > 6);
|
||||
var onDoor = d.Path.Where(p => p.Idx == 0).ToList();
|
||||
Check.True(onDoor.Max(p => Math.Abs(p.E)) < 0.05, "doorway point: straight at it");
|
||||
var first = d.Path.First(p => p.Idx >= 1);
|
||||
Check.True(Dist(first.N, first.E, 20, 0) <= 1.0, "doorway point reached within 1 yd at a 5 yd reach");
|
||||
}
|
||||
}
|
||||
368
Tools/RynthCore.RynthAiHostTests/Tests/NoKillTests.cs
Normal file
368
Tools/RynthCore.RynthAiHostTests/Tests/NoKillTests.cs
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Meta;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
using C = RynthCore.Plugin.RynthAi.LegacyUi.MetaConditionType;
|
||||
using A = RynthCore.Plugin.RynthAi.LegacyUi.MetaActionType;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// "No kills within X minutes" (2026-10-06): the plugin's KillClock, the expression
|
||||
// secondssincelastkill[] and the meta condition No Kills Within Minutes (.af NoKillsInMins).
|
||||
// The kill clock and MetaManager each run on a fake clock, moved together by Rig.Advance.
|
||||
internal static class NoKillTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 10, 6, 2, 0, 0);
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("no-kill: secondssincelastkill[] counts from login, then the later of the last kill and the last macro start", FunctionClock);
|
||||
r.Add("no-kill: only KillerNotification counts, not death messages in chat", OnlyOurKills);
|
||||
r.Add("no-kill: the condition holds from N minutes without a kill", ConditionThreshold);
|
||||
r.Add("no-kill: bad minutes or no clock never hold", ConditionFailsClosed);
|
||||
r.Add("no-kill: NoKillsInMins survives an .af save and reload (also nested)", AfRoundTrip);
|
||||
r.Add("no-kill: survives the settings JSON; an unknown condition number loads and never holds", JsonRoundTrip);
|
||||
r.Add("no-kill: an unknown .af keyword loads as Never (how an older RynthAi reads NoKillsInMins)", UnknownKeywordFailsClosed);
|
||||
r.Add("no-kill: an editor save on a running meta doesn't re-fire it or reset the clock", AutosaveKeepsIt);
|
||||
r.Add("no-kill: the engine Meta editor's vocabulary matches MetaSchema", () => EngineVocabularyMatches());
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly LegacyUiSettings S = new() { IsMacroRunning = true, EnableMeta = true, CurrentState = "Default" };
|
||||
public readonly MetaManager M;
|
||||
public readonly KillClock K;
|
||||
public DateTime Now = T0;
|
||||
public long Ms;
|
||||
|
||||
public Rig(bool withClock = true, params MetaRule[] rules)
|
||||
{
|
||||
S.MetaRules = rules.ToList();
|
||||
M = new MetaManager(S, default, new PlayerVitalsCache()) { Clock = () => Now };
|
||||
K = new KillClock(() => Ms) { MacroRunning = () => S.IsMacroRunning };
|
||||
if (withClock) M.SetKillClock(K);
|
||||
}
|
||||
|
||||
public void Advance(double seconds)
|
||||
{
|
||||
Now = Now.AddSeconds(seconds);
|
||||
Ms += (long)Math.Round(seconds * 1000);
|
||||
}
|
||||
|
||||
public void Tick(double seconds = 0)
|
||||
{
|
||||
Advance(seconds);
|
||||
M.Think();
|
||||
}
|
||||
|
||||
public string Eval(string expr) => M.Expressions.Evaluate(expr);
|
||||
public string Var(string name) => M.Expressions.Variables.TryGetValue(name, out string? v) ? v : "(unset)";
|
||||
|
||||
/// <summary>One freshly armed tick with only this condition; did it fire? Time does not move.</summary>
|
||||
public bool Holds(MetaRule cond)
|
||||
{
|
||||
cond.State = S.CurrentState;
|
||||
cond.Action = A.ExpressionAction;
|
||||
cond.ActionData = "setvar[__hit, 1]";
|
||||
S.MetaRules = new List<MetaRule> { cond };
|
||||
M.Expressions.Evaluate("clearvar[__hit]");
|
||||
S.ForceStateReset = true;
|
||||
M.Think();
|
||||
return M.Expressions.Variables.ContainsKey("__hit");
|
||||
}
|
||||
|
||||
public bool Holds(string minutes) => Holds(NoKills(minutes));
|
||||
}
|
||||
|
||||
private static MetaRule NoKills(string minutes) => new() { Condition = C.NoKillsWithinMinutes, ConditionData = minutes };
|
||||
|
||||
private static MetaRule Mark(string state, C cond, string data, string v) => new()
|
||||
{
|
||||
State = state, Condition = cond, ConditionData = data,
|
||||
Action = A.ExpressionAction, ActionData = $"setvar[{v}, getvar[{v}]+1]",
|
||||
};
|
||||
|
||||
// ── secondssincelastkill[] ────────────────────────────────────────────
|
||||
|
||||
private static void FunctionClock()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.S.IsMacroRunning = false;
|
||||
rig.Advance(5);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "5", "macro never started: from login");
|
||||
Check.Eq(rig.K.Since, "login", "basis: login");
|
||||
Check.Eq(rig.K.SecondsSinceKillOnly(), -1, "status feed: no kill yet");
|
||||
|
||||
rig.S.IsMacroRunning = true;
|
||||
rig.Advance(5); // started at 10 s; nothing read until now
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "0", "macro just started: from the start");
|
||||
rig.Advance(2.5);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "2", "whole seconds (2.5 -> 2)");
|
||||
Check.Eq(rig.K.Since, "macro start", "basis: macro start");
|
||||
|
||||
// A start between reads is still seen: the plugin tick observes the macro every tick.
|
||||
rig.S.IsMacroRunning = false;
|
||||
rig.K.ObserveMacro(false);
|
||||
rig.Advance(10);
|
||||
rig.S.IsMacroRunning = true;
|
||||
rig.K.ObserveMacro(true); // restarted at 22.5 s
|
||||
rig.Advance(3);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "3", "a restart before any kill restarts the count");
|
||||
|
||||
rig.K.RecordKill(); // kill at 25.5 s
|
||||
rig.Advance(1.999);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "1", "after a kill: since the kill");
|
||||
Check.Eq(rig.K.Since, "kill", "basis: kill");
|
||||
Check.Eq(rig.K.SecondsSinceKillOnly(), 1, "status feed: since the kill");
|
||||
|
||||
rig.S.IsMacroRunning = false;
|
||||
rig.K.ObserveMacro(false);
|
||||
rig.Advance(8);
|
||||
rig.S.IsMacroRunning = true;
|
||||
rig.Advance(1);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "0", "a macro restart after a kill starts the count again");
|
||||
Check.Eq(rig.K.Since, "macro start", "basis: macro start");
|
||||
rig.Advance(10);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[] >= 10"), "1", "usable in a comparison");
|
||||
Check.Eq(rig.Eval("SecondsSinceLastKill[]"), "10", "any case");
|
||||
|
||||
rig.K.SessionStarted(); // a new login
|
||||
rig.Advance(4);
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "4", "a new login forgets the old kill (macro already on: counts from login)");
|
||||
Check.False(rig.K.HasKill, "no kill this session");
|
||||
|
||||
var none = new Rig(withClock: false);
|
||||
none.Advance(600);
|
||||
Check.Eq(none.Eval("secondssincelastkill[]"), "0", "no clock wired: 0 (never 'a long time')");
|
||||
}
|
||||
|
||||
// ── Only our kills ────────────────────────────────────────────────────
|
||||
|
||||
private static void OnlyOurKills()
|
||||
{
|
||||
var p = new RynthAiPlugin();
|
||||
KillClock k = p.Kills;
|
||||
int eat = 0;
|
||||
foreach (string line in new[]
|
||||
{
|
||||
"You killed the Drudge Skulker!",
|
||||
"Drudge Skulker died.",
|
||||
"Your fellow Bob killed the Mite Scion!",
|
||||
"The Olthoi Soldier was killed by Bob.",
|
||||
"You have been slain!",
|
||||
})
|
||||
p.OnChatWindowText(line, 0, ref eat);
|
||||
Check.False(k.HasKill, "death messages in chat don't count as our kill");
|
||||
|
||||
p.OnKillNotification("");
|
||||
p.OnKillNotification(null);
|
||||
Check.False(k.HasKill, "an empty notification isn't a kill");
|
||||
|
||||
p.OnKillNotification("You killed the Drudge Skulker!");
|
||||
Check.True(k.HasKill, "KillerNotification (sent to the killer only) is our kill");
|
||||
Check.Eq(k.Since, "kill", "the clock counts from it");
|
||||
}
|
||||
|
||||
// ── The condition ─────────────────────────────────────────────────────
|
||||
|
||||
private static void ConditionThreshold()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.Eval("secondssincelastkill[]"); // the macro start is seen at 0
|
||||
rig.Advance(59.999);
|
||||
Check.False(rig.Holds("1"), "59.999 s: not 1 minute yet");
|
||||
rig.Advance(0.001);
|
||||
Check.True(rig.Holds("1"), "60 s without a kill (from the macro start): holds");
|
||||
Check.True(rig.Holds("0.5"), "decimal minutes (0.5 = 30 s)");
|
||||
Check.True(rig.Holds("0,5"), "a comma decimal too");
|
||||
Check.True(rig.Holds(" 1 "), "spaces ignored");
|
||||
Check.False(rig.Holds("1.5"), "90 s: not yet");
|
||||
Check.True(rig.Holds("0"), "0 minutes: always");
|
||||
|
||||
rig.K.RecordKill();
|
||||
Check.False(rig.Holds("1"), "right after a kill: no");
|
||||
Check.False(rig.Holds("0.01"), "0.01 min, right after a kill: no");
|
||||
rig.Advance(119.999);
|
||||
Check.False(rig.Holds("2"), "just under 2 minutes after the kill");
|
||||
rig.Advance(0.001);
|
||||
Check.True(rig.Holds("2"), "2 minutes after the kill");
|
||||
Check.Eq(rig.Eval("secondssincelastkill[]"), "120", "same clock as the function");
|
||||
|
||||
// Nested like any other condition.
|
||||
Check.True(rig.Holds(new MetaRule { Condition = C.All, Children = { NoKills("1"), new MetaRule { Condition = C.Always } } }), "inside All");
|
||||
Check.False(rig.Holds(new MetaRule { Condition = C.Not, Children = { NoKills("1") } }), "Not of it");
|
||||
|
||||
// A rule fires once per state entry, like every condition.
|
||||
var latch = new Rig(true, Mark("Default", C.NoKillsWithinMinutes, "1", "n"));
|
||||
latch.Tick();
|
||||
latch.Tick(30);
|
||||
Check.Eq(latch.Var("n"), "(unset)", "not before a minute");
|
||||
latch.Tick(30);
|
||||
latch.Tick(30);
|
||||
Check.Eq(latch.Var("n"), "1", "fired once at a minute, latched after");
|
||||
}
|
||||
|
||||
private static void ConditionFailsClosed()
|
||||
{
|
||||
var rig = new Rig();
|
||||
rig.Eval("secondssincelastkill[]");
|
||||
rig.Advance(3600);
|
||||
foreach (string bad in new[] { "", " ", "abc", "-1", "5m", "NaN", "Infinity" })
|
||||
Check.False(rig.Holds(bad), $"'{bad}' never holds (an hour without a kill)");
|
||||
Check.True(rig.Holds("5"), "a real number does");
|
||||
|
||||
var none = new Rig(withClock: false);
|
||||
none.Advance(3600);
|
||||
Check.False(none.Holds("0"), "no kill clock wired: never holds");
|
||||
}
|
||||
|
||||
// ── Files ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void AfRoundTrip()
|
||||
{
|
||||
var rules = new List<MetaRule>
|
||||
{
|
||||
new() { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "2.5", Action = A.SetMetaState, ActionData = "Move" },
|
||||
new()
|
||||
{
|
||||
State = "Default", Condition = C.All, Action = A.ChatCommand, ActionData = "/say quiet",
|
||||
Children = { NoKills("5"), new MetaRule { Condition = C.NavrouteEmpty } },
|
||||
},
|
||||
new() { State = "Move", Condition = C.Not, Children = { NoKills("10") }, Action = A.SetMetaState, ActionData = "Default" },
|
||||
};
|
||||
string text = AfFileWriter.SaveToString(rules, new Dictionary<string, List<string>>());
|
||||
Check.True(text.Contains("NoKillsInMins 2.5"), "written as 'NoKillsInMins 2.5'");
|
||||
Check.False(text.Contains("Expr"), "not written as an expression");
|
||||
|
||||
LoadedMeta back = AfFileParser.LoadFromText(text);
|
||||
Check.Eq(back.Warnings.Count, 0, "loads without warnings");
|
||||
Check.Eq(back.Rules.Count, 3, "three rules back");
|
||||
MetaRule? top = back.Rules.FirstOrDefault(r => r.Condition == C.NoKillsWithinMinutes);
|
||||
Check.NotNull(top, "the top-level condition is back");
|
||||
if (top != null) Check.Eq(top.ConditionData, "2.5", "with its minutes");
|
||||
MetaRule? all = back.Rules.FirstOrDefault(r => r.Condition == C.All);
|
||||
Check.True(all != null && all.Children.Count == 2 && all.Children[0].Condition == C.NoKillsWithinMinutes
|
||||
&& all.Children[0].ConditionData == "5", "inside All");
|
||||
MetaRule? not = back.Rules.FirstOrDefault(r => r.Condition == C.Not);
|
||||
Check.True(not != null && not.Children.Count == 1 && not.Children[0].Condition == C.NoKillsWithinMinutes
|
||||
&& not.Children[0].ConditionData == "10", "under Not (same-line operand)");
|
||||
|
||||
string again = AfFileWriter.SaveToString(back.Rules, new Dictionary<string, List<string>>());
|
||||
Check.Eq(again, text, "a second save is identical");
|
||||
}
|
||||
|
||||
private static void JsonRoundTrip()
|
||||
{
|
||||
var s = new LegacyUiSettings();
|
||||
s.MetaRules.Add(new MetaRule { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "3", Action = A.ChatCommand, ActionData = "/say hi" });
|
||||
string json = JsonSerializer.Serialize(s, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
LegacyUiSettings? back = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(back != null && back.MetaRules.Count == 1 && back.MetaRules[0].Condition == C.NoKillsWithinMinutes
|
||||
&& back.MetaRules[0].ConditionData == "3", "the rule survives the settings JSON");
|
||||
Check.True(Regex.IsMatch(json, "\"Condition\":\\s*" + (int)C.NoKillsWithinMinutes), "stored as its number, like every condition");
|
||||
|
||||
// A condition number this build doesn't know (what an older RynthAi sees for 35): it loads
|
||||
// (System.Text.Json doesn't range-check enums) and the rule never fires.
|
||||
string future = Regex.Replace(json, "\"Condition\":\\s*" + (int)C.NoKillsWithinMinutes, "\"Condition\": 99");
|
||||
LegacyUiSettings? f = JsonSerializer.Deserialize(future, RynthAiJsonContext.Default.LegacyUiSettings);
|
||||
Check.True(f != null && f.MetaRules.Count == 1 && (int)f.MetaRules[0].Condition == 99, "an unknown number loads");
|
||||
var rig = new Rig();
|
||||
rig.Eval("secondssincelastkill[]");
|
||||
rig.Advance(3600);
|
||||
Check.False(rig.Holds(new MetaRule { Condition = (C)99, ConditionData = "3" }), "and never holds");
|
||||
Check.Eq(MetaSchema.ConditionKeyword((C)99), "Never", "an .af save writes it as Never (never true)");
|
||||
}
|
||||
|
||||
private static void UnknownKeywordFailsClosed()
|
||||
{
|
||||
// An older RynthAi's AfFileParser has no NoKillsInMins: unknown keywords load as Never with a
|
||||
// warning (same code path, before 2026-10-06). Simulated with a keyword this build doesn't know.
|
||||
var rules = new List<MetaRule>
|
||||
{
|
||||
new() { State = "Default", Condition = C.NoKillsWithinMinutes, ConditionData = "1", Action = A.ExpressionAction, ActionData = "setvar[x, 1]" },
|
||||
};
|
||||
string text = AfFileWriter.SaveToString(rules, new Dictionary<string, List<string>>()).Replace("NoKillsInMins", "NoKillsInMinsV2");
|
||||
LoadedMeta back = AfFileParser.LoadFromText(text);
|
||||
Check.Eq(back.Rules.Count, 1, "the rule still loads");
|
||||
Check.Eq(back.Rules[0].Condition, C.Never, "as Never");
|
||||
Check.True(back.Warnings.Any(w => w.Contains("NoKillsInMinsV2")), "with a warning naming the keyword");
|
||||
|
||||
var rig = new Rig(true, back.Rules.ToArray());
|
||||
rig.Tick();
|
||||
rig.Tick(3600);
|
||||
Check.Eq(rig.Var("x"), "(unset)", "and never fires");
|
||||
}
|
||||
|
||||
// ── Editor autosave (MetaRuleEdits, update_rule) ─────────────────────
|
||||
|
||||
private static void AutosaveKeepsIt()
|
||||
{
|
||||
var rig = new Rig(true,
|
||||
Mark("Default", C.NoKillsWithinMinutes, "1", "nk"),
|
||||
Mark("Default", C.NoKillsWithinMinutes, "5", "late"));
|
||||
rig.Tick();
|
||||
rig.Tick(61);
|
||||
Check.Eq(rig.Var("nk"), "1", "fired after a minute without a kill");
|
||||
long before = rig.K.ElapsedMs();
|
||||
|
||||
// The editor's autosave: an edited copy of rule 0 (new minutes), then the structural bump.
|
||||
Check.True(MetaRuleEdits.Replace(rig.S.MetaRules, 0, Mark("Default", C.NoKillsWithinMinutes, "0.5", "nk")), "replaced");
|
||||
rig.S.MetaRulesStructuralVersion++;
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("nk"), "1", "the saved rule did not fire again (latch kept)");
|
||||
Check.Eq(rig.K.ElapsedMs(), before, "the kill clock didn't move");
|
||||
Check.Eq(rig.S.MetaRules[0].ConditionData, "0.5", "the new minutes are in");
|
||||
|
||||
// An unfired rule saved with a lower threshold fires on the same clock (nothing restarted).
|
||||
Check.Eq(rig.Var("late"), "(unset)", "the 5-minute rule hasn't fired at 61 s");
|
||||
MetaRuleEdits.Replace(rig.S.MetaRules, 1, Mark("Default", C.NoKillsWithinMinutes, "1", "late"));
|
||||
rig.S.MetaRulesStructuralVersion++;
|
||||
rig.Tick();
|
||||
Check.Eq(rig.Var("late"), "1", "lowered to 1 minute: fires now, the 61 s weren't reset");
|
||||
Check.Eq(rig.S.CurrentState, "Default", "state unchanged");
|
||||
}
|
||||
|
||||
// ── Engine vocabulary drift ───────────────────────────────────────────
|
||||
|
||||
private static void EngineVocabularyMatches([CallerFilePath] string here = "")
|
||||
{
|
||||
// The engine's MetaVocabulary (RynthCore UI/Data/MetaData.cs) is indexed by the enum number
|
||||
// and can't reference the plugin; read its arrays from the side-by-side engine source.
|
||||
string path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(here)!, "..", "..", "..", "..", "RynthCore",
|
||||
"src", "RynthCore.Engine", "UI", "Data", "MetaData.cs"));
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
Check.True(false, $"engine source not found at {path} (RynthCore must sit beside RynthSuite)");
|
||||
return;
|
||||
}
|
||||
string src = File.ReadAllText(path);
|
||||
string[] keywords = ArrayIn(src, "ConditionKeywords");
|
||||
string[] names = ArrayIn(src, "ConditionNames");
|
||||
string[] hints = ArrayIn(src, "ConditionHints");
|
||||
Check.Eq(keywords.Length, MetaSchema.Conditions.Length, "as many engine keywords as conditions");
|
||||
Check.Eq(names.Length, MetaSchema.Conditions.Length, "as many engine names as conditions");
|
||||
Check.Eq(hints.Length, MetaSchema.Conditions.Length, "as many engine hints as conditions");
|
||||
for (int i = 0; i < Math.Min(keywords.Length, MetaSchema.Conditions.Length); i++)
|
||||
Check.Eq(keywords[i], MetaSchema.Conditions[i].Keyword, $"keyword {i}");
|
||||
int nk = (int)C.NoKillsWithinMinutes;
|
||||
Check.Eq(nk, 35, "No Kills Within Minutes is 35 (engine MetaRuleEdit.NoKillsWithinMinutes)");
|
||||
if (names.Length > nk) Check.Eq(names[nk], MetaSchema.Conditions[nk].Label, "same label in the editor");
|
||||
}
|
||||
|
||||
private static string[] ArrayIn(string src, string name)
|
||||
{
|
||||
int i = src.IndexOf("string[] " + name, StringComparison.Ordinal);
|
||||
if (i < 0) return Array.Empty<string>();
|
||||
int j = src.IndexOf("};", i, StringComparison.Ordinal);
|
||||
string body = Regex.Replace(src.Substring(i, j - i), "//[^\n]*", "");
|
||||
int open = body.IndexOf('{');
|
||||
return Regex.Matches(body.Substring(open), "\"([^\"]*)\"").Select(m => m.Groups[1].Value).ToArray();
|
||||
}
|
||||
}
|
||||
198
Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs
Normal file
198
Tools/RynthCore.RynthAiHostTests/Tests/PetRefillTests.cs
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
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;
|
||||
|
||||
// Pet essence refill loop (2026-10-05; spotted by Silentkelpie, rynth PR #1). PetManager decides
|
||||
// "empty, refill it" from the essence's Structure read alone. When that read is stale (0 while the
|
||||
// server holds a full essence), the server answers "This essence is already full." and PetManager
|
||||
// went idle, read 0 again a second later and refilled again: a refill every couple of seconds,
|
||||
// each one forcing peace mode and a clap (ACE PetDevice refill), for as long as the read stayed
|
||||
// stale. A confirmed refill ("You add the spirit to the essence.") with a read that stays 0 burned
|
||||
// a spirit every time. Now the server's reply wins over the read until a summon says the essence
|
||||
// really is empty, the essence is re-identified after a refill, and an essence refilled twice in
|
||||
// 2 minutes that still reads empty is parked for 5 minutes.
|
||||
internal static class PetRefillTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const uint Mob = 0x80300010;
|
||||
private const uint Essence = 0x80300001;
|
||||
private const uint Spirit = 0x80300002;
|
||||
private const uint StructureKey = 92; // AcIntProperty.Structure
|
||||
private const uint Lb = 0xA9B40000;
|
||||
|
||||
private const string AlreadyFull = "This essence is already full.";
|
||||
private const string Added = "You add the spirit to the essence.";
|
||||
private const string NoCharges = "Your summoning device does not have enough charges to function!";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("pets: a charged essence summons; an empty one is refilled once, then summons", NormalPath);
|
||||
r.Add("pets: stale empty read + 'already full' -> summon, not another refill (the loop)", AlreadyFullLoop);
|
||||
r.Add("pets: confirmed refill with a read that stays empty does not burn more spirits", AddedButStale);
|
||||
r.Add("pets: 'not enough charges' after a confirmed refill ends the trust; refill again", TrustEndsOnEmptySummon);
|
||||
r.Add("pets: refilled twice in 2 min and still empty (no reply) -> parked 5 min", SilentRefillsParked);
|
||||
r.Add("pets: the server's 'full' trust expires after 30 min", TrustExpires);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig : IDisposable
|
||||
{
|
||||
public long Now = 1_000_000;
|
||||
public readonly LegacyUiSettings S = new() { SummonPets = true, MonsterRange = 20, CustomPetRange = 5, PetAutoRefill = true };
|
||||
public readonly PetManager Pets;
|
||||
|
||||
public Rig(int charges)
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true; // UseObject (summon), RequestId (re-identify)
|
||||
FakeHost.UseOnCalls = true; // UseObjectOn (spirit on essence)
|
||||
Place(Player, "Pet Tester", 96, 96, creature: false);
|
||||
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
|
||||
Place(Mob, "Drudge Skulker", 96, 99, creature: true); // 3 m north
|
||||
FakeHost.Names[Essence] = "Fire Moar Essence (50)";
|
||||
FakeHost.Containers[Essence] = Player;
|
||||
FakeHost.Names[Spirit] = "Encapsulated Spirit";
|
||||
FakeHost.Containers[Spirit] = Player;
|
||||
SetCharges(charges);
|
||||
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = FakeHost.MakeCache(host, Player, new[] { Mob, Essence, Spirit });
|
||||
S.IsMacroRunning = true;
|
||||
S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Essence), Name = "Fire Moar Essence (50)", Type = "Pet" });
|
||||
var combat = new CombatManager(host, S, cache);
|
||||
combat.SetPlayerId(Player);
|
||||
combat.ScanNearbyTargets();
|
||||
Check.True(combat.ScannedTargets.Count == 1, "rig: the monster is scanned");
|
||||
PetManager.Clock = () => Now;
|
||||
Pets = new PetManager(host, S, cache, combat, null);
|
||||
}
|
||||
|
||||
private static void Place(uint id, string name, float x, float y, bool creature)
|
||||
{
|
||||
FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (Lb | 0x1C, x, y, 0f);
|
||||
if (creature) FakeHost.ItemTypes[id] = 0x10;
|
||||
}
|
||||
|
||||
public static void SetCharges(int charges)
|
||||
{
|
||||
if (charges < 0) FakeHost.Ints.Remove((Essence, StructureKey));
|
||||
else FakeHost.Ints[(Essence, StructureKey)] = charges;
|
||||
}
|
||||
|
||||
/// <summary>Runs the heartbeat for <paramref name="ms"/> of fake time in 100 ms steps.</summary>
|
||||
public void Run(long ms)
|
||||
{
|
||||
for (long t = 0; t < ms; t += 100)
|
||||
{
|
||||
Now += 100;
|
||||
Pets.OnHeartbeat(0);
|
||||
}
|
||||
}
|
||||
|
||||
public void Chat(string line) => Pets.OnChatWindowText(line);
|
||||
|
||||
public int Refills => FakeHost.UsesOn.Count(u => u.Source == Spirit && u.Target == Essence);
|
||||
public int Summons => FakeHost.Uses.Count(u => u == Essence);
|
||||
|
||||
public void Dispose() => PetManager.Clock = static () => Environment.TickCount64;
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void NormalPath()
|
||||
{
|
||||
using (var rig = new Rig(charges: 50))
|
||||
{
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Summons, 1, "a charged essence: one summon");
|
||||
Check.Eq(rig.Refills, 0, "a charged essence: no refill");
|
||||
}
|
||||
|
||||
using (var rig = new Rig(charges: 0))
|
||||
{
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Refills, 1, "an empty essence: one refill");
|
||||
Check.Eq(rig.Summons, 0, "an empty essence: no summon yet");
|
||||
Rig.SetCharges(50); // the server's Structure update lands
|
||||
rig.Chat(Added);
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Refills, 1, "after the refill: still one refill");
|
||||
Check.Eq(rig.Summons, 1, "after the refill: it summons");
|
||||
Check.True(FakeHost.IdRequests.Contains(Essence), "the essence is re-identified after a refill");
|
||||
}
|
||||
}
|
||||
|
||||
private static void AlreadyFullLoop()
|
||||
{
|
||||
using var rig = new Rig(charges: 0); // the read says empty and never changes
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Refills, 1, "the empty read starts one refill");
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
rig.Chat(AlreadyFull); // the server: it was full all along
|
||||
rig.Run(2000);
|
||||
}
|
||||
Check.Eq(rig.Refills, 1, "the server said full: no further refills over 20 s");
|
||||
Check.True(rig.Summons >= 1, "it summons from the essence the server called full");
|
||||
Check.True(FakeHost.IdRequests.Contains(Essence), "the stale essence is re-identified");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("already full", StringComparison.OrdinalIgnoreCase)), "the stale read is logged");
|
||||
}
|
||||
|
||||
private static void AddedButStale()
|
||||
{
|
||||
using var rig = new Rig(charges: 0);
|
||||
rig.Run(1500);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
rig.Chat(Added); // each reply would be a spirit spent
|
||||
rig.Run(2000);
|
||||
}
|
||||
Check.Eq(rig.Refills, 1, "one spirit spent, not one per think tick");
|
||||
Check.True(rig.Summons >= 1, "it summons after the confirmed refill");
|
||||
}
|
||||
|
||||
private static void TrustEndsOnEmptySummon()
|
||||
{
|
||||
using var rig = new Rig(charges: 0);
|
||||
rig.Run(1500);
|
||||
rig.Chat(AlreadyFull);
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Summons, 1, "trusting the server, it summons");
|
||||
rig.Chat(NoCharges); // the summon says it really is empty
|
||||
rig.Run(1500);
|
||||
Check.Eq(rig.Refills, 2, "really empty: refilled again");
|
||||
}
|
||||
|
||||
private static void SilentRefillsParked()
|
||||
{
|
||||
using var rig = new Rig(charges: 0); // no reply ever arrives, the read stays 0
|
||||
rig.Run(10 * 60_000);
|
||||
// Before: a refill every ~38 s (8 s timeout + 30 s park) = about 16 in 10 minutes.
|
||||
// Now: two refills, a 5 minute park, two refills, a park.
|
||||
Check.True(rig.Refills <= 4, $"at most 4 refills in 10 minutes (got {rig.Refills})");
|
||||
Check.True(rig.Refills >= 2, $"it still tries to refill (got {rig.Refills})");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("parking", StringComparison.OrdinalIgnoreCase)), "the park is logged");
|
||||
}
|
||||
|
||||
private static void TrustExpires()
|
||||
{
|
||||
using var rig = new Rig(charges: 0);
|
||||
rig.Run(1500);
|
||||
rig.Chat(AlreadyFull);
|
||||
rig.Run(1500);
|
||||
int refills = rig.Refills;
|
||||
Check.Eq(refills, 1, "trusted: no second refill");
|
||||
// No summon lands (no pet appears, the read never moves): each summon times out and
|
||||
// parks the essence for 30 s. After 30 minutes the trust is gone and the read rules.
|
||||
rig.Run(31 * 60_000);
|
||||
Check.True(rig.Refills > refills, "after 30 minutes the empty read is believed again");
|
||||
}
|
||||
}
|
||||
539
Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs
Normal file
539
Tools/RynthCore.RynthAiHostTests/Tests/UseRefusalTests.cs
Normal file
|
|
@ -0,0 +1,539 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthAi.Loot;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// 2026-10-06, Drakkon on DreamWeave: from 06:18:44 every corpse/door use got the server's UseDone
|
||||
// (no error) about one round trip later and nothing opened; a relog fixed it. The bot kept
|
||||
// hammering corpses for 13 minutes. These tests cover:
|
||||
// - UseRefusalWatch: answered-but-nothing-opened opens -> one clean stop and retry -> "the server
|
||||
// isn't letting this character use objects" once, then a back-off with quiet probes;
|
||||
// - the same through RynthAi's corpse looting (fake clock, fake server);
|
||||
// - the trigger side: a corpse open waits for the arbiter's Looting tick, RynthAi's moves and
|
||||
// turns wait while a door/corpse use is in flight, and Combat's idle peace swap waits while
|
||||
// looting has work (on ACE a move or a mode change cancels the server's walk/turn to the corpse).
|
||||
internal static class UseRefusalTests
|
||||
{
|
||||
private const uint Player = 0x50000D01;
|
||||
private const uint CorpseA = 0x80068ACE;
|
||||
private const uint CorpseB = 0x80072023;
|
||||
private const uint ItemTypeContainer = 0x200;
|
||||
private const uint LongDescKey = 16;
|
||||
private const string Me = "Drakkon";
|
||||
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
|
||||
private const string StuckLine = "isn't letting this character use objects";
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("use check: three answered opens with nothing opened -> clean stop; a second corpse refused too -> stuck; probes back off; an open recovers", WatchEscalates);
|
||||
r.Add("use check: one corpse that never opens is dropped, not reported as a stuck server", WatchDropsSingleCorpse);
|
||||
r.Add("use check: a UseDone with an error, or no UseDone at all, counts as no refusal", WatchIgnoresErrorsAndSilence);
|
||||
r.Add("use check: the next open settles an answered one that opened nothing; an open resets", WatchSettlesOnNextOpen);
|
||||
r.Add("use check (looting): Drakkon's stall - stop once, retry, say it once in chat, stop opening corpses, probe, recover", LootingStall);
|
||||
r.Add("use check (looting): normal opens never trip it", LootingNormalOpens);
|
||||
r.Add("flight recorder: the use check asks the engine for a dump (clean stop, stuck); normal opens never do", FlightDumpRequests);
|
||||
r.Add("corpse open: a corpse claimed while Combat owns the tick is opened only on the Looting tick", OpenWaitsForLootingTick);
|
||||
r.Add("move hold: while a corpse use is in flight RynthAi's moves and turns wait, stops go through, UseDone or 1.5 s releases", MoveHoldWhileUseInFlight);
|
||||
r.Add("move hold: off unless the plugin opts in (RynthNav, RynthLua unchanged)", MoveHoldOptIn);
|
||||
r.Add("idle peace: Combat's idle peace swap waits while looting has work", IdlePeaceHeldWhileLooting);
|
||||
r.Add("idle peace: looting has work = a corpse claimed, a corpse open, a corpse in range, or a use in flight", LootHoldsIdlePeaceInputs);
|
||||
}
|
||||
|
||||
// ── UseRefusalWatch alone ─────────────────────────────────────────────────
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly UseRefusalWatch W = new();
|
||||
public long T = 1_000_000;
|
||||
public int Seq;
|
||||
|
||||
/// <summary>One open of <paramref name="id"/>: answered (UseDone err 0) after 60 ms, nothing opens.
|
||||
/// Returns the verdict of the tick after the grace.</summary>
|
||||
public UseRefusalWatch.Verdict RefusedOpen(int id)
|
||||
{
|
||||
var settle = W.SettleBeforeOpen(T);
|
||||
if (settle != UseRefusalWatch.Verdict.None) return settle;
|
||||
W.OnOpenSent(id, T, Seq);
|
||||
T += 60; Seq++;
|
||||
Check.Eq(W.OnTick(T, Seq, 0, true), UseRefusalWatch.Verdict.None, "answered: no verdict yet");
|
||||
T += UseRefusalWatch.AnswerGraceMs;
|
||||
var v = W.OnTick(T, Seq, 0, true);
|
||||
T += 500;
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WatchEscalates()
|
||||
{
|
||||
var r = new Rig();
|
||||
int a = unchecked((int)CorpseA), b = unchecked((int)CorpseB);
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.None, "refusal 1");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.None, "refusal 2");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.CleanStopAndRetry, "refusal 3: clean stop and retry");
|
||||
Check.Eq(r.W.State, UseRefusalWatch.Phase.Retrying, "retrying");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "the retry refused on the same corpse: drop that corpse");
|
||||
Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.Stuck, "a second corpse refused: the server refuses every use");
|
||||
Check.Eq(r.W.State, UseRefusalWatch.Phase.Stuck, "stuck");
|
||||
Check.Eq(r.W.BackoffMs, UseRefusalWatch.FirstBackoffMs, "first back-off");
|
||||
Check.True(r.W.HoldsOpens(r.T), "no opens during the back-off");
|
||||
Check.False(r.W.HoldsOpens(r.W.BackoffUntil), "the back-off ends");
|
||||
|
||||
r.T = r.W.BackoffUntil;
|
||||
Check.Eq(r.RefusedOpen(b), UseRefusalWatch.Verdict.StillStuck, "the probe refused: still stuck");
|
||||
Check.Eq(r.W.BackoffMs, UseRefusalWatch.FirstBackoffMs * 2, "the back-off doubles");
|
||||
for (int i = 0; i < 5; i++) { r.T = r.W.BackoffUntil; r.RefusedOpen(a); }
|
||||
Check.Eq(r.W.BackoffMs, UseRefusalWatch.MaxBackoffMs, "capped");
|
||||
|
||||
Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.Recovered, "a corpse opened: recovered");
|
||||
Check.Eq(r.W.State, UseRefusalWatch.Phase.Normal, "back to normal");
|
||||
Check.Eq(r.W.Refusals, 0, "count cleared");
|
||||
Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.None, "an open while normal says nothing");
|
||||
}
|
||||
|
||||
private static void WatchDropsSingleCorpse()
|
||||
{
|
||||
var r = new Rig();
|
||||
int a = unchecked((int)CorpseA);
|
||||
r.RefusedOpen(a); r.RefusedOpen(a);
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.CleanStopAndRetry, "three refusals");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "same corpse: dropped");
|
||||
Check.Eq(r.RefusedOpen(a), UseRefusalWatch.Verdict.DropCorpse, "still only that corpse: dropped again, never stuck");
|
||||
Check.Eq(r.W.OnOpened(r.T), UseRefusalWatch.Verdict.None, "another corpse opens: nothing to announce");
|
||||
Check.Eq(r.W.State, UseRefusalWatch.Phase.Normal, "normal");
|
||||
Check.Eq(r.W.RefusedCorpses.Count, 0, "the refused list is cleared by an open");
|
||||
}
|
||||
|
||||
private static void WatchIgnoresErrorsAndSilence()
|
||||
{
|
||||
var w = new UseRefusalWatch();
|
||||
long t = 5_000; int seq = 7;
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
w.OnOpenSent(1, t, seq);
|
||||
seq++; t += 60;
|
||||
w.OnTick(t, seq, 0x1D, true); // "you're too busy"
|
||||
t += 3000;
|
||||
Check.Eq(w.OnTick(t, seq, 0x1D, true), UseRefusalWatch.Verdict.None, "a too-busy answer is no refusal");
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "and settles nothing");
|
||||
}
|
||||
Check.Eq(w.Refusals, 0, "no refusals from errors");
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
w.OnOpenSent(1, t, seq); // the server never answers (a long walk, a lag)
|
||||
t += 2000;
|
||||
Check.Eq(w.OnTick(t, seq, 0, true), UseRefusalWatch.Verdict.None, "unanswered: no verdict");
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "an unanswered open is not settled as refused");
|
||||
}
|
||||
w.OnOpenSent(1, t, seq);
|
||||
t += UseRefusalWatch.UnansweredForgetMs + 1;
|
||||
w.OnTick(t, seq, 0, true);
|
||||
seq++; t += 60;
|
||||
w.OnTick(t, seq, 0, true); // a late UseDone for something else
|
||||
t += 5000;
|
||||
Check.Eq(w.OnTick(t, seq, 0, true), UseRefusalWatch.Verdict.None, "a forgotten open is not judged by a later UseDone");
|
||||
Check.Eq(w.Refusals, 0, "no refusals from silence");
|
||||
}
|
||||
|
||||
private static void WatchSettlesOnNextOpen()
|
||||
{
|
||||
var w = new UseRefusalWatch();
|
||||
long t = 10_000; int seq = 0;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "below the threshold the open goes ahead");
|
||||
w.OnOpenSent(1, t, seq);
|
||||
seq++; t += 60;
|
||||
w.OnTick(t, seq, 0, true);
|
||||
t += 400; // the next attempt comes before the grace
|
||||
}
|
||||
Check.Eq(w.Refusals, 1, "the first answered open was settled as refused by the second");
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.None, "the second one now");
|
||||
Check.Eq(w.Refusals, 2, "two");
|
||||
w.OnOpenSent(1, t, seq); seq++; t += 60; w.OnTick(t, seq, 0, true); t += 400;
|
||||
Check.Eq(w.SettleBeforeOpen(t), UseRefusalWatch.Verdict.CleanStopAndRetry, "the third: hold this open, clean stop first");
|
||||
w.OnOpened(t);
|
||||
Check.Eq(w.Refusals, 0, "an open resets");
|
||||
Check.Eq(w.State, UseRefusalWatch.Phase.Normal, "normal");
|
||||
}
|
||||
|
||||
// ── Through RynthAi's corpse looting ──────────────────────────────────────
|
||||
|
||||
private static (uint Cell, float X, float Y, float Z) Me0 => (0x6347028Au, 100f, 100f, 0f);
|
||||
|
||||
private static void World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.SalvageCalls = true; // UseObject + MoveItemExternal
|
||||
FakeHost.WeaponCalls = true; // RequestId, HasAppraisalData, GetCurrentCombatMode
|
||||
FakeHost.ServerGates = true; // GetUseDoneSeq
|
||||
FakeHost.LastUseDoneCalls = true;
|
||||
FakeHost.StopCalls = true;
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
foreach ((uint id, float dx) in new[] { (CorpseA, 1.0f), (CorpseB, 1.5f) })
|
||||
{
|
||||
FakeHost.Names[id] = "Corpse of Olthoi Swarm Worker";
|
||||
FakeHost.ItemTypes[id] = ItemTypeContainer;
|
||||
FakeHost.Strings[(id, LongDescKey)] = $"Killed by {Me}.";
|
||||
FakeHost.NotAttackable.Add(id);
|
||||
FakeHost.Positions[id] = (Me0.Cell, Me0.X + dx, Me0.Y, Me0.Z);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Bot
|
||||
{
|
||||
public readonly RynthAiPlugin P = new();
|
||||
public readonly LegacyUiSettings S = new()
|
||||
{
|
||||
IsMacroRunning = true,
|
||||
EnableLooting = true,
|
||||
EnableCombat = false,
|
||||
LootOwnership = 0, // My Kills Only
|
||||
LootContentSettleMs = 0,
|
||||
LootEmptyCorpseMs = 0,
|
||||
StopLootingWhenPackFull = false,
|
||||
};
|
||||
public readonly WorldObjectCache Cache;
|
||||
|
||||
public Bot(RynthCoreHost host)
|
||||
{
|
||||
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
|
||||
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
|
||||
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
|
||||
Set("_dashboard", dash);
|
||||
Cache = new WorldObjectCache(host);
|
||||
Cache.SetPlayerId(Player);
|
||||
Set("_objectCache", Cache);
|
||||
Set("_playerId", Player);
|
||||
Cache.OnCreateObject(CorpseA);
|
||||
Cache.OnCreateObject(CorpseB);
|
||||
Cache.Tick();
|
||||
|
||||
string profile = Path.Combine(Program.TempRoot, "use-refusal-test.json");
|
||||
var p = new LootProfile { Name = "nothing" };
|
||||
p.Save(profile);
|
||||
S.CurrentLootPath = profile;
|
||||
}
|
||||
|
||||
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 object? Call(string m, params object[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(P, a);
|
||||
public void Tick(BotActivity act)
|
||||
{
|
||||
Set("_activity", act);
|
||||
Call("TickCorpseOpening");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs the fake clock with RynthAiPlugin.CorpseClock pointed at it.</summary>
|
||||
private static void WithClock(Action<Func<long>, Action<long>> body)
|
||||
{
|
||||
long now = 50_000_000;
|
||||
var saved = RynthAiPlugin.CorpseClock;
|
||||
RynthAiPlugin.CorpseClock = () => now;
|
||||
try { body(() => now, ms => now += ms); }
|
||||
finally { RynthAiPlugin.CorpseClock = saved; }
|
||||
}
|
||||
|
||||
private static int ChatCount(string text) => FakeHost.Chat.Count(c => c.Contains(text));
|
||||
|
||||
private static void LootingStall()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
// The server of 06:18:44 on: every open is answered (UseDone, no error) 60 ms later, nothing opens.
|
||||
long answerAt = 0;
|
||||
void Step()
|
||||
{
|
||||
int uses = FakeHost.Uses.Count;
|
||||
bot.Tick(BotActivity.Looting);
|
||||
if (FakeHost.Uses.Count > uses) answerAt = now() + 60;
|
||||
advance(100);
|
||||
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; }
|
||||
}
|
||||
|
||||
int steps = 0;
|
||||
while (ChatCount(StuckLine) == 0 && steps++ < 600) Step();
|
||||
Check.Eq(ChatCount(StuckLine), 1, "the player is told, once (after " + steps / 10.0 + " s of looting)");
|
||||
Check.True(steps <= 400, "within 40 s of the first refused open (took " + steps / 10.0 + " s)");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("one clean stop")), "the clean stop and retry came first");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("/Loot/UseCheck StopCompletely()")), "one StopCompletely from the use check");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: facing 0x80068ACE")), "and the corpse is faced for the retry");
|
||||
Check.Near(FakeHost.HeadingDeg, 90.0, 0.5, "facing east, where the corpse lies");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("giving up on it")), "the first corpse, retried alone, was dropped before the verdict");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("Use check: the server answers every use but nothing opens")), "the verdict is logged");
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "no corpse held");
|
||||
|
||||
int usesAtStuck = FakeHost.Uses.Count;
|
||||
Check.False((bool)bot.Call("HasLootWork", bot.S, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())!,
|
||||
"no loot work during the back-off: nav and combat run on");
|
||||
for (int i = 0; i < 2400; i++) Step(); // 4 minutes
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck, "no corpse is opened during the back-off");
|
||||
Check.Eq(ChatCount(StuckLine), 1, "and nothing more is said");
|
||||
|
||||
for (int i = 0; i < 700 && FakeHost.Uses.Count == usesAtStuck; i++) Step();
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "one probe after the back-off");
|
||||
for (int i = 0; i < 40; i++) Step();
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("still refused")), "the probe refused: logged");
|
||||
Check.Eq(ChatCount(StuckLine), 1, "not said again");
|
||||
Check.Eq(FakeHost.Uses.Count, usesAtStuck + 1, "and backed off again");
|
||||
|
||||
// A relog, or the server recovers: the next probe opens.
|
||||
int probeUses = FakeHost.Uses.Count;
|
||||
for (int i = 0; i < 6100 && FakeHost.Uses.Count == probeUses; i++)
|
||||
{
|
||||
bot.Tick(BotActivity.Looting);
|
||||
advance(100);
|
||||
}
|
||||
Check.Eq(FakeHost.Uses.Count, probeUses + 1, "the next probe after the longer back-off");
|
||||
uint probed = FakeHost.Uses.Last();
|
||||
bot.P.OnViewObjectContents(probed);
|
||||
Check.Eq(ChatCount("Objects open again"), 1, "the player is told uses work again");
|
||||
Check.False(bot.Get<UseRefusalWatch>("_useRefusals").HoldsOpens(now()), "looting is back on");
|
||||
});
|
||||
}
|
||||
|
||||
private static void LootingNormalOpens()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
for (int round = 0; round < 6; round++)
|
||||
{
|
||||
uint id = round % 2 == 0 ? CorpseA : CorpseB;
|
||||
// Not completed yet: a fresh claim each round.
|
||||
bot.Get<System.Collections.Generic.Dictionary<int, long>>("_completedCorpses").Clear();
|
||||
int uses = FakeHost.Uses.Count;
|
||||
for (int i = 0; i < 30 && FakeHost.Uses.Count == uses; i++) { bot.Tick(BotActivity.Looting); advance(100); }
|
||||
Check.True(FakeHost.Uses.Count > uses, $"round {round}: an open went out");
|
||||
advance(200);
|
||||
FakeHost.UseDone(0);
|
||||
bot.P.OnViewObjectContents(FakeHost.Uses.Last());
|
||||
for (int i = 0; i < 30; i++) { bot.Tick(BotActivity.Looting); advance(100); }
|
||||
}
|
||||
var w = bot.Get<UseRefusalWatch>("_useRefusals");
|
||||
Check.Eq(w.Refusals, 0, "no refusals");
|
||||
Check.Eq(w.State, UseRefusalWatch.Phase.Normal, "normal");
|
||||
Check.Eq(ChatCount(StuckLine), 0, "nothing said");
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("Use check:")), "nothing logged by the use check");
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The engine's flight recorder answers SendPluginCommand("RynthCore.FlightRecorder", "dump", reason).</summary>
|
||||
private static void FlightDumpRequests()
|
||||
{
|
||||
World();
|
||||
FakeHost.PluginCommandCalls = true;
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
long answerAt = 0;
|
||||
int steps = 0;
|
||||
while (ChatCount(StuckLine) == 0 && steps++ < 600)
|
||||
{
|
||||
int uses = FakeHost.Uses.Count;
|
||||
bot.Tick(BotActivity.Looting);
|
||||
if (FakeHost.Uses.Count > uses) answerAt = now() + 60;
|
||||
advance(100);
|
||||
if (answerAt != 0 && now() >= answerAt) { FakeHost.UseDone(0); answerAt = 0; }
|
||||
}
|
||||
var dumps = FakeHost.PluginCommands.Where(c => c.Plugin == "RynthCore.FlightRecorder").ToList();
|
||||
Check.True(dumps.Count >= 2, $"a dump asked at the clean stop and at the verdict ({dumps.Count})");
|
||||
Check.True(dumps.All(d => d.Action == "dump"), "all are dump requests");
|
||||
Check.True(dumps.Any(d => d.Value.StartsWith("RynthAi use check: corpse opens answered")), "the clean stop's reason");
|
||||
Check.True(dumps.Any(d => d.Value.StartsWith("RynthAi use check: server refuses every use")), "the verdict's reason");
|
||||
});
|
||||
|
||||
// Normal opens: nothing asked.
|
||||
World();
|
||||
FakeHost.PluginCommandCalls = true;
|
||||
var host2 = FakeHost.Create(Player);
|
||||
var bot2 = new Bot(host2);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
for (int round = 0; round < 4; round++)
|
||||
{
|
||||
bot2.Get<System.Collections.Generic.Dictionary<int, long>>("_completedCorpses").Clear();
|
||||
int uses = FakeHost.Uses.Count;
|
||||
for (int i = 0; i < 30 && FakeHost.Uses.Count == uses; i++) { bot2.Tick(BotActivity.Looting); advance(100); }
|
||||
advance(200);
|
||||
FakeHost.UseDone(0);
|
||||
bot2.P.OnViewObjectContents(FakeHost.Uses.Last());
|
||||
for (int i = 0; i < 30; i++) { bot2.Tick(BotActivity.Looting); advance(100); }
|
||||
}
|
||||
Check.False(FakeHost.PluginCommands.Any(c => c.Plugin == "RynthCore.FlightRecorder"), "no dump asked");
|
||||
});
|
||||
}
|
||||
|
||||
private static void OpenWaitsForLootingTick()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
WithClock((now, advance) =>
|
||||
{
|
||||
bot.Tick(BotActivity.Combat); // the kill tick: Combat still owns it
|
||||
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)CorpseA), "the corpse is claimed");
|
||||
Check.Eq(FakeHost.Uses.Count, 0, "but not opened while Combat owns the tick");
|
||||
advance(30);
|
||||
bot.Tick(BotActivity.Looting); // the arbiter hands the tick to Looting (its nav stop goes first)
|
||||
Check.Eq(FakeHost.Uses.Count, 1, "opened on the Looting tick");
|
||||
Check.Eq(FakeHost.Uses[0], CorpseA, "the claimed corpse");
|
||||
});
|
||||
}
|
||||
|
||||
// ── MoveAudit hold ────────────────────────────────────────────────────────
|
||||
|
||||
private static void WithAuditClock(Action<Action<long>> body)
|
||||
{
|
||||
long now = 7_000_000;
|
||||
var savedUse = UseAudit.NowMs;
|
||||
var savedMove = MoveAudit.NowMs;
|
||||
UseAudit.NowMs = () => now;
|
||||
MoveAudit.NowMs = () => now;
|
||||
try { body(ms => now += ms); }
|
||||
finally
|
||||
{
|
||||
UseAudit.NowMs = savedUse;
|
||||
MoveAudit.NowMs = savedMove;
|
||||
UseAudit.TrackWorldUses = false;
|
||||
UseAudit.ClearWorldUse();
|
||||
MoveAudit.Reset();
|
||||
UseAudit.Reset("?", null);
|
||||
}
|
||||
}
|
||||
|
||||
private static void MoveHoldWhileUseInFlight()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
WithAuditClock(advance =>
|
||||
{
|
||||
UseAudit.Reset("RynthAi", () => true);
|
||||
MoveAudit.Reset();
|
||||
UseAudit.TrackWorldUses = true;
|
||||
|
||||
Check.True(host.UseFor(CorpseA, "Loot", "test open"), "the corpse use goes out");
|
||||
advance(10);
|
||||
Check.False(host.SetAutoRunBy("Nav", true), "autorun on is held");
|
||||
Check.False(host.TurnToHeadingBy("Nav", 90f), "a heading snap is held");
|
||||
Check.Eq(FakeHost.AutoRunCalls.Count, 0, "no autorun reached the client");
|
||||
Check.Eq(FakeHost.Turns, 0, "no turn reached the client");
|
||||
Check.True(host.StopCompletelyBy("Arbiter"), "a stop goes through");
|
||||
Check.Eq(FakeHost.Stops, 1, "one stop");
|
||||
host.SetAutoRunBy("Nav", false);
|
||||
Check.Eq(string.Join(",", FakeHost.AutoRunCalls), "False", "autorun off goes through");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains(" held: the server is still answering the use of 0x80068ACE")), 1, "one 'held' line for the use");
|
||||
|
||||
FakeHost.UseDone(0); // the server answered
|
||||
Check.True(host.SetAutoRunBy("Nav", true), "after the UseDone autorun goes out");
|
||||
Check.True(host.TurnToHeadingBy("Nav", 45f), "and turns");
|
||||
|
||||
Check.True(host.UseFor(CorpseB, "Loot", "test open 2"), "a second use");
|
||||
Check.False(host.TurnToHeadingBy("Nav", 50f), "held again");
|
||||
advance(UseAudit.WorldUseInFlightMaxMs); // no answer: the cap releases it
|
||||
Check.True(host.TurnToHeadingBy("Nav", 55f), "released after the cap");
|
||||
|
||||
FakeHost.Uses.Clear();
|
||||
Check.True(host.UseFor(0x80001234, "Loot", "a non-world use (an item)"), "an item use");
|
||||
Check.True(host.TurnToHeadingBy("Nav", 60f), "an item use holds nothing");
|
||||
});
|
||||
}
|
||||
|
||||
private static void MoveHoldOptIn()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
WithAuditClock(advance =>
|
||||
{
|
||||
UseAudit.Reset("RynthNav", null);
|
||||
MoveAudit.Reset();
|
||||
Check.False(UseAudit.TrackWorldUses, "off by default");
|
||||
host.UseFor(CorpseA, "Nav", "test open");
|
||||
Check.True(host.SetAutoRunBy("Nav", true), "nothing held without the opt-in");
|
||||
Check.True(host.TurnToHeadingBy("Nav", 90f), "turns too");
|
||||
Check.False(UseAudit.WorldUseInFlight(host, out _), "no use is tracked");
|
||||
});
|
||||
}
|
||||
|
||||
// ── Combat's idle peace swap ──────────────────────────────────────────────
|
||||
|
||||
private static void IdlePeaceHeldWhileLooting()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeCalls = true;
|
||||
FakeHost.CombatModeValue = 2; // melee stance, no target: the idle swap would go to peace
|
||||
FakeHost.Names[Player] = Me;
|
||||
FakeHost.Positions[Player] = Me0;
|
||||
FakeHost.PlayerPose = Me0;
|
||||
var host = FakeHost.Create(Player);
|
||||
var s = new LegacyUiSettings { IsMacroRunning = true, EnableCombat = true, PeaceModeWhenIdle = true, MonsterRange = 50 };
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
var combat = new CombatManager(host, s, cache);
|
||||
combat.SetPlayerId(Player);
|
||||
bool looting = true;
|
||||
combat.HoldIdlePeace = () => looting;
|
||||
|
||||
for (int i = 0; i < 5; i++) combat.Think();
|
||||
Check.Eq(FakeHost.CombatModeRequests.Count, 0, "no peace swap while looting has work");
|
||||
Check.Eq(FakeHost.Logs.Count(l => l.Contains("idle peace-mode swap held")), 1, "said once in the log");
|
||||
|
||||
looting = false;
|
||||
combat.Think();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "looting done: the idle swap to peace goes out");
|
||||
|
||||
combat.HoldIdlePeace = null;
|
||||
FakeHost.CombatModeRequests.Clear();
|
||||
typeof(CombatManager).GetField("_lastPeaceAttempt", Any)!.SetValue(combat, DateTime.MinValue);
|
||||
combat.Think();
|
||||
Check.Eq(string.Join(",", FakeHost.CombatModeRequests), "1", "no hold set: as before");
|
||||
}
|
||||
|
||||
private static void LootHoldsIdlePeaceInputs()
|
||||
{
|
||||
World();
|
||||
var host = FakeHost.Create(Player);
|
||||
var bot = new Bot(host);
|
||||
bool Holds() => (bool)bot.Call("LootHoldsIdlePeace")!;
|
||||
Check.False(Holds(), "nothing to loot: no hold");
|
||||
bot.Set("_targetCorpseId", unchecked((int)CorpseA));
|
||||
Check.True(Holds(), "a claimed corpse");
|
||||
bot.Set("_targetCorpseId", 0);
|
||||
bot.Set("_openedContainerId", unchecked((int)CorpseA));
|
||||
Check.True(Holds(), "an open corpse");
|
||||
bot.Set("_openedContainerId", 0);
|
||||
bot.Set("_lastWantLoot", true);
|
||||
Check.True(Holds(), "a corpse waiting in range (the arbiter's wantLoot)");
|
||||
bot.Set("_lastWantLoot", false);
|
||||
WithAuditClock(_ =>
|
||||
{
|
||||
UseAudit.Reset("RynthAi", () => true);
|
||||
UseAudit.TrackWorldUses = true;
|
||||
host.UseFor(CorpseB, "Loot", "test open");
|
||||
Check.True(Holds(), "a corpse use in flight");
|
||||
});
|
||||
Check.False(Holds(), "all clear: no hold");
|
||||
}
|
||||
}
|
||||
|
|
@ -23,6 +23,7 @@ internal static class VitalsTests
|
|||
r.Add("vitals: Stamina to Health follows its own health line and stamina floor", StaminaToHealthThresholds);
|
||||
r.Add("vitals: profiles without the Stamina to Health keys load today's 30 / 20", StaminaToHealthDefaults);
|
||||
r.Add("vitals: after a kit, nothing else heals until the kit's result line lands", KitResultWait);
|
||||
r.Add("vitals: Heal Self known only above the tier Life Magic allows (vitae) is still cast", HealAboveAllowedTier);
|
||||
r.Add("vitals: low health wins the arbiter even on a busy tick; backs off when nothing can heal", HealthWinsArbiter);
|
||||
r.Add("vitals: 'You're too busy!' paces vital casts, and a long streak stops the character once", TooBusyVitals);
|
||||
// Drakkon's death, 2026-10-05 13:43:20 (ops\overnight\2026-10-05-death-fixes.md).
|
||||
|
|
@ -147,6 +148,29 @@ internal static class VitalsTests
|
|||
Check.False(BuffManager.IsKitResultLine("bob heals you for 40 health points."), "someone else's kit doesn't");
|
||||
}
|
||||
|
||||
private static void HealAboveAllowedTier()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
FakeHost.WeaponCalls = true;
|
||||
FakeHost.CombatModeValue = CombatMode.Magic;
|
||||
int heal6 = SpellTable.Rows.First(r => r.Name == "Heal Self VI").Id;
|
||||
FakeHost.Spellbook.Add((uint)heal6); // the only Heal Self known
|
||||
FakeHost.Skills[(Player, STypeLife)] = (120, 2); // vitae: Life Magic under the tier 6 line
|
||||
var host = FakeHost.Create();
|
||||
var s = new LegacyUiSettings { HealAt = 60, TopOffHP = 60, RestamAt = 0, TopOffStam = 0, GetManaAt = 0, TopOffMana = 0, UsePotions = false };
|
||||
var skills = new CharacterSkills(host);
|
||||
skills.SetPlayerId(Player);
|
||||
var sm = new SpellManager(host, s);
|
||||
sm.InitializeNatively();
|
||||
sm.SetCharacterSkills(skills);
|
||||
Check.True(sm.GetHighestBuffSpellTier(AcSkillType.LifeMagic) < 6, "the rig: Life Magic 120 allows less than tier 6");
|
||||
var vitals = new PlayerVitalsCache { MaxHealth = 100, CurrentHealth = 30, MaxStamina = 100, CurrentStamina = 100, MaxMana = 100, CurrentMana = 100 };
|
||||
var b = new BuffManager(host, s, sm, vitals);
|
||||
b.SetCharacterSkills(skills);
|
||||
Check.True(b.CheckVitals(), "health 30% under Heal At 60%: the vitals step acts");
|
||||
Check.True(FakeHost.Casts.Any(c => c.SpellId == heal6), "Heal Self VI is cast: " + string.Join(",", FakeHost.Casts.Select(c => c.SpellId)));
|
||||
}
|
||||
|
||||
/// <summary>One CheckVitals on a fresh BuffManager; true when it cast a Stamina to Health spell.</summary>
|
||||
private static bool CastsStamToHealth(int healthPct, int staminaPct, System.Action<LegacyUiSettings>? tweak = null)
|
||||
{
|
||||
|
|
|
|||
241
Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs
Normal file
241
Tools/RynthCore.RynthAiHostTests/Tests/WorldCacheTypedTests.cs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using RynthCore.Loot;
|
||||
using RynthCore.Plugin.RynthAi;
|
||||
using RynthCore.RynthAiHostTests.Fakes;
|
||||
using RynthCore.RynthAiTests.Harness;
|
||||
|
||||
namespace RynthCore.RynthAiHostTests.Tests;
|
||||
|
||||
// Typed world-cache placement (2026-10-05; spotted by Silentkelpie, rynth PR #1). A positioned,
|
||||
// non-creature object with a known item type used to be filed only when it was a weapon, armor,
|
||||
// caster or container, and then always into OUR inventory: other players' wielded gear and
|
||||
// ground-dropped weapons counted as ours, and keys, gems, comps and food on the ground stayed
|
||||
// Unknown and were re-probed every 2 s for good. Now they get the class their type gives and are
|
||||
// filed by who has them. Pinned here: what goes where, that hazards (dynamic or static, typed or
|
||||
// not) still register, that corpses are still found, and the loot classes (scrolls, slot-typed
|
||||
// weapons) on objects that come this way.
|
||||
internal static class WorldCacheTypedTests
|
||||
{
|
||||
private const uint Player = 0x50000E01;
|
||||
private const uint OtherPlayer = 0x50000E99;
|
||||
private const uint Lb = 0xA9B40000;
|
||||
private const uint Here = Lb | 0x1C;
|
||||
private const uint Dungeon = 0x01D90105;
|
||||
|
||||
private const uint TMelee = 0x1, TArmor = 0x2, TFood = 0x20, TMisc = 0x80, TContainer = 0x200, TGem = 0x800,
|
||||
TComps = 0x1000, TWritable = 0x2000, TKey = 0x4000, TManaStone = 0x80000, TLifeStone = 0x10000000;
|
||||
|
||||
public static void Register(Runner r)
|
||||
{
|
||||
r.Add("world cache: typed ground items get their class and stay on the landscape", GroundItems);
|
||||
r.Add("world cache: another player's wielded gear is neither ours nor a ground item", OtherPlayersGear);
|
||||
r.Add("world cache: our wielded gear and positioned pack / side-pack items are inventory", OwnGear);
|
||||
r.Add("world cache: ground gear is landscape; unreadable ownership keeps the old filing", GroundGearAndUnknownOwnership);
|
||||
r.Add("world cache: hazards still register (dynamic Misc, static, untyped); lava-named gear does not", Hazards);
|
||||
r.Add("world cache: corpses: named at once, and a Container-typed one named late is rescued", Corpses);
|
||||
r.Add("world cache: an Unknown whose type arrives late is filed as the item it is", LateType);
|
||||
r.Add("world cache: scrolls, slot-typed weapons, chests, lifestones; signs stay scenery", LootClasses);
|
||||
}
|
||||
|
||||
// ── Rig ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static uint _next;
|
||||
|
||||
private static void World()
|
||||
{
|
||||
FakeHost.Reset();
|
||||
_next = 0x80310001;
|
||||
FakeHost.Names[Player] = "Cache Tester";
|
||||
FakeHost.Positions[Player] = (Here, 96f, 96f, 0f);
|
||||
FakeHost.PlayerPose = (Here, 96f, 96f, 0f);
|
||||
FakeHost.Containers[Player] = 0; // installs GetObjectOwnershipInfo for every test
|
||||
}
|
||||
|
||||
/// <summary>A positioned non-creature: on the ground (owner null = ownership unreadable).</summary>
|
||||
private static uint Obj(string name, uint type, uint? container = 0, uint? wielder = null, uint cell = Here, uint id = 0)
|
||||
{
|
||||
if (id == 0) id = _next++;
|
||||
if (name.Length > 0) FakeHost.Names[id] = name;
|
||||
FakeHost.Positions[id] = (cell, 97f, 97f, 0f);
|
||||
if (type != 0) FakeHost.ItemTypes[id] = type;
|
||||
if (container != null) FakeHost.Containers[id] = container.Value;
|
||||
if (wielder != null) FakeHost.Wielders[id] = wielder.Value;
|
||||
FakeHost.NotAttackable.Add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>Classifies <paramref name="ids"/> the way the game does: CreateObject, then ticks.</summary>
|
||||
private static WorldObjectCache Classify(params uint[] ids)
|
||||
{
|
||||
var host = FakeHost.Create(Player);
|
||||
var cache = new WorldObjectCache(host);
|
||||
cache.SetPlayerId(Player);
|
||||
foreach (uint id in ids) cache.OnCreateObject(id);
|
||||
for (int i = 0; i < 12; i++) cache.Tick(); // past the 8 same-tick retries
|
||||
return cache;
|
||||
}
|
||||
|
||||
private static void Reclassify(WorldObjectCache cache)
|
||||
=> typeof(WorldObjectCache).GetMethod("ReclassifyUnknownDynamics", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(cache, null);
|
||||
|
||||
private static AcObjectClass ClassOf(WorldObjectCache c, uint id)
|
||||
=> c.AllKnownObjects().FirstOrDefault(w => w.Id == unchecked((int)id))?.ObjectClass ?? (AcObjectClass)(-1);
|
||||
private static bool InInventory(WorldObjectCache c, uint id) => c.GetInventory().Any(w => w.Id == unchecked((int)id));
|
||||
private static bool OnLandscape(WorldObjectCache c, uint id) => c.GetLandscapeObjects().Any(w => w.Id == unchecked((int)id));
|
||||
|
||||
private static void Where(WorldObjectCache c, uint id, AcObjectClass cls, bool inv, bool land, string what)
|
||||
{
|
||||
Check.Eq(ClassOf(c, id), cls, what + ": class");
|
||||
Check.Eq(InInventory(c, id), inv, what + ": in the inventory");
|
||||
Check.Eq(OnLandscape(c, id), land, what + ": on the landscape");
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void GroundItems()
|
||||
{
|
||||
World();
|
||||
uint key = Obj("Key to the Black Gate", TKey);
|
||||
uint gem = Obj("Black Opal", TGem);
|
||||
uint comp = Obj("Prismatic Taper", TComps);
|
||||
uint food = Obj("Apple", TFood);
|
||||
uint stone = Obj("Mana Stone", TManaStone);
|
||||
var c = Classify(key, gem, comp, food, stone);
|
||||
Where(c, key, AcObjectClass.Key, false, true, "ground key");
|
||||
Where(c, gem, AcObjectClass.Gem, false, true, "ground gem");
|
||||
Where(c, comp, AcObjectClass.SpellComponent, false, true, "ground comps");
|
||||
Where(c, food, AcObjectClass.Food, false, true, "ground food");
|
||||
Where(c, stone, AcObjectClass.ManaStone, false, true, "ground mana stone");
|
||||
Reclassify(c);
|
||||
Check.False(FakeHost.Logs.Any(l => l.Contains("stuck Unknown", StringComparison.Ordinal)), "nothing left for the Unknown re-probe");
|
||||
}
|
||||
|
||||
private static void OtherPlayersGear()
|
||||
{
|
||||
World();
|
||||
uint sword = Obj("Fire Tachi", TMelee, container: 0, wielder: OtherPlayer);
|
||||
uint armor = Obj("Amuli Shadow Coat", TArmor, container: 0, wielder: OtherPlayer);
|
||||
var c = Classify(sword, armor);
|
||||
Where(c, sword, AcObjectClass.MeleeWeapon, false, false, "another player's sword");
|
||||
Where(c, armor, AcObjectClass.Armor, false, false, "another player's coat");
|
||||
Check.False(c.GetContainedItems(unchecked((int)Player)).Any(w => w.Id == unchecked((int)sword)), "not one of our items");
|
||||
}
|
||||
|
||||
private static void OwnGear()
|
||||
{
|
||||
World();
|
||||
uint sword = Obj("Fire Tachi", TMelee, container: 0, wielder: Player);
|
||||
uint shield = Obj("Kite Shield", TArmor, container: Player);
|
||||
uint pack = 0x80310F00;
|
||||
FakeHost.Names[pack] = "Pack";
|
||||
FakeHost.ItemTypes[pack] = TContainer;
|
||||
FakeHost.Containers[pack] = Player;
|
||||
uint gem = Obj("Black Opal", TGem, container: pack);
|
||||
var c = Classify(sword, shield, gem);
|
||||
Where(c, sword, AcObjectClass.MeleeWeapon, true, false, "our wielded sword");
|
||||
Where(c, shield, AcObjectClass.Armor, true, false, "our shield");
|
||||
Where(c, gem, AcObjectClass.Gem, true, false, "a gem in our side pack");
|
||||
}
|
||||
|
||||
private static void GroundGearAndUnknownOwnership()
|
||||
{
|
||||
World();
|
||||
uint dropped = Obj("Fire Tachi", TMelee, container: 0);
|
||||
uint unknownSword = Obj("Frost Tachi", TMelee, container: null);
|
||||
uint unknownGem = Obj("Black Opal", TGem, container: null);
|
||||
var c = Classify(dropped, unknownSword, unknownGem);
|
||||
Where(c, dropped, AcObjectClass.MeleeWeapon, false, true, "a sword on the ground");
|
||||
Where(c, unknownSword, AcObjectClass.MeleeWeapon, true, false, "a sword whose owner can't be read (as before)");
|
||||
Where(c, unknownGem, AcObjectClass.Gem, false, true, "a gem whose owner can't be read");
|
||||
}
|
||||
|
||||
private static void Hazards()
|
||||
{
|
||||
World();
|
||||
uint lava = Obj("Lava", TMisc, container: 0, cell: Dungeon);
|
||||
uint lavaUnknownOwner = Obj("Pool of Acid", TMisc, container: null, cell: Dungeon + 1);
|
||||
uint staticAcid = Obj("Pool of Acid", TMisc, container: null, cell: Dungeon + 2, id: 0x71D90002);
|
||||
uint untyped = Obj("Magma", 0, container: null, cell: Dungeon + 3);
|
||||
uint gear = Obj("Lava Gauntlets", TArmor, container: 0, cell: Dungeon + 4);
|
||||
var c = Classify(lava, lavaUnknownOwner, staticAcid, untyped, gear);
|
||||
Check.True(c.IsHazardCell(Dungeon), "a dynamic Misc lava hotspot registers its cell");
|
||||
Where(c, lava, AcObjectClass.Misc, false, true, "the lava hotspot");
|
||||
Check.True(c.IsHazardCell(Dungeon + 1), "a hotspot whose owner can't be read registers");
|
||||
Check.True(c.IsHazardCell(Dungeon + 2), "a static hotspot registers");
|
||||
Where(c, staticAcid, AcObjectClass.Unknown, false, true, "the static hotspot stays scenery");
|
||||
Check.True(c.IsHazardCell(Dungeon + 3), "an untyped hotspot registers");
|
||||
Check.False(c.IsHazardCell(Dungeon + 4), "gauntlets named Lava on the floor are not a hazard (as before)");
|
||||
Check.True(System.IO.Directory.Exists(System.IO.Path.Combine(Program.TempRoot, "DungeonHazards")), "hazards persist to the scratch folder, not C:\\Games");
|
||||
}
|
||||
|
||||
private static void Corpses()
|
||||
{
|
||||
World();
|
||||
uint named = Obj("Corpse of Drudge Skulker", TContainer, container: 0);
|
||||
uint late = Obj("", TContainer, container: 0);
|
||||
var c = Classify(named, late);
|
||||
Where(c, named, AcObjectClass.Corpse, false, true, "a named corpse");
|
||||
Where(c, late, AcObjectClass.Container, false, true, "a nameless container (before its name)");
|
||||
FakeHost.Names[late] = "Corpse of Drudge Ravener";
|
||||
Reclassify(c);
|
||||
Where(c, late, AcObjectClass.Corpse, false, true, "named late: rescued as a corpse");
|
||||
|
||||
// The corpse flag alone, name never matching.
|
||||
World();
|
||||
uint flagged = Obj("Drudge Remains", TContainer, container: 0);
|
||||
FakeHost.Bitfields[flagged] = 0x2000;
|
||||
var c2 = Classify(flagged);
|
||||
Where(c2, flagged, AcObjectClass.Corpse, false, true, "a corpse by its weenie flag");
|
||||
}
|
||||
|
||||
private static void LateType()
|
||||
{
|
||||
World();
|
||||
uint gem = Obj("Black Opal", 0, container: 0);
|
||||
var c = Classify(gem);
|
||||
Where(c, gem, AcObjectClass.Unknown, false, true, "no type yet: Unknown landscape");
|
||||
FakeHost.ItemTypes[gem] = TGem;
|
||||
FakeHost.Logs.Clear();
|
||||
Reclassify(c);
|
||||
Where(c, gem, AcObjectClass.Gem, false, true, "type arrived: a ground gem");
|
||||
Check.True(FakeHost.Logs.Any(l => l.Contains("typed 1 Unknown object", StringComparison.Ordinal)), "logged once");
|
||||
|
||||
// Our own item whose type arrives late goes to the inventory.
|
||||
World();
|
||||
uint mine = Obj("Fire Tachi", 0, container: 0, wielder: Player);
|
||||
var c2 = Classify(mine);
|
||||
FakeHost.ItemTypes[mine] = TMelee;
|
||||
Reclassify(c2);
|
||||
Where(c2, mine, AcObjectClass.MeleeWeapon, true, false, "our sword typed late");
|
||||
|
||||
// A creature still wins: a late Creature type promotes, it is not filed as an item.
|
||||
World();
|
||||
uint mob = Obj("Drudge Skulker", 0, container: 0);
|
||||
var c3 = Classify(mob);
|
||||
FakeHost.ItemTypes[mob] = 0x10;
|
||||
Reclassify(c3);
|
||||
Check.Eq(ClassOf(c3, mob), AcObjectClass.Monster, "a late creature type: Monster");
|
||||
}
|
||||
|
||||
private static void LootClasses()
|
||||
{
|
||||
World();
|
||||
uint scroll = Obj("Scroll of Gift of Essence", TWritable, container: 0);
|
||||
FakeHost.DataIds[(scroll, 28)] = 2001;
|
||||
uint book = Obj("Tattered Journal", TWritable, container: 0); // no "Scroll" name, no spell
|
||||
uint slayer = Obj("Driftwarden Greataxe", TMisc, container: 0);
|
||||
FakeHost.Ints[(slayer, 9)] = 0x00100000; // ValidLocations: melee weapon slot
|
||||
uint chest = Obj("Chest", TContainer, container: null, id: 0x71D90010);
|
||||
uint stone = Obj("Life Stone", TLifeStone, container: null, id: 0x71D90011);
|
||||
uint sign = Obj("Sign", TMisc, container: null, id: 0x71D90012);
|
||||
var c = Classify(scroll, book, slayer, chest, stone, sign);
|
||||
Where(c, scroll, AcObjectClass.Scroll, false, true, "a spell scroll on the ground");
|
||||
Where(c, book, AcObjectClass.Book, false, true, "a journal on the ground");
|
||||
Where(c, slayer, AcObjectClass.MeleeWeapon, false, true, "a Misc-typed weapon with a weapon slot");
|
||||
Where(c, chest, AcObjectClass.Container, false, true, "a static chest");
|
||||
Where(c, stone, AcObjectClass.Lifestone, false, true, "a lifestone");
|
||||
Where(c, sign, AcObjectClass.Unknown, false, true, "a static sign stays scenery");
|
||||
}
|
||||
}
|
||||
|
|
@ -41,4 +41,9 @@
|
|||
<None Include="Fixtures\**\*" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@
|
|||
<Compile Include="..\..\Plugins\Shared\RynthAiScriptApi.cs" Link="Plugin\Shared\RynthAiScriptApi.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\UseAudit.cs" Link="Plugin\Shared\UseAudit.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\*.cs" Link="Sdk\%(Filename)%(Extension)" />
|
||||
<!-- The SDK takes CurrentApiVersion from the engine's constant since plugin manifests (API v79). -->
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Sdk\PluginContractVersion.cs" />
|
||||
<Compile Include="..\..\..\RynthCore\src\RynthCore.PluginCore\*.cs" Link="Sdk\%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
|
|
@ -37,4 +39,9 @@
|
|||
<None Include="Scripts\**\*.lua" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- RynthLuaPaths.cs uses the install-folder resolver. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -38,4 +38,9 @@
|
|||
<Compile Include="..\..\..\RynthCore\src\RynthCore.StatusAgent\Dat\DxtUtil.cs" Link="Engine\DxtUtil.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- RynthLuaPaths.cs uses the install-folder resolver. -->
|
||||
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ internal static class Program
|
|||
Run(nameof(EndToEndAroundAWall), EndToEndAroundAWall);
|
||||
Run(nameof(LandmassesAndSameLand), LandmassesAndSameLand);
|
||||
Run(nameof(PathGoesRoundAPortal), PathGoesRoundAPortal);
|
||||
Run(nameof(TripWalkFromTileFiles), TripWalkFromTileFiles);
|
||||
Run(nameof(RealTripWalk), RealTripWalk);
|
||||
}
|
||||
finally { try { Directory.Delete(_root, true); } catch { } }
|
||||
Console.WriteLine();
|
||||
|
|
@ -385,4 +387,72 @@ internal static class Program
|
|||
double d = Math.Sqrt((nearPt.X - 95) * (nearPt.X - 95) + (nearPt.Z - 96) * (nearPt.Z - 96));
|
||||
Check(nearRef != 0 && d >= PortalAvoid.LiveRadius - 0.01, $"a goal beside the portal snaps to ground outside its circle ({d:F2} u away)");
|
||||
}
|
||||
|
||||
// ── A planned trip's walk, from the tile files (TilePathFinder, on a worker in the plugin) ──
|
||||
|
||||
private static void TripWalkFromTileFiles()
|
||||
{
|
||||
// The wall: from the south of tile 0 to the south of tile 2, the only way is round the north.
|
||||
string dir = Bake("tripwall", (0, 0, 192, 192), (192, 150, 384, 192), (384, 0, 576, 192));
|
||||
BuildGraph(dir, out NavGraph g);
|
||||
var from = new RynthCore.Plugin.RynthNav.WorldPt(100, 20, 0);
|
||||
var to = new RynthCore.Plugin.RynthNav.WorldPt(480, 20, double.NaN);
|
||||
var finder = new TilePathFinder(dir, g, null);
|
||||
var path = finder.Walk(from, to, false, out string note);
|
||||
Check(path != null && path.Count >= 4, $"a path round the wall ({path?.Count} corners; {note})");
|
||||
Check(note == "", "no gaps: " + note);
|
||||
Check(path != null && path.Exists(p => p.Y > 150), "it goes north through the passage");
|
||||
Check(path != null && Math.Abs(path[^1].X - 480) < 3 && Math.Abs(path[^1].Y - 20) < 3, "and ends at the goal");
|
||||
Check(path != null && path.TrueForAll(p => !double.IsNaN(p.H) && Math.Abs(p.H) < 2), "heights from the navmesh");
|
||||
Check(finder.TilesRead >= 3, $"read the tiles it needed ({finder.TilesRead})");
|
||||
var thin = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path!);
|
||||
Check(thin.Exists(p => p.Y > 150), "thinned, it still goes round");
|
||||
|
||||
// Without the route graph, a short leg is planned on the tiles alone.
|
||||
var direct = new TilePathFinder(dir, null, null).Walk(from, to, false, out string note2);
|
||||
Check(direct != null && direct.Exists(p => p.Y > 150), "without the graph: the same way round (" + note2 + ")");
|
||||
// No navmesh at the far end: none, and why.
|
||||
var nowhere = new TilePathFinder(dir, g, null).Walk(from, new RynthCore.Plugin.RynthNav.WorldPt(2000, 2000, 0), false, out string why);
|
||||
Check(nowhere == null && why.Length > 0, "no tile at the end: no path (" + why + ")");
|
||||
|
||||
// An Atlas portal on the straight line over open ground: kept out of, unless it's the leg's own.
|
||||
string open = Bake("tripportal", (0, 0, 192, 192));
|
||||
var spot = new[] { new PortalAvoid.Spot(95, 96, PortalAvoid.MapRadius, "Unwanted Portal") };
|
||||
var round = new TilePathFinder(open, null, spot).Walk(new(30, 96, 0), new(160, 96, 0), false, out _);
|
||||
double gap = double.MaxValue;
|
||||
for (int i = 1; round != null && i < round.Count; i++) gap = Math.Min(gap, PortalAvoid.SegmentDistance(95, 96, round[i - 1].X, round[i - 1].Y, round[i].X, round[i].Y));
|
||||
Check(round != null && gap >= PortalAvoid.MapRadius - 0.01, $"the walk keeps out of the portal's circle ({gap:F2} u)");
|
||||
var own = new TilePathFinder(open, null, spot).Walk(new(30, 96, 0), new(95, 96, 0), true, out _);
|
||||
Check(own != null && Math.Abs(own[^1].X - 95) < 3, "walking into that portal: it's the goal, not avoided");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real map (read only, when it's installed): Holtburg to Lytelthorpe, about 11k yd over
|
||||
/// land, as the path markers and "save as nav route" would work it out. Prints the size and time.
|
||||
/// </summary>
|
||||
private static void RealTripWalk()
|
||||
{
|
||||
string dir = Environment.GetEnvironmentVariable("RYNTHNAV_NAVDATA") ?? @"C:\Games\RynthCore\NavData";
|
||||
string graphFile = Path.Combine(dir, NavGraph.FileName);
|
||||
if (!File.Exists(graphFile)) { Console.WriteLine(" (no real NavData here: skipped)"); return; }
|
||||
NavGraph g = NavGraph.Load(graphFile);
|
||||
var from = RynthCore.Plugin.RynthNav.WorldPt.FromMap(42.08, 33.6, double.NaN);
|
||||
var to = RynthCore.Plugin.RynthNav.WorldPt.FromMap(-0.8, 51.2, double.NaN);
|
||||
// Landmasses, as the plugin has them (LoadGraph): Lytelthorpe's centre probes onto a roof,
|
||||
// a landmass of one region; the ground beside it is found instead.
|
||||
g.BuildComponents();
|
||||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||
var finder = new TilePathFinder(dir, g, null);
|
||||
var path = finder.Walk(from, to, false, out string note);
|
||||
long ms = sw.ElapsedMilliseconds;
|
||||
Check(path != null, "Holtburg to Lytelthorpe on the real navmesh: " + note);
|
||||
if (path == null) return;
|
||||
var thin = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path);
|
||||
int corners = RynthCore.Plugin.RynthNav.TripPathBuilder.Thin(path, maxSpacing: 0).Count;
|
||||
double len = 0;
|
||||
for (int i = 1; i < thin.Count; i++) len += thin[i - 1].FlatDistance(thin[i]);
|
||||
Console.WriteLine($" Holtburg -> Lytelthorpe: {path.Count} corners, {corners} kept by thinning, {thin.Count} with a point every {RynthCore.Plugin.RynthNav.TripPathBuilder.MaxSpacing} yd, {len:F0} yd, {finder.TilesRead} tiles read, {ms} ms{(note.Length > 0 ? "; " + note : "")}");
|
||||
Check(len > from.FlatDistance(to) * 0.98 && len < from.FlatDistance(to) * 2.5, $"a sensible length ({len:F0} vs {from.FlatDistance(to):F0} straight)");
|
||||
Check(ms < 30000, $"worked out in reasonable time ({ms} ms)");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,13 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PortalAvoid.cs" Link="Linked\PortalAvoid.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AvoidFilter.cs" Link="Linked\AvoidFilter.cs" />
|
||||
<Compile Include="..\RynthNav.Baker\GraphBuild.cs" Link="Linked\GraphBuild.cs" />
|
||||
<!-- A planned trip's walk from the tile files (TilePathFinder) and what it needs. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TilePathFinder.cs" Link="Linked\TilePathFinder.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPlan.cs" Link="Linked\TripPlan.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPath.cs" Link="Linked\TripPath.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavCoords.cs" Link="Linked\NavCoords.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TownNet.cs" Link="Linked\TownNet.cs" />
|
||||
<Compile Include="..\RynthNav.PortalGraph\PortalRoute.cs" Link="Linked\PortalRoute.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ internal static partial class Program
|
|||
RunTownNet();
|
||||
RunAvoid();
|
||||
RunTravelPlan();
|
||||
RunTripExport();
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(_fails == 0 && _asserts > 0
|
||||
|
|
|
|||
|
|
@ -28,6 +28,14 @@
|
|||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TownNet.cs" Link="Linked\TownNet.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PortalAvoid.cs" Link="Linked\PortalAvoid.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TravelPlan.cs" Link="Linked\TravelPlan.cs" />
|
||||
<!-- The planned trip, its path, the path markers and "save as nav route" (TripExportTests). -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPlan.cs" Link="Linked\TripPlan.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\TripPath.cs" Link="Linked\TripPath.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\PathMarkers.cs" Link="Linked\PathMarkers.cs" />
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavRouteExport.cs" Link="Linked\NavRouteExport.cs" />
|
||||
<Compile Include="..\..\Plugins\Shared\Nav3DText.cs" Link="Linked\Nav3DText.cs" />
|
||||
<!-- RynthAi's own nav reader/writer: the saved route is read back the way RynthAi reads it. -->
|
||||
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\LegacyUi\NavRouteParser.cs" Link="Linked\NavRouteParser.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
389
Tools/RynthNav.RouteTests/TripExportTests.cs
Normal file
389
Tools/RynthNav.RouteTests/TripExportTests.cs
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||
using RynthCore.Plugin.RynthNav;
|
||||
using RynthCore.Plugin.Shared;
|
||||
using RynthNav.Routing;
|
||||
|
||||
namespace RynthNav.RouteTests;
|
||||
|
||||
// A planned trip on the ground and as a RynthAi nav route: the trip's legs (PlannedTrip), the
|
||||
// walking path thinned (TripPathBuilder), the path markers (PathMarkers: what's built, what's drawn,
|
||||
// the next waypoint, when the markers go) and "save as nav route" (NavRouteExport: walks, recalls,
|
||||
// portals and the Town Network as nav steps, read back with RynthAi's own reader; a file that's
|
||||
// there isn't replaced without being asked).
|
||||
internal static partial class Program
|
||||
{
|
||||
private static void RunTripExport()
|
||||
{
|
||||
Run(nameof(ThinKeepsCornersAndSplitsStraights), ThinKeepsCornersAndSplitsStraights);
|
||||
Run(nameof(StopShortAlongThePath), StopShortAlongThePath);
|
||||
Run(nameof(TripLegsWalkRecallPortal), TripLegsWalkRecallPortal);
|
||||
Run(nameof(TripPathStraightLineWhenNoMesh), TripPathStraightLineWhenNoMesh);
|
||||
Run(nameof(ExportWalkRecallPortalRoundTrip), ExportWalkRecallPortalRoundTrip);
|
||||
Run(nameof(ExportCommandRecallAndDungeonEntrance), ExportCommandRecallAndDungeonEntrance);
|
||||
Run(nameof(ExportTownNetwork), ExportTownNetwork);
|
||||
Run(nameof(ExportStopsAtAStepWithNoNavEquivalent), ExportStopsAtAStepWithNoNavEquivalent);
|
||||
Run(nameof(SaveRefusesToOverwrite), SaveRefusesToOverwrite);
|
||||
Run(nameof(MarkersBuiltFromTheTrip), MarkersBuiltFromTheTrip);
|
||||
Run(nameof(MarkersEmitNearTheCharacter), MarkersEmitNearTheCharacter);
|
||||
Run(nameof(MarkersNextWaypointAdvances), MarkersNextWaypointAdvances);
|
||||
Run(nameof(MarkersClearOffTheTrip), MarkersClearOffTheTrip);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A navmesh-like path a→b: a point every 2 yd, swinging 10 yd out round an obstacle halfway.</summary>
|
||||
private static List<WorldPt>? FakeWalk(WorldPt a, WorldPt b, bool intoPortal, out string note)
|
||||
{
|
||||
note = "";
|
||||
var pts = new List<WorldPt>();
|
||||
double len = a.FlatDistance(b);
|
||||
int n = Math.Max(2, (int)(len / 2));
|
||||
double nx = -(b.Y - a.Y) / len, ny = (b.X - a.X) / len; // left of the way
|
||||
for (int i = 0; i <= n; i++)
|
||||
{
|
||||
double t = (double)i / n;
|
||||
double off = 10.0 * Math.Max(0, 1 - Math.Abs(t - 0.5) * 8); // a tent 10 yd high from t=0.375 to 0.625
|
||||
pts.Add(new WorldPt(a.X + (b.X - a.X) * t + nx * off, a.Y + (b.Y - a.Y) * t + ny * off, 5.0));
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
private static PlannedTrip Trip(List<RouteStep> steps, double startNs, double startEw, string goal, double goalNs, double goalEw,
|
||||
List<TripRecall>? recalls = null, string enterPortal = "", string enterName = "", bool startOnMap = true, int id = 1)
|
||||
{
|
||||
WorldPt start = WorldPt.FromMap(startNs, startEw, 5.0);
|
||||
uint lb = start.Landblock;
|
||||
uint cell = (lb << 16) | 0x0001;
|
||||
return new PlannedTrip(id, steps, goal, goalNs, goalEw, startOnMap, start, cell, recalls, enterPortal, enterName);
|
||||
}
|
||||
|
||||
private sealed class Recorder : IMarkerSink
|
||||
{
|
||||
public readonly List<(float X, float Y, float Z, float R, uint C)> Rings = new();
|
||||
public readonly List<(float X1, float Y1, float Z1, float X2, float Y2, float Z2, uint C)> Lines = new();
|
||||
public int Tris;
|
||||
public void Ring(float x, float y, float z, float radius, float thickness, uint colorArgb) => Rings.Add((x, y, z, radius, colorArgb));
|
||||
public void Line(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb) => Lines.Add((x1, y1, z1, x2, y2, z2, colorArgb));
|
||||
public void Triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint colorArgb) => Tris++;
|
||||
}
|
||||
|
||||
// ── Thinning ─────────────────────────────────────────────────────────
|
||||
|
||||
private static void ThinKeepsCornersAndSplitsStraights()
|
||||
{
|
||||
// 100 yd east in 1 yd steps with 0.2 yd wobble, then 50 yd north; heights unknown at first.
|
||||
var raw = new List<WorldPt>();
|
||||
for (int i = 0; i <= 100; i++) raw.Add(new WorldPt(1000 + i, 1000 + (i % 2 == 0 ? 0.2 : -0.2), i < 3 ? double.NaN : 7));
|
||||
for (int i = 1; i <= 50; i++) raw.Add(new WorldPt(1100, 1000 + i, 7));
|
||||
raw.Add(new WorldPt(1100, 1050.1, 7)); // a near duplicate
|
||||
List<WorldPt> thin = TripPathBuilder.Thin(raw);
|
||||
Check(thin.Count < 12, $"151 navmesh points thin to a few ({thin.Count})");
|
||||
Check(thin[0].FlatDistance(raw[0]) < 0.01 && thin[^1].FlatDistance(raw[^1]) < 0.6, "the ends are kept");
|
||||
Check(thin.Any(p => Math.Abs(p.X - 1100) < 0.6 && Math.Abs(p.Y - 1000) < 0.6), "the corner is kept");
|
||||
for (int i = 1; i < thin.Count; i++)
|
||||
Check(thin[i - 1].FlatDistance(thin[i]) <= TripPathBuilder.MaxSpacing + 0.01, $"no stretch longer than {TripPathBuilder.MaxSpacing} yd ({i})");
|
||||
Check(thin.All(p => !double.IsNaN(p.H)), "unknown heights filled from the neighbours");
|
||||
foreach (WorldPt p in raw)
|
||||
{
|
||||
double best = double.MaxValue;
|
||||
for (int i = 1; i < thin.Count; i++) best = Math.Min(best, PlannedTrip.SegmentDistance(p, thin[i - 1], thin[i]));
|
||||
if (best > TripPathBuilder.ThinTolerance + 0.01) { Check(false, $"a dropped point is {best:F2} yd off the thinned path"); break; }
|
||||
}
|
||||
Check(TripPathBuilder.Thin(new List<WorldPt> { new(0, 0, 1), new(0, 100, 1) }).Count == 3, "a 100 yd straight gets a point every 60 yd at most (2 stretches)");
|
||||
}
|
||||
|
||||
private static void StopShortAlongThePath()
|
||||
{
|
||||
var path = new List<WorldPt> { new(0, 0, 1), new(10, 0, 1), new(10, 3, 1) };
|
||||
List<WorldPt> s = TripPathBuilder.StopShort(path, 5);
|
||||
Check(s.Count == 2 && Math.Abs(s[^1].X - 8) < 1e-9 && Math.Abs(s[^1].Y) < 1e-9, "5 yd short, back round the corner");
|
||||
Check(TripPathBuilder.StopShort(path, 20).Count == 1, "shorter than that: only the start");
|
||||
Check(TripPathBuilder.StopShort(path, 0).Count == 3, "0: unchanged");
|
||||
}
|
||||
|
||||
// ── The trip's legs ──────────────────────────────────────────────────
|
||||
|
||||
private static void TripLegsWalkRecallPortal()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "Lifestone Recall", 0, 20, 20), // cast here, land at 20,20
|
||||
new(20.5, 20, true, false, "Portal to Far", -1, 50, 50), // walk to a portal, land at 50,50
|
||||
new(50.4, 50.3, false, false, "walk"), // walk to the goal
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List<TripRecall> { new("Lifestone Recall", 1635, "", 13) });
|
||||
Check(trip.WalkFrom[0] == null && trip.Point[0] is WorldPt c && c.FlatDistance(trip.Start) < 0.01, "a recall walks nowhere; it's cast at the start");
|
||||
Check(trip.WalkFrom[1] is WorldPt f1 && Math.Abs(f1.Ns - 20) < 1e-9 && Math.Abs(f1.Ew - 20) < 1e-9, "the next walk starts at the recall's landing");
|
||||
Check(trip.Point[1] is WorldPt p1 && Math.Abs(p1.Ns - 20.5) < 1e-9, "...and ends at the portal");
|
||||
Check(trip.WalkFrom[2] is WorldPt f2 && Math.Abs(f2.Ns - 50) < 1e-9, "the last walk starts at the portal's landing");
|
||||
Check(trip.RecallOf(0)?.SpellId == 1635 && trip.RecallOf(1) == null, "the recall by index");
|
||||
|
||||
// A portal into a dungeon (no landing on the map) and nothing after it: the dungeon goto.
|
||||
var into = Trip(new List<RouteStep> { new(10.2, 10.2, true, false, "Matron Hive") }, 10, 10, "Matron Hive", 10.2, 10.2,
|
||||
enterPortal: "Portal to Matron Hive", enterName: "Matron Hive");
|
||||
Check(into.EndsInEntrance && into.PortalName(0) == "Portal to Matron Hive", "a dungeon goto's portal is the portal object, not the dungeon's name");
|
||||
// No steps: a plain walk to the goal.
|
||||
var plain = Trip(new List<RouteStep>(), 10, 10, "Near", 10.3, 10.1);
|
||||
Check(plain.Count == 1 && plain.WalkFrom[0] != null && !plain.Steps[0].UsePortal, "no steps = one walk");
|
||||
}
|
||||
|
||||
private static void TripPathStraightLineWhenNoMesh()
|
||||
{
|
||||
var trip = Trip(new List<RouteStep> { new(10.5, 10, false, false, "walk") }, 10, 10, "G", 10.5, 10);
|
||||
TripPath p = TripPathBuilder.Build(trip, (WorldPt a, WorldPt b, bool ip, out string note) => { note = "no navmesh at its start"; return null; }, null);
|
||||
Check(p.Walks[0] != null && p.Walks[0]!.Length == 3, $"a straight line, split every 60 yd (120 yd: {p.Walks[0]?.Length})");
|
||||
Check(p.Notes.Count == 1 && p.Notes[0].Contains("step 1") && p.Notes[0].Contains("straight"), "...with a note: " + string.Join("; ", p.Notes));
|
||||
TripPath q = TripPathBuilder.Build(trip, FakeWalk, null);
|
||||
Check(q.Notes.Count == 0 && q.Walks[0]!.Length < 20, $"the navmesh path, thinned ({q.Walks[0]!.Length} points)");
|
||||
Check(q.Walks[0]!.Any(w => PlannedTrip.SegmentDistance(w, trip.Start, trip.Point[0]!.Value) > 9), "it keeps the swing round the obstacle");
|
||||
}
|
||||
|
||||
// ── Save as nav route ────────────────────────────────────────────────
|
||||
|
||||
private static void ExportWalkRecallPortalRoundTrip()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "Lifestone Recall", 0, 20, 20),
|
||||
new(20.5, 20, true, false, "Portal to Far", -1, 50, 50),
|
||||
new(50.4, 50.3, false, false, "walk"),
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List<TripRecall> { new("Lifestone Recall", 1635, "", 13) });
|
||||
TripPath path = TripPathBuilder.Build(trip, FakeWalk, null);
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, path, null);
|
||||
Check(r.StoppedAt == -1 && r.StopReason == "", "the whole trip converts: " + r.StopReason);
|
||||
List<NavPoint> pts = r.Route.Points;
|
||||
Check(r.Route.RouteType == NavRouteType.Once, "a Once route");
|
||||
Check(pts[0].Type == NavPointType.Recall && pts[0].SpellId == 1635, "first: the recall spell");
|
||||
int portal = pts.FindIndex(p => p.Type == NavPointType.PortalNPC);
|
||||
Check(portal > 1, "then walking points, then the portal step");
|
||||
Check(pts.Skip(1).Take(portal - 1).All(p => p.Type == NavPointType.Point), "walking legs are Points");
|
||||
Check(portal - 1 < 15, $"thinned: not every navmesh corner ({portal - 1} points for 120 yd with an obstacle)");
|
||||
NavPoint pn = pts[portal];
|
||||
Check(pn.TargetName == "Portal to Far" && pn.ObjectClass == NavRouteExport.PortalObjectClass && pn.IsTie, "the portal by name, VTank's portal class");
|
||||
Check(Math.Abs(pn.PortalExitNS - 20.5) < 1e-6 && Math.Abs(pn.PortalExitEW - 20) < 1e-6, "at the portal's entrance");
|
||||
NavPoint before = pts[portal - 1];
|
||||
double toPortal = NavCoords.Distance(before.NS, before.EW, 20.5, 20);
|
||||
Check(toPortal > NavRouteExport.PortalStopShort - 0.5 && toPortal < 12, $"the walk stops short of the entrance ({toPortal:F1} yd)");
|
||||
Check(pts[^1].Type == NavPointType.Point && NavCoords.Distance(pts[^1].NS, pts[^1].EW, 50.4, 50.3) < 0.5, "the last point is the goal");
|
||||
Check(NavCoords.Distance(pts[portal + 1].NS, pts[portal + 1].EW, 50, 50) < TripPathBuilder.MaxSpacing, "after the portal the walk starts near its landing");
|
||||
Check(pts.Where(p => p.Type == NavPointType.Point).All(p => Math.Abs(p.Z - 5.0 / 240.0) < 1e-9), "heights in nav units (metres / 240)");
|
||||
|
||||
// Read back with RynthAi's own reader.
|
||||
var back = NavRouteParser.LoadFromLines(r.Route.ToLines());
|
||||
Check(back.LoadWarning == null && back.Points.Count == pts.Count && back.RouteType == NavRouteType.Once, "RynthAi reads it back whole");
|
||||
bool same = true;
|
||||
for (int i = 0; i < pts.Count && same; i++)
|
||||
same = back.Points[i].Type == pts[i].Type && Math.Abs(back.Points[i].NS - pts[i].NS) < 1e-9 && Math.Abs(back.Points[i].EW - pts[i].EW) < 1e-9
|
||||
&& back.Points[i].SpellId == pts[i].SpellId && back.Points[i].TargetName == pts[i].TargetName && back.Points[i].ObjectClass == pts[i].ObjectClass;
|
||||
Check(same, "every step the same after the round trip");
|
||||
Check(r.Waypoints + r.Portals + r.Recalls == pts.Count, "the counts add up");
|
||||
}
|
||||
|
||||
private static void ExportCommandRecallAndDungeonEntrance()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "@lifestone", 0, 20, 20),
|
||||
new(20.3, 20.2, true, false, "Matron Hive"), // Entrance.EndingInPortal labels it with the dungeon
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Matron Hive", 20.3, 20.2, new List<TripRecall> { new("@lifestone", 0, "@lifestone", 15) },
|
||||
enterPortal: "Portal to Matron Hive", enterName: "Matron Hive");
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null);
|
||||
List<NavPoint> pts = r.Route.Points;
|
||||
Check(pts[0].Type == NavPointType.Chat && pts[0].ChatCommand == "@lifestone", "a command recall is a chat step");
|
||||
Check(pts[1].Type == NavPointType.Pause && pts[1].PauseTimeMs == NavRouteExport.CommandRecallPauseMs, "...and a pause for its teleport");
|
||||
Check(pts[^1].Type == NavPointType.PortalNPC && pts[^1].TargetName == "Portal to Matron Hive", "it ends with the dungeon's entrance portal, by the portal's name");
|
||||
Check(r.StoppedAt == -1, "nothing left out");
|
||||
var back = NavRouteParser.LoadFromLines(r.Route.ToLines());
|
||||
Check(back.Points.Count == pts.Count && back.Points[0].ChatCommand == "@lifestone" && back.Points[1].PauseTimeMs == NavRouteExport.CommandRecallPauseMs,
|
||||
"read back by RynthAi");
|
||||
}
|
||||
|
||||
private static void ExportTownNetwork()
|
||||
{
|
||||
TownNet net = TownNet.Parse(SmallTownNet(), out _)!;
|
||||
var steps = PortalRoute.Plan(NoPortals, null, net.Links(90, false, null), 0, 0, 40, 40, out _, out int used);
|
||||
Check(used == 2 && steps.Count == 3 && steps[1].IsHub, "the plan: walk to the entry, the network, walk on");
|
||||
var trip = Trip(steps, 0, 0, "Eastwatch", 40, 40);
|
||||
TripPath path = TripPathBuilder.Build(trip, FakeWalk, net);
|
||||
Check(path.Hub[1] != null && path.Hub[1]!.Length >= 2, "the walk inside comes from townnet.json");
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, path, net);
|
||||
List<NavPoint> pts = r.Route.Points;
|
||||
var portals = pts.Where(p => p.Type == NavPointType.PortalNPC).ToList();
|
||||
Check(r.StoppedAt == -1 && portals.Count == 2, "two portal steps: " + r.StopReason);
|
||||
Check(portals[0].TargetName == "Portal to Town Network" && portals[1].TargetName == "Portal to Eastwatch", "into the network, then the exit by name");
|
||||
int exit = pts.IndexOf(portals[1]), entry = pts.IndexOf(portals[0]);
|
||||
Check(exit - entry >= 2, "waypoints inside the network between them");
|
||||
// Inside: the network's landblock 0x0007 (coordinates the way RynthAi reads a dungeon pose).
|
||||
// The stored walk (60,-70) to (70,-70) to (86.5,-70) is one straight line: thinned to its end,
|
||||
// stopped 2 yd short of the exit portal.
|
||||
NavCoordinateHelper(0x0007016Bu, 84.5, -70, out double ins, out double iew);
|
||||
Check(pts.Skip(entry + 1).Take(exit - entry - 1).Any(p => Math.Abs(p.NS - ins) < 0.001 && Math.Abs(p.EW - iew) < 0.001), "inside points in dungeon coordinates");
|
||||
NavCoordinateHelper(0x0007016Bu, 86.5, -70, out double xns, out double xew);
|
||||
Check(Math.Abs(portals[1].PortalExitNS - xns) < 1e-6 && Math.Abs(portals[1].PortalExitEW - xew) < 1e-6, "the exit portal where it stands");
|
||||
|
||||
// Without townnet.json: stop before the network, say why.
|
||||
NavRouteExport.Result none = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null);
|
||||
Check(none.StoppedAt == 1 && none.StopReason.Contains("Town Network"), "no network data: stops at it: " + none.StopReason);
|
||||
Check(none.Route.Points.Count > 0 && none.Route.Points[^1].Type == NavPointType.PortalNPC, "...keeping the walk to the entry portal");
|
||||
}
|
||||
|
||||
private static void NavCoordinateHelper(uint cell, double x, double y, out double ns, out double ew) => NavCoords.FromCell(cell, x, y, out ns, out ew);
|
||||
|
||||
private static void ExportStopsAtAStepWithNoNavEquivalent()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10.2, 10, false, false, "walk"),
|
||||
new(10.2, 10, false, true, "Some Recall", 3, 20, 20), // index 3: not in the trip's recalls
|
||||
new(20.1, 20, false, false, "walk"),
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "G", 20.1, 20, new List<TripRecall>());
|
||||
NavRouteExport.Result r = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null);
|
||||
Check(r.StoppedAt == 1 && r.StopReason.StartsWith("step 2:") && r.StopReason.Contains("Some Recall"), "stops at the recall it can't cast: " + r.StopReason);
|
||||
Check(r.Route.Points.Count > 0 && r.Route.Points.All(p => p.Type == NavPointType.Point), "the walk before it is kept");
|
||||
|
||||
var other = Trip(steps, 10, 10, "G", 20.1, 20, new List<TripRecall>(), id: 2);
|
||||
NavRouteExport.Result wrong = NavRouteExport.Convert(other, TripPathBuilder.Build(trip, FakeWalk, null), null);
|
||||
Check(wrong.StoppedAt == 0 && wrong.Route.Points.Count == 0, "a path from another trip isn't used");
|
||||
}
|
||||
|
||||
private static void SaveRefusesToOverwrite()
|
||||
{
|
||||
string dir = Path.Combine(Path.GetTempPath(), "rnav-save-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var trip = Trip(new List<RouteStep> { new(10.2, 10, false, false, "walk") }, 10, 10, "G", 10.2, 10);
|
||||
NavRouteParser route = NavRouteExport.Convert(trip, TripPathBuilder.Build(trip, FakeWalk, null), null).Route;
|
||||
Check(NavRouteExport.Save(dir, "To G", route, false, out string path, out bool exists, out string err) && !exists && err == "",
|
||||
"a new file is written (the folder made): " + err);
|
||||
string first = File.ReadAllText(path);
|
||||
Check(NavRouteParser.Load(path).Points.Count == route.Points.Count, "RynthAi loads the file");
|
||||
|
||||
var other = new NavRouteParser { RouteType = NavRouteType.Once };
|
||||
other.Points.Add(new NavPoint { Type = NavPointType.Point, NS = 1, EW = 2 });
|
||||
Check(!NavRouteExport.Save(dir, "To G", other, false, out _, out exists, out _) && exists, "the same name again: refused");
|
||||
Check(File.ReadAllText(path) == first, "...and the file is untouched");
|
||||
Check(!File.Exists(path + ".tmp"), "no temporary file left");
|
||||
Check(NavRouteExport.Save(dir, "To G", other, true, out _, out _, out _) && NavRouteParser.Load(path).Points.Count == 1, "overwrite: replaced");
|
||||
|
||||
Check(NavRouteExport.FileName(" To Holtburg.nav ", out _) == "To Holtburg", "a typed name: trimmed, without .nav");
|
||||
Check(NavRouteExport.FileName("a/b", out string e1) == "" && e1.Length > 0, "a path isn't a name");
|
||||
Check(NavRouteExport.FileName("..", out _) == "" && NavRouteExport.FileName("", out _) == "", "nor .. or nothing");
|
||||
Check(NavRouteExport.SafeName("To Lin: \"Town\"?") == "To Lin Town", "a place's name made safe for a file");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
// ── Markers ──────────────────────────────────────────────────────────
|
||||
|
||||
private static (PlannedTrip Trip, TripPath Path) MarkerTrip()
|
||||
{
|
||||
var steps = new List<RouteStep>
|
||||
{
|
||||
new(10, 10, false, true, "Lifestone Recall", 0, 20, 20),
|
||||
new(20.5, 20, true, false, "Portal to Far", -1, 50, 50),
|
||||
new(50.4, 50.3, false, false, "walk"),
|
||||
};
|
||||
var trip = Trip(steps, 10, 10, "Far Goal", 50.4, 50.3, new List<TripRecall> { new("Lifestone Recall", 1635, "", 13) });
|
||||
return (trip, TripPathBuilder.Build(trip, FakeWalk, null));
|
||||
}
|
||||
|
||||
private static void MarkersBuiltFromTheTrip()
|
||||
{
|
||||
var (trip, path) = MarkerTrip();
|
||||
MarkerSnapshot bare = PathMarkers.Build(trip, null, null);
|
||||
Check(!bare.HasPath && bare.Marks.Length == 3, $"without the path: the steps' markers only ({bare.Marks.Length})");
|
||||
Check(bare.Marks[0].Kind == MarkKind.Recall && bare.Marks[0].Label.StartsWith("RECALL LIFESTONE") && bare.Marks[0].Label.Length <= PathMarkers.MaxLabelChars,
|
||||
"the recall, where it's cast: " + bare.Marks[0].Label);
|
||||
Check(bare.Marks[1].Kind == MarkKind.Portal && bare.Marks[1].Label.StartsWith("PORTAL"), "the portal at its entrance");
|
||||
Check(bare.Marks[2].Kind == MarkKind.Goal && bare.Marks[2].Label == "FAR GOAL", "the goal");
|
||||
Check(bare.Marks.All(m => !m.LineToNext), "no lines over ground not worked out yet");
|
||||
|
||||
MarkerSnapshot s = PathMarkers.Build(trip, path, null);
|
||||
Check(s.HasPath && s.Marks.Length > 6, $"with the path: the waypoints too ({s.Marks.Length})");
|
||||
int portal = Array.FindIndex(s.Marks, m => m.Kind == MarkKind.Portal);
|
||||
Check(!s.Marks[portal].LineToNext && !s.Marks[0].LineToNext, "no line across a teleport (after the portal, after the recall)");
|
||||
Check(s.Marks[portal - 1].LineToNext && s.Marks[portal - 1].Kind == MarkKind.Waypoint, "a line into the portal");
|
||||
Check(s.Marks.Count(m => m.Kind == MarkKind.Goal) == 1 && s.Marks[^1].Kind == MarkKind.Goal, "the goal last");
|
||||
for (int i = 1; i < s.Marks.Length; i++)
|
||||
if (s.Marks[i].P.FlatDistance(s.Marks[i - 1].P) < 0.99) { Check(false, $"two markers on one spot ({i})"); break; }
|
||||
Check(PathMarkers.Build(trip, TripPathBuilder.Build(Trip(trip.Steps.ToList(), 10, 10, "x", 1, 1, id: 9), FakeWalk, null), null).HasPath == false,
|
||||
"another trip's path isn't drawn");
|
||||
}
|
||||
|
||||
private static void MarkersEmitNearTheCharacter()
|
||||
{
|
||||
var (trip, path) = MarkerTrip();
|
||||
MarkerSnapshot s = PathMarkers.Build(trip, path, null);
|
||||
WorldPt landing = WorldPt.FromMap(20.3, 20); // on the walk from the recall's landing to the portal, 48 yd short of it
|
||||
var rec = new Recorder();
|
||||
int rings = PathMarkers.Emit(s, new MarkerView(landing.X, landing.Y, 5.0, -1, true, true), rec);
|
||||
Check(rings > 3 && rec.Rings.Count == rings, $"rings near the character ({rings})");
|
||||
Check(rec.Lines.Count > 2, "lines between them");
|
||||
Check(rec.Lines[0].C == PathMarkers.GuideColor, "the guide line goes in first");
|
||||
float lx = (float)(landing.X - Math.Floor(landing.X / 192) * 192), lz = (float)(landing.Y - Math.Floor(landing.Y / 192) * 192);
|
||||
Check(Math.Abs(rec.Lines[0].X1 - lx) < 0.01 && Math.Abs(rec.Lines[0].Z1 - lz) < 0.01, "...from the character's feet, in the landblock's frame");
|
||||
Check(rec.Rings.Any(r => r.C == PathMarkers.PortalColor), "the portal in its own colour");
|
||||
Check(rec.Rings.All(r => r.X > -200 && r.X < 400 && r.Z > -200 && r.Z < 400 && Math.Abs(r.Y - 5.1f) < 0.01), "landblock-local, at path height");
|
||||
Check(rec.Tris > 0, "the portal's label drawn (triangles)");
|
||||
Check(!rec.Rings.Any(r => r.C == PathMarkers.GoalColor), "the goal, far away, isn't drawn");
|
||||
|
||||
var off = new Recorder();
|
||||
PathMarkers.Emit(s, new MarkerView(landing.X, landing.Y, 5.0, -1, false, false), off);
|
||||
Check(off.Tris == 0 && off.Lines.All(l => l.C != PathMarkers.GuideColor), "labels and guide off: neither");
|
||||
|
||||
WorldPt far = WorldPt.FromMap(80, 80);
|
||||
var none = new Recorder();
|
||||
Check(PathMarkers.Emit(s, new MarkerView(far.X, far.Y, 0, -1, true, true), none) == 0 && none.Lines.Count == 0, "nothing far from the trip");
|
||||
|
||||
// A long dense walk: at most MaxWaypointRings rings.
|
||||
var many = new List<Mark>();
|
||||
for (int i = 0; i < 200; i++) many.Add(new Mark(new WorldPt(1000 + i, 1000, 1), MarkKind.Waypoint, "", 0, true));
|
||||
var dense = new MarkerSnapshot(5, true, many.ToArray());
|
||||
var cap = new Recorder();
|
||||
PathMarkers.Emit(dense, new MarkerView(1100, 1000, 1, 100, false, false), cap);
|
||||
Check(cap.Rings.Count <= PathMarkers.MaxWaypointRings + 1 && cap.Lines.Count <= PathMarkers.MaxLines, $"capped ({cap.Rings.Count} rings, {cap.Lines.Count} lines)");
|
||||
Check(cap.Rings.Count(r => r.C == PathMarkers.NextColor) == 1, "the next waypoint in red");
|
||||
}
|
||||
|
||||
private static void MarkersNextWaypointAdvances()
|
||||
{
|
||||
var marks = new List<Mark>();
|
||||
for (int i = 0; i <= 10; i++) marks.Add(new Mark(new WorldPt(1000 + i * 10, 1000, 1), MarkKind.Waypoint, "", 0, true));
|
||||
marks.Add(new Mark(new WorldPt(1100, 1010, 1), MarkKind.Portal, "PORTAL X", 0, false));
|
||||
marks.Add(new Mark(new WorldPt(3000, 3000, 1), MarkKind.Goal, "G", 1, false));
|
||||
var s = new MarkerSnapshot(1, true, marks.ToArray());
|
||||
int next = PathMarkers.Advance(s, -1, 0, 1000, 1000);
|
||||
Check(next == 1, $"standing on the first: the next is the second ({next})");
|
||||
next = PathMarkers.Advance(s, next, 0, 1033, 1001);
|
||||
Check(next == 4, $"part way along: the one ahead ({next})");
|
||||
Check(PathMarkers.Advance(s, next, 0, 1005, 1000) == 4, "never back");
|
||||
Check(PathMarkers.Advance(s, next, 0, 1100, 1009) == 11, "at the end: the portal (the step's own marker)");
|
||||
Check(PathMarkers.Advance(s, 11, 1, 2900, 2900) == 12, "next step: its first marker");
|
||||
Check(PathMarkers.Advance(s, 0, 7, 0, 0) == -1, "a step with no markers: none");
|
||||
}
|
||||
|
||||
private static void MarkersClearOffTheTrip()
|
||||
{
|
||||
var (trip, path) = MarkerTrip();
|
||||
uint startLb = (trip.StartCell >> 16) & 0xFFFF;
|
||||
Check(trip.Covers(startLb, path, null), "where it starts");
|
||||
Check(trip.Covers(WorldPt.FromMap(20, 20).Landblock, path, null), "the recall's landing");
|
||||
Check(trip.Covers(WorldPt.FromMap(35, 35).Landblock, path, null) == false, "between the portal and its landing (a teleport) isn't on it");
|
||||
Check(trip.Covers(WorldPt.FromMap(50.2, 50.1).Landblock, path, null), "the last walk");
|
||||
Check(!trip.Covers(WorldPt.FromMap(-60, -60).Landblock, path, null), "a teleport elsewhere isn't");
|
||||
Check(trip.Covers(0, path, null), "portal space (landblock 0) doesn't count against it");
|
||||
|
||||
TownNet net = TownNet.Parse(SmallTownNet(), out _)!;
|
||||
var steps = PortalRoute.Plan(NoPortals, null, net.Links(90, false, null), 0, 0, 40, 40, out _, out _);
|
||||
var hubTrip = Trip(steps, 0, 0, "Eastwatch", 40, 40);
|
||||
Check(hubTrip.Covers(0x0007, null, net.Contains), "inside the Town Network on a trip that takes it");
|
||||
Check(!trip.Covers(0x0007, path, net.Contains), "...but not on one that doesn't");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue