Snapshot for release 2026.10.27.1 (internal 48d0d60)

This commit is contained in:
Tom Bohar 2026-10-27 08:41:02 -04:00
commit 2dd532963f
31 changed files with 2995 additions and 118 deletions

View file

@ -2109,6 +2109,15 @@ public partial class BuffManager : IDisposable
// dropping to the top-off line (Top Stam can be lower than Re-stam To).
if (run && s.RestamTo > s.RestamAt && stamPct < s.RestamTo && casts < RestamRunMaxCasts)
return Math.Max(s.RestamTo, s.TopOffStam);
// Under Re-stam At with no monster in range starts one too (Drakkon, 10-23): the last swing, or a
// Stamina to Health just before the kill (174 stamina at once), took it there, so the fight never
// started the recharge, and the top-off stopped at Top Stam 60 instead of Re-stam To 90.
if (s.RestamTo > s.RestamAt && stamPct < s.RestamAt)
{
run = true;
casts = 0;
return Math.Max(s.RestamTo, s.TopOffStam);
}
run = false;
return s.TopOffStam;
}
@ -5221,6 +5230,9 @@ public partial class BuffManager : IDisposable
_buffStanceStuckSince = Now;
_buffStanceStuckStartMs = ActionPacer.NowMs();
}
// No Magic request for a minute (buffing gave up or was taken over): that episode is over, this is a new one.
if (_buffStanceStuckSince != DateTime.MinValue && (Now - _lastBuffStanceAttempt).TotalMilliseconds > StanceEpisodeGapMs)
EndStanceEpisode();
double stuckMs = _buffStanceStuckSince == DateTime.MinValue ? 0 : (Now - _buffStanceStuckSince).TotalMilliseconds;
// Capped re-equip recovery (mirrors CombatManager): handles the rare
@ -5577,8 +5589,25 @@ public partial class BuffManager : IDisposable
bool first = _lastSeenMode == -1; // the first read after a load is not a change
_lastSeenMode = m;
if (!first) _modeChangedAt = Now;
// In Magic: a stance episode is over, whoever got there. EnsureMagicMode ends it only when it runs in
// Magic itself; when the cast went out from another step, or combat took the stance back to its weapons
// first, the clock kept running and the next buff, 18 minutes later, logged "stuck 1123s". The
// launcher's wedge rule (a stance stuck over 300 s = an item-action hard lock) killed Drakkon on it (10-23).
if (m == CombatMode.Magic) EndStanceEpisode();
}
/// <summary>The stance-stuck bookkeeping back to "no episode" (Magic was reached).</summary>
private void EndStanceEpisode()
{
_buffStanceConsecutiveFails = 0;
_buffStanceStuckSince = DateTime.MinValue;
_buffStanceReEquips = 0;
_buffStanceWedgeWarned = false;
}
/// <summary>A stance request after this long without one starts a new episode (the backoff's longest wait is 30 s).</summary>
private const double StanceEpisodeGapMs = 60_000;
/// <summary>
/// The wand is in hand after a swap through peace: Magic is asked for now, from the swap itself (it
/// can run before the cast gates, which the pacer holds while our own peace request settles: 0.75 s

View file

@ -583,6 +583,46 @@ public partial class CombatManager : IDisposable
private const double KILL_CONFIDENCE = 0.80; // predict kill if remaining HP <= avg cast damage * this
private const int KILL_MIN_SAMPLES = 3; // need this many learned hits before trusting the avg
// A boss swapped off as dead with a third of its health left (report R-20261025-183343-727b,
// Conquest, 2026-10-25): "Predicted kill shot 0x80621EBC 'Curator of Torment' (cast#37
// hp~450250 dealt~294989)". Path A (casts-to-kill) fires on the cast COUNT alone: the learned
// average said ~37 Flame Bolts kill a Curator (kills other players helped with teach a low
// count), so cast #37 was "the kill" although the damage math said ~155,000 HP were left and
// one bolt does 5-12k, and the server's own health (34% on the re-lock) agreed. Now either
// prediction is called off when the evidence we have says this cast can't finish it: the
// fight target's fresh server health, or (once damage has landed) the HP pool minus the
// damage dealt, leaves more than KILL_VETO_REACH casts' worth: what is left after this cast
// must be under half a cast (the margin for the roll: earlier low rolls, this one high). So a
// normal mob's finishing cast still swaps, and a one-shot (nothing landed yet) keeps path A.
private const double KILL_VETO_REACH = 1.5;
private int _killShotVetoLoggedFor; // fight target the "not predicted" line was logged for (once a fight)
// The fight target's last SERVER health (OnUpdateHealth via the plugin; ACE sends it only for
// the selected target) and when it came, and when our last hit on it landed: a reading older
// than the last hit doesn't count that hit, and one from before the fight isn't this fight's.
private float _fightHealth = -1f;
private DateTime _fightHealthAt = DateTime.MinValue;
private DateTime _fightLastHitAt = DateTime.MinValue;
private const double FightHealthHitSlackMs = 500; // health and the hit's chat line arrive in either order
// The armed cast's own hit (same report): the swap waits for the cast gesture to release,
// and a Flame Bolt's gesture released 800 ms AFTER its bolt had hit ("You singe Curator of
// Torment for 7883 points" at 58.107, swap at 58.920). ACE sends the killer the death
// message instead of a damage line on a killing blow, so a damage line on the armed target
// means it survived the cast that was to kill it: the swap is called off. A line under
// ArmedHitMinMs after the cast is the previous cast's projectile (no windup is that short).
private const double ArmedHitMinMs = 1000;
// A predicted kill whose death isn't confirmed yet still counts as a monster in range (same
// report): the swap hid the Curator from the scan for PREDICTED_SWAP_SUPPRESS_MS, the
// Rynthid it swapped to died at once, and with the scan empty HasTargets went false, so the
// corpse gate let looting claim a corpse and open it for 4.6 s while the live Curator, 1.9 m
// away, hit the player. Until the kill notice, health 0 or the corpse confirms its death,
// or the suppression ends and the scan has it again, it counts for HasTargets,
// HasCloseThreat (so HasEngageableTarget: combat keeps the tick, no corpse is claimed, no
// starved loot turn) and the idle peace-mode swap. id -> when it was swapped off (TargetClock).
private readonly Dictionary<int, DateTime> _predictedDeathPending = new();
private readonly List<int> _predictedDeathScratch = new();
internal void SetDamageStores(CreatureProfileStore? creatures, MonsterDamageStore? damage)
{
_creatureStore = creatures;
@ -699,8 +739,11 @@ public partial class CombatManager : IDisposable
internal MonsterDamageStore? DamageStore => _damageStore; // per-monster pet choice (PetManager)
internal CreatureProfileStore? CreatureStore => _creatureStore; // learned resists (PetManager)
/// <summary>True when combat has an active target or viable targets nearby. Used to block navigation.</summary>
public bool HasTargets => activeTargetId != 0 || _scannedTargets.Count > 0;
/// <summary>True when combat has an active target or viable targets nearby. Used to block navigation
/// and by the corpse gates. A predicted kill still alive in MonsterRange counts until its death is
/// confirmed (see <see cref="_predictedDeathPending"/>).</summary>
public bool HasTargets => activeTargetId != 0 || _scannedTargets.Count > 0
|| PredictedDeathPendingWithin(System.Math.Max(1, _settings.MonsterRange));
// Monsters that passed range/attackable checks but were LOS-blocked by walls.
// Non-zero means a monster is nearby but not yet visible — nav should stop.
@ -715,9 +758,76 @@ public partial class CombatManager : IDisposable
{
for (int i = 0; i < _scannedTargets.Count; i++)
if (_scannedTargets[i].Distance <= yd) return true;
return PredictedDeathPendingWithin(yd);
}
/// <summary>
/// True when a monster swapped off as a predicted kill is, as far as we know, still alive within
/// <paramref name="yd"/>: its death isn't confirmed (kill notice, health 0, corpse, deleted) and
/// the scan suppression from the swap hasn't ended (after that the scan itself has it again).
/// No side effects (the arbiter's pure path); ScanNearbyTargets prunes the map.
/// </summary>
private bool PredictedDeathPendingWithin(double yd)
{
if (_predictedDeathPending.Count == 0) return false;
DateTime now = TargetClock();
int me = unchecked((int)_playerId);
foreach (var kv in _predictedDeathPending)
{
if ((now - kv.Value).TotalMilliseconds > PREDICTED_SWAP_SUPPRESS_MS) continue;
if (!IsLiveMonster(kv.Key)) continue;
if (me == 0 || _worldFilter.Distance(me, kv.Key) > yd) continue;
return true;
}
return false;
}
/// <summary>The object is a monster the server hasn't said is dead (health 0) and isn't a corpse.</summary>
private bool IsLiveMonster(int id)
{
var wo = _worldFilter[id];
return wo != null && (int)wo.ObjectClass == (int)AcObjectClass.Monster
&& _worldFilter.GetHealthRatio(id) != 0f;
}
/// <summary>
/// ScanNearbyTargets: drop pending predicted kills that are confirmed dead or whose window is
/// over. One that is still alive at the end of its window is back in the scan from this tick
/// (its suppression ended), which the log says, so combat goes back to it at once.
/// </summary>
private void PrunePredictedDeaths()
{
if (_predictedDeathPending.Count == 0) return;
DateTime now = TargetClock();
_predictedDeathScratch.Clear();
foreach (var kv in _predictedDeathPending)
{
bool alive = IsLiveMonster(kv.Key);
bool over = (now - kv.Value).TotalMilliseconds > PREDICTED_SWAP_SUPPRESS_MS;
if (alive && !over) continue;
_predictedDeathScratch.Add(kv.Key);
if (!alive) continue; // health 0 or the corpse: dead after all, nothing to say
// Alive at the end of the window: lift the swap's suppression now, whatever RynthClock
// says (TargetClock is that clock outside tests). A confirmed kill took the id out of
// this map in OnKillNotification, so its longer suppression is never lifted here.
_recentlyKilled.Remove(kv.Key);
_host.Log($"[RynthAi] Predicted kill of 0x{(uint)kv.Key:X8} '{_worldFilter[kv.Key]?.Name}' not confirmed " +
$"{(now - kv.Value).TotalSeconds:0.0} s after the swap and it is still alive: it is a target again.");
}
for (int i = 0; i < _predictedDeathScratch.Count; i++)
_predictedDeathPending.Remove(_predictedDeathScratch[i]);
}
/// <summary>A predicted kill was hit after the swap (a damage line, which a killing blow never
/// sends): it is alive. Back in the scan now, not at the end of the suppression window.</summary>
private void NotePredictedKillSurvived(int id, int amount)
{
if (id == 0 || !_predictedDeathPending.Remove(id)) return;
_recentlyKilled.Remove(id);
_host.Log($"[RynthAi] Predicted kill of 0x{(uint)id:X8} '{_worldFilter[id]?.Name}' took a {amount}-point hit after the swap: " +
"it is alive, a target again.");
}
/// <summary>True only when actively attacking a specific target. Unlike HasTargets, this is false between kills even when more monsters are scanned nearby.</summary>
public bool IsActivelyEngaged => activeTargetId != 0;
@ -937,6 +1047,7 @@ public partial class CombatManager : IDisposable
for (int i = 0; i < _killPruneScratch.Count; i++)
_recentlyKilled.Remove(_killPruneScratch[i]);
}
PrunePredictedDeaths(); // before the loop: a predicted kill still alive is scanned again this tick
_scannedTargets.Clear();
_nearbyNoLos = 0;
@ -1135,6 +1246,7 @@ public partial class CombatManager : IDisposable
{
int id = (int)objectId;
_recentlyKilled.Remove(id);
_predictedDeathPending.Remove(id); // gone (died and despawned, or out of view): not a monster in range
_hitAt.Remove(id);
_blacklistManager.ForgetTarget(id);
Ghosts.NoteDeleted(id);
@ -1328,6 +1440,12 @@ public partial class CombatManager : IDisposable
{ "Bludgeon", new[] { "Tectonic Rifts", "Tectonic Rifts II" } },
};
/// <summary>The level-5 rings without a lore name (SpellData 3805-3808); Cold, Blade and Bludgeon have none.</summary>
private static readonly Dictionary<string, string> PlainRings = new(StringComparer.OrdinalIgnoreCase)
{
{ "Fire", "Flame Ring" }, { "Acid", "Acid Ring" }, { "Pierce", "Force Ring" }, { "Lightning", "Lightning Ring" },
};
private static readonly Dictionary<string, string[]> VoidSpellShapes = new(StringComparer.OrdinalIgnoreCase)
{
{ "Nether", new[] { "Nether Arc", "Nether Ring", "Nether Streak", "Nether Bolt", "Nether Blast" } },
@ -1491,7 +1609,14 @@ public partial class CombatManager : IDisposable
// spell landed. Without it, three casts that hit after the player clicked a corpse were
// "no damage": the live monster was blacklisted and combat stopped (2026-10-21, Conquest).
if (onFight && amount > 0)
{
ReportDamageOnTarget(_fightTargetId);
NoteFightHit(amount); // the kill-shot health check's clock; calls off a swap the hit disproves
}
// A damage line is never a killing blow's (ACE sends the death message then), so a hit on
// a monster we swapped off as a predicted kill says it is alive (R-20261025-183343-727b).
if (amount > 0 && victimId != 0 && victimId != _fightTargetId)
NotePredictedKillSurvived(victimId, amount);
if (!onFight && !onLastFight)
{
@ -2403,6 +2528,9 @@ public partial class CombatManager : IDisposable
_fightDamage = 0;
_fightCastCount = 0;
_fightAppraiseRequested = false;
_fightHealth = -1f;
_fightHealthAt = DateTime.MinValue;
_fightLastHitAt = DateTime.MinValue;
_predictKillSwap = false;
_predictKillSwapArmed = false;
// Clear the stance-stuck timer — it arms during the normal NonCombat→Magic
@ -2434,6 +2562,7 @@ public partial class CombatManager : IDisposable
_recentlyKilled[swapId] = RynthClock.Now.AddMilliseconds(PREDICTED_SWAP_SUPPRESS_MS);
ForgetScanned(swapId);
_predictedSwapAt[swapId] = TargetClock(); // fought again later = it didn't die (PredictionFailed)
_predictedDeathPending[swapId] = TargetClock(); // still a monster in range until its death is confirmed
// Queue this predicted one-shot so it's CREDITED when its death confirms —
// we may swap away before its KillerNotification. Capture the name LIVE
// from the world filter (_fightTargetName is often empty this early).
@ -2511,6 +2640,15 @@ public partial class CombatManager : IDisposable
bool curMatches = curName.Length > 0
&& deathMessage.IndexOf(curName, StringComparison.OrdinalIgnoreCase) >= 0;
// The predicted kill's death is confirmed (R-20261025-183343-727b): no longer a monster in
// range for the corpse gate, and the scan stays off it for a confirmed kill's window while
// the corpse forms (the swap gave it 2 s). Not when the notice names the current target
// too (a same-named swarm): it may be the current target's, so the predicted one stays
// pending until its own health, corpse or window says.
if (pendingKillId != 0 && !(curMatches && tid != pendingKillId)
&& _predictedDeathPending.Remove(pendingKillId))
_recentlyKilled[pendingKillId] = nowKill.AddMilliseconds(RECENTLY_KILLED_SUPPRESS_MS);
// (2) The current target died (its name is in the message).
if (!recorded && curMatches && _fightTargetWcid != 0 && _fightCastCount > 0)
{
@ -2671,6 +2809,7 @@ public partial class CombatManager : IDisposable
int tid = activeTargetId;
if (tid == 0 || tid != _fightTargetId) return;
NoteFightHit((int)Math.Round(damage));
_fightDamage += damage;
// War magic sends NO 0x01B1 (its damage comes from the chat parse), so a structured
@ -2732,6 +2871,9 @@ public partial class CombatManager : IDisposable
_fightTargetMaxHp = 0;
_fightHpEstimated = false;
_fightAppraiseRequested = false;
_fightHealth = -1f;
_fightHealthAt = DateTime.MinValue;
_fightLastHitAt = DateTime.MinValue;
_predictKillSwap = false;
_fightTargetName = "";
_fightStartedAt = default;
@ -2844,6 +2986,81 @@ public partial class CombatManager : IDisposable
}
}
/// <summary>
/// A damage line landed on the fight target. Stamps the hit (a server health reading older
/// than it doesn't count it), and when the swap armed by a predicted kill shot is waiting on
/// this target and the line comes ArmedHitMinMs or more after the arming cast, that cast hit
/// without killing (a killing blow sends the death message, not a damage line): the swap is
/// called off and the bot keeps casting at it (R-20261025-183343-727b).
/// </summary>
private void NoteFightHit(int amount)
{
_fightLastHitAt = TargetClock();
if (!_predictKillSwapArmed || _fightTargetId == 0 || _predictArmTargetId != _fightTargetId) return;
double sinceCast = (RynthClock.Now - _predictArmCastAt).TotalMilliseconds;
if (sinceCast < ArmedHitMinMs) return;
_predictKillSwapArmed = false;
_host.Log($"[RynthAi] Predicted kill shot 0x{(uint)_fightTargetId:X8} '{_worldFilter[_fightTargetId]?.Name}' called off: " +
$"its cast hit for {amount} {sinceCast:0} ms after it went out and the monster is still alive " +
$"(cast#{_fightCastCount} hp~{_fightTargetMaxHp:0} dealt~{_fightDamage + amount:0}).");
}
/// <summary>The plugin's OnUpdateHealth: the server's health for <paramref name="id"/>. Kept for the
/// fight target only (the kill-shot check), stamped with when it came.</summary>
internal void NoteServerHealth(int id, float ratio)
{
if (id == 0 || id != _fightTargetId || float.IsNaN(ratio)) return;
_fightHealth = Math.Clamp(ratio, 0f, 1f);
_fightHealthAt = TargetClock();
}
/// <summary>The fight target's server health when it counts every hit landed so far: it came during
/// this fight and no hit landed more than FightHealthHitSlackMs after it.</summary>
private bool TryFreshFightHealth(out float ratio)
{
ratio = _fightHealth;
if (_fightHealthAt == DateTime.MinValue || ratio <= 0f) return false;
return _fightLastHitAt == DateTime.MinValue
|| _fightHealthAt >= _fightLastHitAt.AddMilliseconds(-FightHealthHitSlackMs);
}
/// <summary>
/// The evidence says the cast just fired can't finish the fight target: what is left of it is more
/// than KILL_VETO_REACH casts of <paramref name="perCast"/>. Two sources, either one enough:
/// the fresh server health (with the HP pool, or with the damage dealt when the pool is unknown:
/// dealt / (1 - ratio) is the pool the health implies), and the HP pool minus the damage dealt,
/// once damage has landed (a one-shot has nothing landed and is left to casts-to-kill as before;
/// an HP pool that is off then can't hold it back). Without a per-cast figure there is no check.
/// </summary>
private bool KillShotContradicted(double perCast, out string why)
{
why = "";
if (perCast <= 0) return false;
double reach = perCast * KILL_VETO_REACH;
if (TryFreshFightHealth(out float ratio))
{
double left = _fightTargetMaxHp > 0 ? ratio * _fightTargetMaxHp
: _fightDamage > 0 && ratio < 1f ? _fightDamage * ratio / (1.0 - ratio)
: -1;
if (left > reach)
{
why = $"the server says its health is {ratio * 100f:0}% (~{left:0} HP left)";
return true;
}
}
if (_fightTargetMaxHp > 0 && _fightDamage > 0)
{
double left = _fightTargetMaxHp - _fightDamage;
if (left > reach)
{
why = $"~{left:0} of its ~{_fightTargetMaxHp:0} HP are left after ~{_fightDamage:0} dealt" +
(_fightHpEstimated ? " (the HP is the tier estimate)" : "");
return true;
}
}
return false;
}
/// <summary>
/// After firing an offensive cast at the active target, decide whether that
/// cast is expected to finish the mob. If so — and another target is in
@ -2859,27 +3076,42 @@ public partial class CombatManager : IDisposable
if (PredictionFailed(activeTargetId)) return; // survived a predicted kill — stay on it
if (!HasAlternateTarget(activeTargetId)) return; // nothing to swap to — keep casting
// Both paths need the evidence not to say otherwise (KillShotContradicted, 2026-10-25): one
// cast's damage is the learned average, else this fight's own average over the casts that
// have landed (the one just fired hasn't).
double expected = _damageStore.GetAvgDamage(weaponId, _fightTargetWcid, element, tier, out int dmgSamples);
bool learned = dmgSamples >= KILL_MIN_SAMPLES && expected > 0;
double perCast = learned ? expected
: _fightCastCount > 1 && _fightDamage > 0 ? _fightDamage / (_fightCastCount - 1)
: 0;
// (A) Casts-to-kill: we've fired the number of casts this wcid typically
// takes to die from this weapon+spell. Catches ONE-SHOTS (avg≈1 → swap
// right after cast 1), which the damage math below can't — nothing has
// landed when we predict, so it has no remaining-HP signal yet.
// landed when we predict, so it has no remaining-HP signal yet. On its own
// it is only a count (the Curator's cast #37), hence the evidence check.
double avgCasts = _damageStore.GetAvgCastsToKill(weaponId, _fightTargetWcid, element, tier, out int killSamples);
if (killSamples >= KILL_MIN_SAMPLES && avgCasts > 0
&& _fightCastCount >= (int)Math.Round(avgCasts))
{
_predictKillSwap = true;
return;
}
bool byCount = killSamples >= KILL_MIN_SAMPLES && avgCasts > 0
&& _fightCastCount >= (int)Math.Round(avgCasts);
// (B) Damage-based: remaining HP is within one comfortable cast. Precise
// for multi-cast fights once some damage has landed.
if (_fightTargetMaxHp > 0)
bool byDamage = _fightTargetMaxHp > 0 && learned
&& _fightTargetMaxHp - _fightDamage <= expected * KILL_CONFIDENCE;
if (!byCount && !byDamage) return;
if (KillShotContradicted(perCast, out string why))
{
double expected = _damageStore.GetAvgDamage(weaponId, _fightTargetWcid, element, tier, out int dmgSamples);
double remaining = _fightTargetMaxHp - _fightDamage;
if (dmgSamples >= KILL_MIN_SAMPLES && expected > 0 && remaining <= expected * KILL_CONFIDENCE)
_predictKillSwap = true;
if (_killShotVetoLoggedFor != _fightTargetId)
{
_killShotVetoLoggedFor = _fightTargetId;
_host.Log($"[RynthAi] Kill shot not predicted for 0x{(uint)_fightTargetId:X8} '{_worldFilter[_fightTargetId]?.Name}' " +
$"(cast#{_fightCastCount}" + (byCount ? $", ~{avgCasts:0.#} casts kill one" : "") +
$", one cast ~{perCast:0}): {why}. Staying on it.");
}
return;
}
_predictKillSwap = true;
}
/// <summary>True if a scanned, non-suppressed target other than <paramref name="excludeId"/> is available to swap to.</summary>
@ -2913,6 +3145,7 @@ public partial class CombatManager : IDisposable
if (!_predictedSwapAt.TryGetValue(id, out DateTime swappedAt)) return false;
_predictedSwapAt.Remove(id);
_predictedDeathPending.Remove(id);
_predictionFailedAt[id] = now;
float hp = _worldFilter.GetHealthRatio(id);
string health = hp >= 0f ? $"health {hp * 100f:0}%" : "health unknown";
@ -2946,6 +3179,19 @@ public partial class CombatManager : IDisposable
/// <summary>Test seam: the confirmed predicted-kill swap off the fight target.</summary>
internal void PredictedSwapForTest() => ExecuteDeferredKillSwap();
/// <summary>Test seam: a predicted kill shot armed by a cast at the fight target <paramref name="castAgoMs"/> ago
/// (as the attack block arms it), waiting for the cast to be confirmed.</summary>
internal void ArmPredictedSwapForTest(double castAgoMs)
{
_predictKillSwapArmed = true;
_predictSwapGestureSeen = false;
_predictArmTargetId = activeTargetId;
_predictArmCastAt = RynthClock.Now.AddMilliseconds(-castAgoMs);
}
/// <summary>Tests: a predicted kill-shot swap is armed and waiting.</summary>
internal bool PredictedSwapArmed => _predictKillSwapArmed;
/// <summary>Floor between attack commands for the first cast at a new target when the server
/// gates are available (see <see cref="AttackIntervalMs"/>). Only bounds how fast a refused
/// cast could be retried; a refusal sets the target as the last attacked, so the retry waits
@ -3166,8 +3412,11 @@ public partial class CombatManager : IDisposable
if (CurrentCombatMode == CombatMode.NonCombat)
_idlePeaceAttempts = 0; // reached peace — the next idle request starts fresh
bool peaceHeld = false;
// !HasTargets, not an empty scan: a predicted kill still alive and in range (its death
// unconfirmed, scan-suppressed for a moment) is fought again in a second or two, and a
// peace swap now would be undone at once (R-20261025-183343-727b).
if (_settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat
&& _scannedTargets.Count == 0 && BusyCount == 0
&& !HasTargets && BusyCount == 0
&& RynthClock.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode
{
try { peaceHeld = HoldIdlePeace?.Invoke() == true; } catch { peaceHeld = false; }
@ -3179,7 +3428,7 @@ public partial class CombatManager : IDisposable
}
if (!peaceHeld) _idlePeaceHeldLogged = false;
if (!peaceHeld && _settings.PeaceModeWhenIdle && CurrentCombatMode != CombatMode.NonCombat
&& _scannedTargets.Count == 0 && BusyCount == 0
&& !HasTargets && BusyCount == 0
&& RynthClock.Now >= _navMagicWantedUntil) // a nav recall wants Magic mode
{
// Defer idle peace-swap while a cast at the just-dropped target is still
@ -7304,6 +7553,8 @@ public partial class CombatManager : IDisposable
/// <summary>Tests: the wall-path count instead of the scan (the scan needs a live world).</summary>
internal Func<int>? WallPathCountOverride { get; set; }
/// <summary>Tests: the monsters in ring range instead of the landscape count.</summary>
internal Func<int>? RingCountOverride { get; set; }
/// <summary>Monsters (the target included) in a wall's path toward <paramref name="targetId"/>:
/// ahead of the caster, within <paramref name="rangeYards"/>, and within <see cref="WallHalfWidth"/>
@ -7584,7 +7835,22 @@ public partial class CombatManager : IDisposable
// Ring override: when UseRing is enabled, check if enough monsters are within
// ring range. If so, upgrade to ring; otherwise keep the base shape (arc/streak/blast/bolt).
bool ringDue = rule != null && rule.UseRing && _settings.RingRange > 0
&& CountMonstersInRange(_settings.RingRange) >= Math.Max(1, _settings.MinRingTargets);
&& (RingCountOverride?.Invoke() ?? CountMonstersInRange(_settings.RingRange)) >= Math.Max(1, _settings.MinRingTargets);
// Like a wall, a ring is due only when one is known: Void Magic has no ring at all (no
// "Nether Ring" in SpellData.txt), so a Void caster with Use Ring on cast nothing once a
// pack came into ring range and stood in the fight ("No spell found: elem=Nether",
// #rynth-issues 2026-10-23, DreamWeave). Without one, the rule's other shape is cast.
int ringId = 0;
if (ringDue)
{
ringId = FindRingSpell(element, skill, useVoid);
if (ringId == 0)
{
ringDue = false;
if (_noRingLogged.Add(element + (useVoid ? "/void" : "")))
_host.Log($"[CombatCast] no {element} ring spell known{(useVoid ? " (Void Magic has none)" : "")}: casting the rule's other shape when a ring is due");
}
}
// Wall override (Wall Range on): a wall when enough monsters are in its path toward the
// target and the character knows a wall of this element (none for Nether). Asked only for a
@ -7611,15 +7877,15 @@ public partial class CombatManager : IDisposable
return wallId;
}
if (!TryGetShapeBase(element, shapeIdx, useVoid, out string baseName, out string? t7, out bool forcedWar)) return 0;
if (forcedWar) skill = AcSkillType.WarMagic;
if (shapeIdx == ShapeRing)
{
int ringId = FindBestRingSpell(element, skill);
if (ringId != 0) { isRing = true; castShape = ShapeRing; return ringId; }
isRing = true; castShape = ShapeRing;
return ringId;
}
if (!TryGetShapeBase(element, shapeIdx, useVoid, out string baseName, out string? t7, out bool forcedWar)) return 0;
if (forcedWar) skill = AcSkillType.WarMagic;
// Strict TYPE adherence: cast ONLY the shape configured in the
// Monsters tab (Arc/Bolt/Streak/Blast) — plus the ring override handled
// above. No cross-shape fallthrough; that was casting Streak when
@ -7651,6 +7917,20 @@ public partial class CombatManager : IDisposable
}
private readonly HashSet<string> _blastFallbackLogged = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _noRingLogged = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The best ring of <paramref name="element"/> the character knows (0 = none): War's lore
/// rings, else the generic "{ring base} {tier}" of the shape table (the Void row's
/// "Nether Ring" / "Corrosion Ring" exist on no known server, so a Void caster gets 0).
/// </summary>
private int FindRingSpell(string element, AcSkillType skill, bool useVoid)
{
if (!TryGetShapeBase(element, ShapeRing, useVoid, out string ringBase, out string? ringT7, out bool forcedWar)) return 0;
if (forcedWar) skill = AcSkillType.WarMagic;
int id = FindBestRingSpell(element, skill);
return id != 0 ? id : FindBestOffensiveSpellId(ringBase, skill, ringT7);
}
private int FindBestRingSpell(string element, AcSkillType skill)
{
@ -7666,17 +7946,26 @@ public partial class CombatManager : IDisposable
int maxTier = EffectiveMaxTier(skill);
// The rings are level 5 and 7 (SpellData: power 200 and 300): the named one (Cassius' Ring of
// Fire, Halo of Frost, ...) and the plain one (Flame Ring, Acid Ring, Force Ring, Lightning Ring)
// at 5, the named "II" at 7. The named ring used to wait for tier 6, and the plain ones were
// looked for with numerals ("Ring of Fire V"), names no server has: a caster at tier 5 never
// got a ring (2026-10-25).
if (maxTier >= 7)
{
int id = TrySpellByName(loreNames[1]); if (id != 0) return id;
id = TrySpellByName(loreNames[1].Replace("'", "\u2019")); if (id != 0) return id;
id = TrySpellByName(loreNames[1].Replace("'", "`")); if (id != 0) return id;
}
if (maxTier >= 6)
if (maxTier >= 5)
{
int id = TrySpellByName(loreNames[0]); if (id != 0) return id;
id = TrySpellByName(loreNames[0].Replace("'", "\u2019")); if (id != 0) return id;
id = TrySpellByName(loreNames[0].Replace("'", "`")); if (id != 0) return id;
if (PlainRings.TryGetValue(element, out string? plain))
{
id = TrySpellByName(plain); if (id != 0) return id;
}
}
if (maxTier >= 8)
{

View file

@ -854,6 +854,7 @@ internal sealed unsafe class InstrumentDashboard
if (!open) return;
try
{
KeepPopupOnScreen();
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float w = ImGui.GetContentRegionAvail().X;
Vector2 p = ImGui.GetCursorScreenPos();
@ -1002,6 +1003,7 @@ internal sealed unsafe class InstrumentDashboard
if (!open) return;
try
{
KeepPopupOnScreen(flipDownTo: _charAnchor.Y);
RynthCoreHost host = _d.Host;
bool oracle = host.SetPanelOpen(OracleKey, RynthPanelOpen.Ask) >= 0;
ImGui.TextDisabled("Character");
@ -1027,6 +1029,29 @@ internal sealed unsafe class InstrumentDashboard
}
}
/// <summary>
/// Keeps the current popup inside the game window. ImGui only fits a popup to the screen when
/// it placed the popup itself; one placed with SetNextWindowPos stays where it was put, so the
/// Char menu (opened upward from the icon) ran off the top with the dashboard in the top left
/// corner (#rynth-issues "character window not clamped to screen", 2026-10-23).
/// <paramref name="flipDownTo"/>: for a menu opened upward, the Y to open it downward from
/// when its top is off screen; then it is pushed back inside the edges. Skipped on the
/// appearing frame: the popup isn't measured yet, and moving it then would cancel the pivot
/// ImGui applies once it is.
/// </summary>
private static void KeepPopupOnScreen(float flipDownTo = float.NaN)
{
if (ImGui.IsWindowAppearing()) return;
Vector2 pos = ImGui.GetWindowPos(), size = ImGui.GetWindowSize();
if (size.X <= 0 || size.Y <= 0) return;
Vector2 display = ImGui.GetIO().DisplaySize;
Vector2 p = pos;
if (!float.IsNaN(flipDownTo) && p.Y < 0) p.Y = flipDownTo;
p.X = Math.Clamp(p.X, 0, Math.Max(0, display.X - size.X));
p.Y = Math.Clamp(p.Y, 0, Math.Max(0, display.Y - size.Y));
if (p != pos) ImGui.SetWindowPos(p);
}
private static void PanelItem(RynthCoreHost host, string key, string command)
{
int state = host.SetPanelOpen(key, RynthPanelOpen.Ask);

View file

@ -305,6 +305,42 @@ internal sealed class DungeonGeometry
return false;
}
/// <summary>The height of the cell's floor at (x, y), the floor polygon nearest
/// <paramref name="zRef"/> in height if several are under it (any height apart). False when
/// (x, y) is off the cell's floor or the cell has no floor data.</summary>
internal bool TryCellFloorHeight(uint cell, double x, double y, double zRef, out double h)
{
h = 0;
if (!_floors.TryGetValue(cell, out var list)) return false;
double best = double.MaxValue;
foreach (var v in list)
{
if (!InsidePolygon2D(v, x, y)) continue;
NewellNormal(v, out double nx, out double ny, out double nz);
if (Math.Abs(nz) < 1e-9) continue;
double px = 0, py = 0, pz = 0;
foreach (var q in v) { px += q.X; py += q.Y; pz += q.Z; }
px /= v.Length; py /= v.Length; pz /= v.Length;
double fh = pz - (nx * (x - px) + ny * (y - py)) / nz;
if (Math.Abs(fh - zRef) < best) { best = Math.Abs(fh - zRef); h = fh; }
}
return best < double.MaxValue;
}
/// <summary>The box round the cell's floor polygons (false: no floor data).</summary>
internal bool TryCellFloorBounds(uint cell, out double minX, out double minY, out double maxX, out double maxY)
{
minX = minY = double.MaxValue; maxX = maxY = double.MinValue;
if (!_floors.TryGetValue(cell, out var list)) return false;
foreach (var v in list)
foreach (var q in v)
{
minX = Math.Min(minX, q.X); maxX = Math.Max(maxX, q.X);
minY = Math.Min(minY, q.Y); maxY = Math.Max(maxY, q.Y);
}
return minX <= maxX;
}
/// <summary>True when (x, y) is on the floor of any of <paramref name="cells"/>; also true
/// when none of them has floor data (nothing to check against).</summary>
public bool OnFloorOfAny(IEnumerable<uint> cells, double x, double y, double z)

View file

@ -1,4 +1,4 @@
// Detector C — offline lava/acid hazard-cell detection from EnvCell surface textures.
// Detector C — offline lava/acid hazard-cell detection from EnvCell floor textures.
//
// WHY: AC environmental hazards are server-side `HotSpot` weenies, and ~75/120 templates set
// PropertyBool.Visibility=true, so ACE never broadcasts them to the client (Player_Tracking.cs:58
@ -8,8 +8,18 @@
// the EnvCell, sitting in client_portal.dat. Detector C reads that texture directly and pre-emptively
// marks matching cells hazardous at patrol-build time — no first-hit, no broadcast, no visible object.
//
// FLOORS ONLY (2026-10-23): a cell is a hazard when a texture in HazardTextures.txt is on its
// walkable FLOOR — a render polygon facing up at least as steeply as AC's FloorZ (0.66417) — not
// merely somewhere in its surface palette. The palette also holds the walls' and ceilings' textures
// (and sometimes entries no polygon uses), so the palette test flagged cells for their walls: in
// Tiny Hive (0x0289) the learned 0x0500279D is the Olthoi hive WALL texture (on walls in 3,530
// cells across the dats, on a floor in none) and boxed the patrol in at the entrance.
// The floors come from DungeonLOS.GetCellFloorSurfaces (render polygons carry PosSurface, an
// index into the EnvCell's palette); learning (LearnFromCell) looks at floors too, so it can
// never learn a wall texture.
//
// RESOLUTION CHAIN (all verified):
// EnvCell (cell.dat) -> ushort[numSurfaces] palette
// EnvCell (cell.dat) -> ushort[numSurfaces] palette; CellStruct render polygon PosSurface -> palette index
// -> (0x08000000u | surfIdx) -> Surface file (portal.dat 0x0800xxxx)
// -> Surface.Type (uint @ OFFSET 0, NO leading-id skip)
// if (Type & (Base1Image 0x2 | Base1ClipMap 0x4)) -> OrigTextureId (uint, next) <-- HAZARD KEY
@ -37,8 +47,9 @@ namespace RynthCore.Plugin.RynthAi;
internal static class DungeonHazardSurfaces
{
// Sibling of NavProfiles / DungeonHazards (LegacyDashboardRenderer._navFolder family).
private static readonly string Folder = RynthCore.Install.RynthInstallPaths.RynthAiDir;
private static readonly string SetPath = System.IO.Path.Combine(Folder, "HazardTextures.txt");
// Settable so the offline tests can point it at a scratch folder.
internal static string Folder = RynthCore.Install.RynthInstallPaths.RynthAiDir;
private static string SetPath => System.IO.Path.Combine(Folder, "HazardTextures.txt");
private static readonly object _gate = new();
@ -53,6 +64,11 @@ internal static class DungeonHazardSurfaces
private static uint _cachedLandblock;
private static HashSet<uint>? _cachedCells;
// Per-landblock floor textures: cell -> OrigTextureIds on its walkable floor. Dat-only, so it
// never goes stale; kept for one landblock (the patrol's).
private static uint _floorTexLandblock;
private static Dictionary<uint, HashSet<uint>>? _floorTex;
// ── Hazard-texture set (persistent, user-editable) ─────────────────────────
private static HashSet<uint> Textures()
@ -127,6 +143,7 @@ internal static class DungeonHazardSurfaces
{
"# RynthAi Detector C — hazard floor textures (0x05 OrigTextureId), one hex id per line.",
"# Flag a lava/acid floor with: /ra hazard surfaces then /ra hazard learnhere (or texture add 0x<id>).",
"# Only a texture on a cell's walkable floor marks it; the same texture on walls or ceilings does not.",
};
var sorted = new List<uint>(_hazardTextures!);
sorted.Sort();
@ -205,82 +222,133 @@ internal static class DungeonHazardSurfaces
return result;
}
/// <summary>Distinct non-zero OrigTextureIds present in an EnvCell's surface palette. Never throws.</summary>
private static HashSet<uint> CellTextureSet(DatDatabase? cellDat, DatDatabase? portal, uint cellId)
{
var set = new HashSet<uint>();
foreach (var (_, texId) in GetCellSurfaces(cellDat, portal, cellId))
if (texId != 0) set.Add(texId);
return set;
}
// ── Per-landblock hazard-cell computation ──────────────────────────────────
// ── Floor textures ─────────────────────────────────────────────────────────
/// <summary>
/// Returns (cached) the EnvCells in the landblock whose surface palette contains a flagged
/// hazard texture. Cheap no-op re-call for the same landblock. Pure dat reads. Never throws.
/// (Cached) cell → OrigTextureIds on its walkable floor, for every EnvCell of the landblock
/// that has a textured floor (DungeonLOS.GetCellFloorSurfaces, resolved through portal.dat).
/// Empty without geometry. Never throws.
/// </summary>
public static HashSet<uint> ComputeHazardCells(uint landblockKey, DatDatabase? cellDat, DatDatabase? portal)
public static Dictionary<uint, HashSet<uint>> GetFloorTextures(uint landblockKey, DungeonLOS? los, DatDatabase? portal)
{
lock (_gate)
if (_cachedCells != null && _cachedLandblock == landblockKey) return _cachedCells;
if (_floorTex != null && _floorTexLandblock == landblockKey) return _floorTex;
var cells = new HashSet<uint>();
var map = new Dictionary<uint, HashSet<uint>>();
try
{
if (cellDat != null && portal != null && HazardTextureCount > 0)
if (los != null && portal != null)
{
foreach (uint cellId in cellDat.GetLandblockCellIds(landblockKey))
foreach (var kv in los.GetCellFloorSurfaces(landblockKey))
{
foreach (uint texId in CellTextureSet(cellDat, portal, cellId))
var set = new HashSet<uint>();
foreach (ushort s in kv.Value)
{
if (IsHazardTexture(texId)) { cells.Add(cellId); break; }
uint t = ResolveOrigTextureId(portal, s);
if (t != 0) set.Add(t);
}
if (set.Count > 0) map[kv.Key] = set;
}
}
}
catch { }
lock (_gate) { _cachedCells = cells; _cachedLandblock = landblockKey; }
// Nothing read (geometry not up yet): don't pin an empty answer for this landblock.
if (map.Count > 0)
lock (_gate) { _floorTex = map; _floorTexLandblock = landblockKey; }
return map;
}
/// <summary>OrigTextureIds on one cell's walkable floor (empty when none). For diagnostics. Never throws.</summary>
public static HashSet<uint> GetCellFloorTextures(uint cellId, DungeonLOS? los, DatDatabase? portal)
=> GetFloorTextures(cellId >> 16, los, portal).TryGetValue(cellId, out var set) ? set : new HashSet<uint>();
// ── Per-landblock hazard-cell computation ──────────────────────────────────
/// <summary>
/// Returns (cached) the EnvCells in the landblock whose walkable floor shows a flagged hazard
/// texture. Cheap no-op re-call for the same landblock. Pure dat reads. Never throws.
/// </summary>
public static HashSet<uint> ComputeHazardCells(uint landblockKey, DungeonLOS? los, DatDatabase? portal)
{
lock (_gate)
if (_cachedCells != null && _cachedLandblock == landblockKey) return _cachedCells;
var cells = new HashSet<uint>();
bool settled = false; // cache only a real answer, not "geometry not up yet"
try
{
if (los != null && portal != null)
{
if (HazardTextureCount == 0) settled = true;
else
{
var floors = GetFloorTextures(landblockKey, los, portal);
cells = HazardCellsFrom(floors);
settled = floors.Count > 0;
}
}
}
catch { }
if (settled)
lock (_gate) { _cachedCells = cells; _cachedLandblock = landblockKey; }
return cells;
}
/// <summary>The cells whose floor textures include a flagged hazard texture.</summary>
internal static HashSet<uint> HazardCellsFrom(IReadOnlyDictionary<uint, HashSet<uint>> floorTexByCell)
{
var cells = new HashSet<uint>();
foreach (var kv in floorTexByCell)
foreach (uint t in kv.Value)
if (IsHazardTexture(t)) { cells.Add(kv.Key); break; }
return cells;
}
// ── Learn-here (precision-guarded auto-flag) ───────────────────────────────
/// <summary>
/// Stand in a hazard cell and call this: it flags the cell's surface texture(s) that are RARE
/// across the landblock (the texture only lava/acid cells use), while rejecting the common
/// floor/wall textures. This is the safe auto-bootstrap — it avoids the catastrophic failure of
/// learning a ubiquitous floor texture and banning the whole dungeon. Returns the newly-flagged ids.
/// Stand in a hazard cell and call this: it flags the texture(s) on the cell's FLOOR that are
/// RARE across the landblock's floors (the texture only lava/acid cells use), while rejecting
/// the common floor textures. Wall and ceiling textures are never candidates. This is the safe
/// auto-bootstrap — it avoids the catastrophic failure of learning a ubiquitous floor texture
/// and banning the whole dungeon. Returns the newly-flagged ids.
/// </summary>
public static List<uint> LearnFromCell(uint cellId, DatDatabase? cellDat, DatDatabase? portal,
public static List<uint> LearnFromCell(uint cellId, DungeonLOS? los, DatDatabase? portal,
double rareFractionMax = 0.25)
{
var learned = new List<uint>();
try
{
if (cellDat == null || portal == null) return learned;
uint landblockKey = cellId >> 16;
var freq = new Dictionary<uint, int>();
int totalCells = 0;
foreach (uint cid in cellDat.GetLandblockCellIds(landblockKey))
{
var texs = CellTextureSet(cellDat, portal, cid);
if (texs.Count == 0) continue;
totalCells++;
foreach (uint t in texs) freq[t] = freq.GetValueOrDefault(t) + 1;
}
if (totalCells == 0) return learned;
foreach (uint t in CellTextureSet(cellDat, portal, cellId))
{
double frac = freq.GetValueOrDefault(t) / (double)totalCells;
if (frac <= rareFractionMax && AddHazardTexture(t))
learned.Add(t);
}
if (los == null || portal == null) return learned;
var floors = GetFloorTextures(cellId >> 16, los, portal);
foreach (uint t in RareFloorTextures(cellId, floors, rareFractionMax))
if (AddHazardTexture(t)) learned.Add(t);
}
catch { }
return learned;
}
/// <summary>
/// The textures on <paramref name="cellId"/>'s floor that are on the floor of at most
/// <paramref name="rareFractionMax"/> of the landblock's cells with a textured floor.
/// </summary>
internal static List<uint> RareFloorTextures(uint cellId, IReadOnlyDictionary<uint, HashSet<uint>> floorTexByCell,
double rareFractionMax)
{
var rare = new List<uint>();
if (!floorTexByCell.TryGetValue(cellId, out var here) || here.Count == 0) return rare;
var freq = new Dictionary<uint, int>();
foreach (var texs in floorTexByCell.Values)
foreach (uint t in texs) freq[t] = freq.GetValueOrDefault(t) + 1;
int totalCells = floorTexByCell.Count;
if (totalCells == 0) return rare;
foreach (uint t in here)
if (freq.GetValueOrDefault(t) / (double)totalCells <= rareFractionMax) rare.Add(t);
rare.Sort();
return rare;
}
}

View file

@ -0,0 +1,833 @@
// DungeonPathfinder, portals half: the patrol keeps out of portals (2026-10-23).
//
// Why: a portal in AC fires the moment the character touches it (the portal's collision sphere,
// 1.36 m for the usual portal Setup 0x020005D3, meets the character's 0.48 m spheres), and the
// patrol knew nothing of portals. Tiny Hive (0x0289), coverage Everything: the start cell
// 028902A5 opens north onto a ramp (028902BB) up into a 3 m nook (028902BA) whose back is the
// Surface Portal (0x7028905D, world 494.0, 26300.2, -24.0). The nook is a dead end, so the patrol
// stepped into it: waypoint 1 was the doorway's exit point 1.2 m in, 0.02 m from the portal, and
// the 35 m leg to it ran from the room south of the start straight up the ramp. A client that
// started its lap at waypoint 1 was in portal space 1.5 s later (Tom, 2026-10-23).
//
// Now BuildPatrolRoute takes the portals of the landblock (the live objects; BuildDunPatrol) as
// circles to keep out of: PatrolPortal.Radius, the touch distance plus steering slack
// (PortalKeepOutRadius). Points, legs and floor on the portal's level (PortalLevelBand) count.
// 1. Each room (DungeonRooms) the circle reaches is split by it: its floor, less the circle and
// less a body's width along its edges, falls into parts. A doorway out of the room whose
// passable spots are all inside the circle, or which only reaches a part the patrol doesn't
// keep, is closed: the edge is left out of the cell graph the patrol is laid on. The part
// kept is the start's own (where the character stands), else the one most doorways reach.
// So a portal's nook is a dead end the patrol turns round before, and a corridor a portal
// stands across is walked up to it from either side. Without floor data, a doorway the circle
// covers (every spot a character passes through, half a metre in from its sides) is closed.
// 2. The route laid, a point inside a circle is moved out past its edge (on walkable floor, the
// legs to its neighbours walkable) or dropped, and a leg passing through one is bent round it:
// corners on a slightly bigger circle (every new leg a tangent of it), the shorter way round
// first, each corner on walkable floor and every new leg walkable.
// 3. A leg no bend gets round: the cell it passes the portal in is cut off as well (never the
// start's) and the patrol laid again, up to PortalMaxRounds times.
// The start: BuildDunPatrol walks the character out of a circle it stands in first (PortalWalkOut;
// the patrol is then built from there), then round any circle between it and the first point
// (PortalLeadIn). One log line per portal: PortalAvoidance.Describe.
// Patrol routes have no Portal points. A recorded route that walks into a portal on purpose (its
// portal step) is not laid here, and the navigation engine runs it as before.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
/// <summary>A portal the patrol keeps out of: a circle round it on its level (world metres).</summary>
internal sealed class PatrolPortal
{
public uint Id;
public string Name = "";
/// <summary>The cell it stands in (0 = not known: the cell under it is used).</summary>
public uint Cell;
/// <summary>World position (x east, y north, z its base).</summary>
public double X, Y, Z;
/// <summary>Points and legs stay at least this far away (horizontally).</summary>
public double Radius = DungeonPathfinder.PortalKeepOutDefault;
}
/// <summary>What the patrol build did about one portal (the log line BuildDunPatrol writes).</summary>
internal sealed class PortalAvoidance
{
public PatrolPortal Portal = null!;
/// <summary>Openings closed because the circle covers them.</summary>
public readonly List<(uint A, uint B)> Closed = new();
/// <summary>Cells cut off because a leg could not be bent round the portal there.</summary>
public readonly List<uint> CutCells = new();
public int Moved, Dropped, Bent;
/// <summary>The character stood inside the circle when the patrol was built (led out first).</summary>
public bool StartInside;
/// <summary>The finished route's nearest point or leg on the portal's level (metres; +infinity: none).</summary>
public double Nearest = double.PositiveInfinity;
/// <summary>How many times the patrol was laid (1 + the rounds with cells cut off), and how long the
/// whole portal-aware build took (the same for every portal of one build).</summary>
public int Laid;
public double BuildMs, SplitMs;
public bool Clear => Nearest >= Portal.Radius - 0.05;
public string Describe()
{
var inv = CultureInfo.InvariantCulture;
var p = Portal;
string closed = Closed.Count == 0 ? "none" : string.Join(" ", Closed.Select(e => $"{e.A:X8}/{e.B:X8}"));
string cut = CutCells.Count == 0 ? "" : "; cells cut off " + string.Join(" ", CutCells.Select(c => c.ToString("X8")));
string near = double.IsPositiveInfinity(Nearest) ? "nothing on its level" : Nearest.ToString("F1", inv) + " m";
return string.Format(inv,
"portal 0x{0:X8} '{1}' ({2:F1},{3:F1},{4:F1}) cell {5:X8}, kept {6:F1} m out: openings closed {7}{8}; points moved {9}, dropped {10}; legs bent {11}{12}; nearest {13}{14}",
p.Id, p.Name, p.X, p.Y, p.Z, p.Cell, p.Radius, closed, cut, Moved, Dropped, Bent,
StartInside ? "; start inside it: walked out first" : "", near, Clear ? "" : " (STILL INSIDE: no way round found)")
+ string.Format(inv, " [patrol laid {0}x, {1:F0} ms, of it {2:F0} ms splitting rooms]", Laid, BuildMs, SplitMs);
}
}
internal static partial class DungeonPathfinder
{
/// <summary>The character touches a portal this far from its centre: the usual portal sphere
/// (Setup 0x020005D3: 1.36 m) plus the character's (0.48 m), rounded up.</summary>
internal const double PortalTouchMeters = 1.9;
/// <summary>The least room past the touch distance: the steering's arrival ring (1.5 yd by
/// default) cuts a corner by about that much, and the character drifts off the line a little.</summary>
internal const double PortalSlackMeters = 1.6;
/// <summary>The keep-out radius at the default nav point reach (1.5 yd): 3.5 m.</summary>
internal const double PortalKeepOutDefault = PortalTouchMeters + PortalSlackMeters;
/// <summary>A point or leg counts against a portal when its height is within this of the portal's base.</summary>
internal const double PortalLevelBand = 3.0;
/// <summary>Legs and openings: how many times the patrol is laid again with more cut off.</summary>
internal const int PortalMaxRounds = 4;
// A point moved out goes this far past the circle's edge, and at most PortalMoveMax from where it was.
private const double PortalPointOut = 0.4, PortalMoveMax = 2.5;
// Bend corners stand on circles this much bigger than the keep-out (the bigger first), every
// PortalBendStepDeg degrees round at most.
private static readonly double[] PortalBendOut = { 0.75, 0.3 };
private const double PortalBendStepDeg = 40.0;
// Openings: a character passes this far in from either side.
private const double OpeningSideMargin = 0.5;
// Corners and moved points keep this much clearance from walls (or the wall distance, if less);
// new legs at least PortalLegWalkMin (walkable: on the floor, through no wall).
private const double PortalCornerClearMin = 0.5, PortalLegWalkMin = 0.25;
private const double PortalEps = 0.01;
/// <summary>What the last BuildPatrolRoute with portals did about each (per thread; null without portals).</summary>
[ThreadStatic] internal static List<PortalAvoidance>? LastPortalAvoidance;
/// <summary>The keep-out radius for a nav point reach (FollowNavMin) or corner rounding of
/// <paramref name="cutYards"/>: the touch distance plus that much (at least PortalSlackMeters).</summary>
internal static double PortalKeepOutRadius(double cutYards)
=> PortalTouchMeters + Math.Max(PortalSlackMeters, (double.IsFinite(cutYards) ? cutYards : 0) + 0.1);
// ── The build ────────────────────────────────────────────────────────────
private static NavRouteParser BuildPatrolRouteAroundPortals(
Dictionary<uint, DungeonNavNode> graph, uint startCell, IReadOnlySet<uint>? hazardCells,
DungeonGeometry? geo, DungeonPatrolOptions o, IReadOnlyList<PatrolPortal> portals,
(double X, double Y, double Z)? startAt)
{
foreach (var p in portals)
{
if (!(p.Radius > 0) || !double.IsFinite(p.Radius)) p.Radius = PortalKeepOutDefault;
if (p.Cell == 0 || !graph.ContainsKey(p.Cell)) p.Cell = CellAt(graph, geo, WorldPoint(p.X, p.Y, p.Z, false));
}
var clock = System.Diagnostics.Stopwatch.StartNew();
var reports = portals.Select(p => new PortalAvoidance { Portal = p }).ToList();
var closed = PortalClosedOpenings(graph, geo, hazardCells, portals, startCell, startAt, reports);
double splitMs = clock.Elapsed.TotalMilliseconds;
int laid = 0;
NavRouteParser route;
Dictionary<uint, DungeonNavNode> g;
for (int round = 0; ; round++)
{
g = WithoutOpenings(graph, closed, startCell);
route = BuildPatrolRoute(g, startCell, hazardCells, geo, o);
laid++;
foreach (var r in reports) r.Moved = r.Dropped = r.Bent = 0; // the last laying's
var unresolved = KeepOutOfPortals(route.Points, closed: true, g, geo, portals, reports, o.WallClearance);
if (unresolved.Count == 0 || round >= PortalMaxRounds) break;
// Legs no bend gets round: cut off the cell there (never the start), and lay it again.
bool more = false;
foreach (var (k, cell) in unresolved)
{
uint cut = cell != 0 && cell != startCell ? cell
: portals[k].Cell != 0 && portals[k].Cell != startCell ? portals[k].Cell : 0;
if (cut == 0 || !graph.TryGetValue(cut, out var node)) continue;
bool any = false;
foreach (uint nb in node.Neighbors) any |= closed.Add(EdgeKey(cut, nb));
if (any && !reports[k].CutCells.Contains(cut)) reports[k].CutCells.Add(cut);
more |= any;
}
if (!more) break;
}
foreach (var r in reports)
{
r.Nearest = NearestApproach(route.Points, closed: true, r.Portal);
r.Laid = laid;
r.BuildMs = clock.Elapsed.TotalMilliseconds;
r.SplitMs = splitMs;
}
LastPortalAvoidance = reports;
return route;
}
/// <summary>
/// The doorways (graph edges between rooms) the patrol must not use because of the portals: each
/// room a circle reaches is split by it (<see cref="SplitRoomByPortal"/>), and a doorway that
/// only reaches a part of the room the patrol doesn't keep, or none, is closed. Without the map
/// geometry (or for a room without floor data), a doorway the circle covers is closed
/// (<see cref="OpeningCovered"/>; no opening known: the midpoint of the two cell centres).
/// </summary>
internal static HashSet<ulong> PortalClosedOpenings(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geo,
IReadOnlySet<uint>? hazardCells, IReadOnlyList<PatrolPortal> portals,
uint startCell, (double X, double Y, double Z)? startAt,
List<PortalAvoidance>? reports = null)
{
var closed = new HashSet<ulong>();
void Close(int k, uint a, uint b)
{
if (closed.Add(EdgeKey(a, b)) && reports != null && k < reports.Count) reports[k].Closed.Add((a, b));
}
if (geo == null || geo.DoorwayCount == 0)
{
foreach (var node in graph.Values)
foreach (uint nb in node.Neighbors)
{
if (nb <= node.CellId || !graph.TryGetValue(nb, out var other) || IsDropEdge(node, other)) continue;
for (int k = 0; k < portals.Count; k++)
if (OpeningCovered(geo, node, other, portals[k])) Close(k, node.CellId, nb);
}
return closed;
}
var rooms = BuildRooms(graph, geo, hazardCells);
for (int k = 0; k < portals.Count; k++)
{
var p = portals[k];
double reach = p.Radius + PortalFreeOut;
for (int r = 0; r < rooms.Cells.Count; r++)
{
bool near = false;
foreach (uint c in rooms.Cells[r])
{
if (geo.TryCellFloorBounds(c, out double x0, out double y0, out double x1, out double y1))
near = p.X > x0 - reach && p.X < x1 + reach && p.Y > y0 - reach && p.Y < y1 + reach;
else if (graph.TryGetValue(c, out var n))
near = Dist(DungeonGeometry.NavToWorld(n.EW), DungeonGeometry.NavToWorld(n.NS), p.X, p.Y) < reach + 8.0;
if (near) break;
}
if (near) SplitRoomByPortal(graph, geo, rooms, r, p, startCell, startAt, (a, b) => Close(k, a, b));
}
}
return closed;
}
// The free floor (outside the circle) is this much bigger than the keep-out, so the smaller
// bend circle fits where the floor says the way round is.
private const double PortalFreeOut = 0.3;
// A spot of floor is free when a body this wide fits there (walkable floor this far to all four sides).
private const double PortalBodyMeters = 0.45;
// Doorway spots tried this far into the room.
private const double PortalDoorInset = 0.6;
/// <summary>
/// Splits room <paramref name="room"/> by portal <paramref name="p"/>: its floor (the cells' floor
/// polygons, on a 0.4 m grid) less the circle (where the floor is on the portal's level) and
/// less a body's width along its edges falls into parts. Each doorway out of the room reaches the
/// parts its passable spots (just inside the room) are in. The part kept is the one where the
/// character stands (<paramref name="startAt"/>, the start's room), else the one most doorways
/// reach (then the biggest); every doorway that doesn't reach it is closed. A room with no floor
/// left keeps no doorway, unless the start is in it. Doorways whose spots have no floor data are
/// judged by <see cref="OpeningCovered"/>.
/// </summary>
private static void SplitRoomByPortal(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry geo, DungeonRooms rooms, int room,
PatrolPortal p, uint startCell, (double X, double Y, double Z)? startAt, Action<uint, uint> close)
{
var cells = rooms.Cells[room];
var doors = new List<(uint C, uint N)>();
foreach (uint c in cells)
{
if (!graph.TryGetValue(c, out var n)) continue;
foreach (uint nb in n.Neighbors)
if (graph.TryGetValue(nb, out var o) && rooms.RoomOf.TryGetValue(nb, out int rn) && rn != room && !IsDropEdge(n, o))
doors.Add((c, nb));
}
if (doors.Count == 0) return;
// The floor grid.
var floored = new List<(uint Cell, double X0, double Y0, double X1, double Y1)>();
double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
foreach (uint c in cells)
{
if (!geo.TryCellFloorBounds(c, out double x0, out double y0, out double x1, out double y1)) continue;
floored.Add((c, x0, y0, x1, y1));
minX = Math.Min(minX, x0); minY = Math.Min(minY, y0); maxX = Math.Max(maxX, x1); maxY = Math.Max(maxY, y1);
}
if (floored.Count == 0)
{
foreach (var (c, nb) in doors)
if (OpeningCovered(geo, graph[c], graph[nb], p)) close(c, nb);
return;
}
double step = 0.4;
while ((maxX - minX) / step * ((maxY - minY) / step) > 90_000) step *= 1.25;
int nx = (int)Math.Ceiling((maxX - minX) / step) + 1, ny = (int)Math.Ceiling((maxY - minY) / step) + 1;
// Per spot: off the floor, a body doesn't fit, inside the circle, or free.
const byte Off = 0, Tight = 1, InCircle = 2, Free = 3;
var spot = new byte[nx * ny];
double rf = p.Radius + PortalFreeOut;
bool anyInCircle = false;
for (int iy = 0; iy < ny; iy++)
for (int ix = 0; ix < nx; ix++)
{
double x = minX + ix * step, y = minY + iy * step;
bool on = false;
double h = 0, best = double.MaxValue;
foreach (var f in floored)
{
if (x < f.X0 || x > f.X1 || y < f.Y0 || y > f.Y1) continue;
if (geo.TryCellFloorHeight(f.Cell, x, y, p.Z, out double fh) && Math.Abs(fh - p.Z) < best)
{ best = Math.Abs(fh - p.Z); h = fh; on = true; }
}
int idx = iy * nx + ix;
if (!on) { spot[idx] = Off; continue; }
bool body = geo.OnWalkableFloor(x + PortalBodyMeters, y, h) && geo.OnWalkableFloor(x - PortalBodyMeters, y, h)
&& geo.OnWalkableFloor(x, y + PortalBodyMeters, h) && geo.OnWalkableFloor(x, y - PortalBodyMeters, h);
if (!body) { spot[idx] = Tight; continue; }
bool inCircle = SameLevel(p, h) && Dist(x, y, p.X, p.Y) < rf;
anyInCircle |= inCircle;
spot[idx] = inCircle ? InCircle : Free;
}
if (!anyInCircle) return; // the circle takes nothing a body could stand on here
// The parts, four ways round: with the circle cut out, and (to tell what the portal does from
// what the room is anyway: a neck too narrow for a body) without.
int[] Parts(bool cut, out int count, out List<int> sizes)
{
var part = new int[spot.Length];
for (int s = 0; s < part.Length; s++) part[s] = spot[s] == Free || (!cut && spot[s] == InCircle) ? int.MaxValue : -1;
count = 0;
sizes = new List<int>();
var queue = new Queue<int>();
for (int s = 0; s < part.Length; s++)
{
if (part[s] != int.MaxValue) continue;
int id = count++, n = 0;
part[s] = id; queue.Enqueue(s);
while (queue.Count > 0)
{
int q = queue.Dequeue(); n++;
int qx = q % nx, qy = q / nx;
if (qx > 0 && part[q - 1] == int.MaxValue) { part[q - 1] = id; queue.Enqueue(q - 1); }
if (qx + 1 < nx && part[q + 1] == int.MaxValue) { part[q + 1] = id; queue.Enqueue(q + 1); }
if (qy > 0 && part[q - nx] == int.MaxValue) { part[q - nx] = id; queue.Enqueue(q - nx); }
if (qy + 1 < ny && part[q + nx] == int.MaxValue) { part[q + nx] = id; queue.Enqueue(q + nx); }
}
sizes.Add(n);
}
return part;
}
var cutParts = Parts(true, out int parts, out var size);
var wholeParts = Parts(false, out _, out _);
// Which parts each doorway reaches, with and without the circle (null: no floor data at its spots).
var reach = new List<HashSet<int>?>(doors.Count);
var reachWhole = new List<HashSet<int>>(doors.Count);
foreach (var (c, nb) in doors)
{
var spots = new List<(double X, double Y)>();
if (geo.TryGetDoorway(c, nb, out var d))
{
var (ox, oy) = d.NormalFrom(c); // out of the room
double half = Math.Max(0, d.Width / 2 - OpeningSideMargin);
int n = Math.Max(1, (int)Math.Ceiling(half / 0.3));
for (int i = -n; i <= n; i++)
{
double s = half * i / n;
spots.Add((d.X - ox * PortalDoorInset - oy * s, d.Y - oy * PortalDoorInset + ox * s));
}
}
else
{
var a = graph[c]; var b = graph[nb];
double ax = DungeonGeometry.NavToWorld(a.EW), ay = DungeonGeometry.NavToWorld(a.NS);
double mx = (ax + DungeonGeometry.NavToWorld(b.EW)) * 0.5, my = (ay + DungeonGeometry.NavToWorld(b.NS)) * 0.5;
double dl = Dist(ax, ay, mx, my);
spots.Add(dl > PortalDoorInset ? (mx + (ax - mx) / dl * PortalDoorInset, my + (ay - my) / dl * PortalDoorInset) : (ax, ay));
}
HashSet<int>? got = null;
var whole = new HashSet<int>();
foreach (var (sx, sy) in spots)
{
int cx = (int)Math.Round((sx - minX) / step), cy = (int)Math.Round((sy - minY) / step);
for (int ddy = -1; ddy <= 1; ddy++)
for (int ddx = -1; ddx <= 1; ddx++)
{
int gx = cx + ddx, gy = cy + ddy;
if (gx < 0 || gy < 0 || gx >= nx || gy >= ny) continue;
int at = gy * nx + gx;
if (spot[at] == Off) continue;
got ??= new HashSet<int>();
if (cutParts[at] >= 0) got.Add(cutParts[at]);
if (wholeParts[at] >= 0) whole.Add(wholeParts[at]);
}
}
reach.Add(got);
reachWhole.Add(whole);
}
// The part kept.
bool startHere = cells.Contains(startCell);
int kept = -1;
if (startHere && startAt is { } st)
{
double best = double.MaxValue;
for (int q = 0; q < cutParts.Length; q++)
{
if (cutParts[q] < 0) continue;
double dq = Dist(minX + (q % nx) * step, minY + (q / nx) * step, st.X, st.Y);
if (dq < best) { best = dq; kept = cutParts[q]; }
}
}
if (kept < 0)
{
var doorsOf = new int[parts];
foreach (var got in reach) if (got != null) foreach (int v in got) doorsOf[v]++;
for (int v = 0; v < parts; v++)
if (kept < 0 || doorsOf[v] > doorsOf[kept] || (doorsOf[v] == doorsOf[kept] && size[v] > size[kept])) kept = v;
}
// The character's own part with no doorway (boxed in by the portal): only what the circle
// covers is closed; it has to get out somehow.
if (startHere && kept >= 0 && !reach.Any(g => g != null && g.Contains(kept))) kept = -1;
int keptWhole = -1;
if (kept >= 0)
for (int q = 0; q < cutParts.Length && keptWhole < 0; q++)
if (cutParts[q] == kept) keptWhole = wholeParts[q];
for (int i = 0; i < doors.Count; i++)
{
var (c, nb) = doors[i];
var got = reach[i];
bool shut;
if (got == null) shut = OpeningCovered(geo, graph[c], graph[nb], p);
else if (got.Count == 0) shut = reachWhole[i].Count > 0; // every spot it has is inside the circle
else if (kept >= 0) shut = !got.Contains(kept) && reachWhole[i].Contains(keptWhole); // cut off from the part kept by the circle
else shut = !startHere; // nothing of the room is left to keep
if (shut) close(c, nb);
}
}
private static bool OpeningCovered(DungeonGeometry? geo, DungeonNavNode a, DungeonNavNode b, PatrolPortal p)
{
if (geo != null && geo.TryGetDoorway(a.CellId, b.CellId, out var d))
{
if (!SameLevel(p, d.Z)) return false;
double half = Math.Max(0, d.Width / 2 - OpeningSideMargin);
double ux = -d.Ny, uy = d.Nx; // along the opening
int n = Math.Max(1, (int)Math.Ceiling(half / 0.25));
for (int i = -n; i <= n; i++)
{
double s = half * i / n;
if (Dist(d.X + ux * s, d.Y + uy * s, p.X, p.Y) >= p.Radius) return false;
}
return true;
}
double mx = (DungeonGeometry.NavToWorld(a.EW) + DungeonGeometry.NavToWorld(b.EW)) * 0.5;
double my = (DungeonGeometry.NavToWorld(a.NS) + DungeonGeometry.NavToWorld(b.NS)) * 0.5;
return SameLevel(p, (a.Z + b.Z) * 0.5) && Dist(mx, my, p.X, p.Y) < p.Radius;
}
/// <summary>The graph without the <paramref name="closed"/> edges (a copy where they were; the
/// cached graph is never changed). The start keeps its edges when closing them all would leave
/// it no way out: the character is already there.</summary>
internal static Dictionary<uint, DungeonNavNode> WithoutOpenings(Dictionary<uint, DungeonNavNode> graph, HashSet<ulong> closed, uint startCell)
{
if (closed.Count == 0) return graph;
bool keepStart = false;
if (graph.TryGetValue(startCell, out var s))
{
int open = 0, any = 0;
foreach (uint nb in s.Neighbors)
{
if (!graph.TryGetValue(nb, out var o) || IsDropEdge(s, o)) continue;
any++;
if (!closed.Contains(EdgeKey(startCell, nb))) open++;
}
keepStart = any > 0 && open == 0;
}
var g = new Dictionary<uint, DungeonNavNode>(graph.Count);
foreach (var (id, n) in graph)
{
bool touched = false;
foreach (uint nb in n.Neighbors)
if (Closed(id, nb)) { touched = true; break; }
if (!touched) { g[id] = n; continue; }
var copy = new DungeonNavNode { CellId = n.CellId, NS = n.NS, EW = n.EW, Z = n.Z };
foreach (uint nb in n.Neighbors) if (!Closed(id, nb)) copy.Neighbors.Add(nb);
g[id] = copy;
}
return g;
bool Closed(uint a, uint b) => closed.Contains(EdgeKey(a, b)) && !(keepStart && (a == startCell || b == startCell));
}
// ── Points and legs ──────────────────────────────────────────────────────
/// <summary>
/// Keeps the points and legs of <paramref name="pts"/> (a loop when <paramref name="closed"/>)
/// out of every portal's circle: a point inside is moved out past the edge or dropped, a leg
/// through one is bent round it. Returns the legs it could not bend: (portal index, the cell the
/// leg passes the portal in).
/// </summary>
internal static List<(int Portal, uint Cell)> KeepOutOfPortals(List<NavPoint> pts, bool closed, Dictionary<uint, DungeonNavNode> graph,
DungeonGeometry? geo, IReadOnlyList<PatrolPortal> portals,
List<PortalAvoidance>? reports, double wall)
{
var unresolved = new List<(int, uint)>();
if (portals.Count == 0 || pts.Count == 0) return unresolved;
// Points inside a circle.
for (int k = 0; k < portals.Count; k++)
{
var p = portals[k];
for (int i = 0; i < pts.Count; i++)
{
var pt = pts[i];
if (!NavRouteParser.IsPlainWaypoint(pt.Type) || !Inside(p, pt)) continue;
NavPoint? prev = pts.Count > 1 && (i > 0 || closed) ? pts[(i - 1 + pts.Count) % pts.Count] : null;
NavPoint? next = pts.Count > 1 && (i + 1 < pts.Count || closed) ? pts[(i + 1) % pts.Count] : null;
if (TryMoveOut(geo, p, portals, pt, prev, next, wall, out double mx, out double my, out double mz))
{
pt.EW = DungeonGeometry.WorldToNav(mx);
pt.NS = DungeonGeometry.WorldToNav(my);
pt.Z = mz / 240.0;
NotePortal(pt, "moved-out-of-portal");
if (reports != null && k < reports.Count) reports[k].Moved++;
}
else
{
pts.RemoveAt(i--);
if (reports != null && k < reports.Count) reports[k].Dropped++;
if (pts.Count == 0) return unresolved;
}
}
}
// Legs through a circle.
var failed = new HashSet<(NavPoint, NavPoint, int)>();
int budget = 8 * pts.Count + 64;
int at = 0;
while (pts.Count >= 2 && at < (closed ? pts.Count : pts.Count - 1))
{
var a = pts[at]; var b = pts[(at + 1) % pts.Count];
int worst = -1; double worstD = double.MaxValue, worstT = 0;
for (int k = 0; k < portals.Count; k++)
{
double d = LegDistance(portals[k], a, b, out double t);
if (d < portals[k].Radius - PortalEps && d < worstD && !failed.Contains((a, b, k))) { worst = k; worstD = d; worstT = t; }
}
if (worst < 0) { at++; continue; }
if (budget-- > 0 && TryBend(geo, a, b, portals[worst], portals, wall, out var corners))
{
pts.InsertRange(at + 1, corners);
if (reports != null && worst < reports.Count) reports[worst].Bent++;
continue; // the first new leg next (another portal may be in its way)
}
failed.Add((a, b, worst));
double ax = X(a), ay = Y(a), az = a.Z * 240.0;
var spot = WorldPoint(ax + (X(b) - ax) * worstT, ay + (Y(b) - ay) * worstT, az + (b.Z * 240.0 - az) * worstT, false);
unresolved.Add((worst, CellAt(graph, geo, spot)));
}
return unresolved;
}
/// <summary>
/// Where the character at (px, py, pz) walks first when it stands inside a portal's circle:
/// straight away from the portal (else turned up to 90 degrees either way) to just past the
/// circle's edge, on walkable floor with some clearance, out of every circle. Null when it
/// stands in none. BuildDunPatrol builds the patrol from there (its cell, its part of a room the
/// portal splits). Tagged "portal-lead".
/// </summary>
internal static NavPoint? PortalWalkOut(DungeonGeometry? geo, IReadOnlyList<PatrolPortal> portals, double px, double py, double pz,
double wall, List<PortalAvoidance>? reports = null)
{
var here = WorldPoint(px, py, pz, false);
NavPoint? result = null;
for (int pass = 0; pass < 3; pass++) // out of one circle can be into the next (portals side by side)
{
int k = -1;
for (int i = 0; i < portals.Count && k < 0; i++) if (Inside(portals[i], here)) k = i;
if (k < 0) break;
if (reports != null && k < reports.Count) reports[k].StartInside = true;
var p = portals[k];
double hx = X(here), hy = Y(here), hz = here.Z * 240.0, d = Dist(hx, hy, p.X, p.Y);
double ux = d > 0.05 ? (hx - p.X) / d : 1, uy = d > 0.05 ? (hy - p.Y) / d : 0;
double want = p.Radius + PortalPointOut;
double ox = p.X + ux * want, oy = p.Y + uy * want, oz = hz;
foreach (double deg in new[] { 0.0, 20, -20, 40, -40, 60, -60, 90, -90 })
{
double a = deg * Math.PI / 180.0, c = Math.Cos(a), s = Math.Sin(a);
double cx = p.X + (ux * c - uy * s) * want, cy = p.Y + (ux * s + uy * c) * want, cz = hz;
if (geo != null)
{
if (geo.TryFloorHeight(cx, cy, hz, 1.5, out double h)) cz = h;
if (!geo.OnWalkableFloor(cx, cy, cz) || geo.ClearanceMemo(cx, cy, cz, wall + 0.5) < Math.Min(wall, PortalCornerClearMin)) continue;
if (geo.LegClearance(hx, hy, hz, cx, cy, cz, 1.0, 0.3, out _, out _, out _) < 0.1) continue; // through a wall
}
if (InsideAny(portals, cx, cy, cz)) continue;
ox = cx; oy = cy; oz = cz;
break;
}
here = Tag(WorldPoint(ox, oy, oz, false), "portal-lead");
NotePortal(here, "out-of-portal");
result = here;
}
return result;
}
/// <summary>
/// The corners to walk between <paramref name="from"/> (the character, or where it walked out of
/// a circle to) and the route's first point <paramref name="first"/> so the way there keeps out of
/// the portals (bent round any circle in between). Empty when the straight walk is clear. Tagged
/// "portal-lead".
/// </summary>
internal static List<NavPoint> PortalLeadIn(Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geo, IReadOnlyList<PatrolPortal> portals,
NavPoint from, NavPoint first, double wall, List<PortalAvoidance>? reports = null)
{
var lead = new List<NavPoint>();
var legs = new List<NavPoint> { from, first };
KeepOutOfPortals(legs, closed: false, graph, geo, portals, reports, wall);
foreach (var p in legs)
{
if (ReferenceEquals(p, from) || ReferenceEquals(p, first)) continue;
Tag(p, "portal-lead");
lead.Add(p);
}
return lead;
}
/// <summary>The least distance (metres) from the portal to the route's points and legs on its
/// level: +infinity when none is.</summary>
internal static double NearestApproach(List<NavPoint> pts, bool closed, PatrolPortal p)
{
double best = double.PositiveInfinity;
for (int i = 0; i < pts.Count; i++)
{
if (SameLevel(p, pts[i].Z * 240.0)) best = Math.Min(best, Dist(X(pts[i]), Y(pts[i]), p.X, p.Y));
if (i + 1 < pts.Count || (closed && pts.Count > 1))
best = Math.Min(best, LegDistance(p, pts[i], pts[(i + 1) % pts.Count], out _));
}
return best;
}
// A point inside the circle moved out to PortalPointOut past its edge: straight away from the
// portal, else turned up to 90 degrees either way; on walkable floor with some clearance, out of
// every circle, the legs to its neighbours walkable, at most PortalMoveMax from where it was.
private static bool TryMoveOut(DungeonGeometry? geo, PatrolPortal p, IReadOnlyList<PatrolPortal> all, NavPoint pt,
NavPoint? prev, NavPoint? next, double wall, out double mx, out double my, out double mz)
{
mx = my = mz = 0;
double x0 = X(pt), y0 = Y(pt), z0 = pt.Z * 240.0;
double d = Dist(x0, y0, p.X, p.Y), ux, uy;
if (d > 0.05) { ux = (x0 - p.X) / d; uy = (y0 - p.Y) / d; }
else
{
var toward = prev ?? next;
double tx = toward != null ? X(toward) - p.X : 1, ty = toward != null ? Y(toward) - p.Y : 0, tl = Math.Sqrt(tx * tx + ty * ty);
if (tl < 0.05) { tx = 1; ty = 0; tl = 1; }
ux = tx / tl; uy = ty / tl;
}
double want = p.Radius + PortalPointOut;
foreach (double deg in new[] { 0.0, 20, -20, 40, -40, 60, -60, 90, -90 })
{
double a = deg * Math.PI / 180.0, c = Math.Cos(a), s = Math.Sin(a);
double vx = ux * c - uy * s, vy = ux * s + uy * c;
double cx = p.X + vx * want, cy = p.Y + vy * want, cz = z0;
if (Dist(cx, cy, x0, y0) > PortalMoveMax) continue;
if (geo != null)
{
if (geo.TryFloorHeight(cx, cy, z0, 1.5, out double h)) cz = h;
if (!geo.OnWalkableFloor(cx, cy, cz)) continue;
if (geo.ClearanceMemo(cx, cy, cz, wall + 0.5) < Math.Min(wall, PortalCornerClearMin)) continue;
}
if (InsideAny(all, cx, cy, cz)) continue;
if (geo != null)
{
var cand = WorldPoint(cx, cy, cz, false);
if (prev != null && !LegWalkable(geo, prev, cand)) continue;
if (next != null && !LegWalkable(geo, cand, next)) continue;
}
mx = cx; my = cy; mz = cz;
return true;
}
// Too deep in for that: back along a leg to a neighbour, to where it leaves the circle (the
// patrol turns round there instead), the nearer of the two.
double bestMove = double.MaxValue;
bool found = false;
foreach (var nb in new[] { prev, next })
{
if (nb == null) continue;
double bx = X(nb), by = Y(nb), bz = nb.Z * 240.0;
double dx = bx - x0, dy = by - y0, len = Math.Sqrt(dx * dx + dy * dy);
if (len < 1e-6 || Dist(bx, by, p.X, p.Y) < want) continue; // the neighbour is inside too (it goes as well)
// The first t along pt -> nb at distance `want` from the portal: |pt + t*u - P| = want.
double fx = x0 - p.X, fy = y0 - p.Y, ex = dx / len, ey = dy / len;
double bq = fx * ex + fy * ey, cq = fx * fx + fy * fy - want * want, disc = bq * bq - cq;
if (disc < 0) continue;
double t = -bq + Math.Sqrt(disc);
if (t <= 0 || t > len) continue;
double cx = x0 + ex * t, cy = y0 + ey * t, cz = z0 + (bz - z0) * (t / len);
if (geo != null && geo.TryFloorHeight(cx, cy, cz, 1.5, out double h)) cz = h;
if (InsideAny(all, cx, cy, cz) || t >= bestMove) continue;
bestMove = t; mx = cx; my = cy; mz = cz; found = true;
}
return found;
}
// The leg a-b bent round the circle: corners on a circle a little bigger, each leg a tangent of it
// (so every new leg keeps out), the shorter way round first; every corner on walkable floor with
// some clearance and out of every circle, every new leg walkable.
private static bool TryBend(DungeonGeometry? geo, NavPoint a, NavPoint b, PatrolPortal p, IReadOnlyList<PatrolPortal> all,
double wall, out List<NavPoint> corners)
{
corners = null!;
double ax = X(a), ay = Y(a), az = a.Z * 240.0, bx = X(b), by = Y(b), bz = b.Z * 240.0;
double da = Dist(ax, ay, p.X, p.Y), db = Dist(bx, by, p.X, p.Y);
if (da < p.Radius - PortalEps || db < p.Radius - PortalEps) return false; // an end inside: not a bend's job
double angA = Math.Atan2(ay - p.Y, ax - p.X), angB = Math.Atan2(by - p.Y, bx - p.X);
foreach (double extra in PortalBendOut)
{
double rb = p.Radius + extra;
double offA = da > rb ? Math.Acos(rb / da) : 0, offB = db > rb ? Math.Acos(rb / db) : 0;
var ways = new List<(int Side, double Start, double Sweep)>(2);
foreach (int side in new[] { 1, -1 })
{
double start = angA + side * offA, end = angB - side * offB;
double sweep = side > 0 ? Wrap2Pi(end - start) : Wrap2Pi(start - end);
if (sweep > 1.5 * Math.PI) continue; // all the way round: never the way
ways.Add((side, start, sweep));
}
ways.Sort((u, v) => u.Sweep.CompareTo(v.Sweep));
foreach (var (side, start, sweep) in ways)
{
int n = Math.Max(1, (int)Math.Ceiling(sweep / (PortalBendStepDeg * Math.PI / 180.0) - 1e-9));
double step = sweep / n, r = rb / Math.Cos(step / 2);
var list = new List<NavPoint>(n);
bool ok = true;
for (int j = 0; j < n && ok; j++)
{
double ang = start + side * step * (j + 0.5);
double cx = p.X + Math.Cos(ang) * r, cy = p.Y + Math.Sin(ang) * r;
double zRef = az + (bz - az) * Along(ax, ay, bx, by, cx, cy), cz = zRef;
if (geo != null)
{
if (geo.TryFloorHeight(cx, cy, zRef, 1.5, out double h)) cz = h;
ok = geo.OnWalkableFloor(cx, cy, cz) && geo.ClearanceMemo(cx, cy, cz, wall + 0.5) >= Math.Min(wall, PortalCornerClearMin);
}
ok = ok && !InsideAny(all, cx, cy, cz);
if (ok) list.Add(WorldPoint(cx, cy, cz, false));
}
if (!ok) continue;
NavPoint from = a;
foreach (var c in list.Append(b))
{
if (LegDistance(p, from, c, out _) < p.Radius - PortalEps || (geo != null && !LegWalkable(geo, from, c))) { ok = false; break; }
from = c;
}
if (!ok) continue;
foreach (var c in list) { Tag(c, "portal-bend"); NotePortal(c, "round-portal"); }
corners = list;
return true;
}
}
return false;
}
// ── Helpers ──────────────────────────────────────────────────────────────
private static bool SameLevel(PatrolPortal p, double z) => Math.Abs(z - p.Z) <= PortalLevelBand;
private static bool Inside(PatrolPortal p, NavPoint pt)
=> SameLevel(p, pt.Z * 240.0) && Dist(X(pt), Y(pt), p.X, p.Y) < p.Radius - PortalEps;
/// <summary>The straight walk a-b keeps out of every portal's circle (and, with the map geometry,
/// is walkable: on the floor, through no wall).</summary>
internal static bool PortalLegClear(DungeonGeometry? geo, IReadOnlyList<PatrolPortal> portals, NavPoint a, NavPoint b)
{
foreach (var p in portals)
if (LegDistance(p, a, b, out _) < p.Radius - PortalEps) return false;
return geo == null || LegWalkable(geo, a, b);
}
/// <summary>(x, y, z) (world) is inside the portal's circle, on its level.</summary>
internal static bool InsidePortal(PatrolPortal p, double x, double y, double z)
=> SameLevel(p, z) && Dist(x, y, p.X, p.Y) < p.Radius - PortalEps;
private static bool InsideAny(IReadOnlyList<PatrolPortal> all, double x, double y, double z)
{
foreach (var q in all)
if (SameLevel(q, z) && Dist(x, y, q.X, q.Y) < q.Radius - PortalEps) return true;
return false;
}
/// <summary>The least horizontal distance from the portal to the leg a-b over the part of the leg
/// on the portal's level (+infinity when no part of it is); t: where (0..1).</summary>
internal static double LegDistance(PatrolPortal p, NavPoint a, NavPoint b, out double t)
{
double ax = X(a), ay = Y(a), az = a.Z * 240.0, bx = X(b), by = Y(b), bz = b.Z * 240.0;
double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
t = l2 < 1e-12 ? 0 : Math.Clamp(((p.X - ax) * dx + (p.Y - ay) * dy) / l2, 0, 1);
double d = Dist(ax + dx * t, ay + dy * t, p.X, p.Y);
if (SameLevel(p, az + (bz - az) * t)) return d;
if (SameLevel(p, az) == SameLevel(p, bz) && !SameLevel(p, az) && (az - p.Z) * (bz - p.Z) > 0) return double.PositiveInfinity; // all of it above or below
// Off its level at the nearest spot: the nearest spot of the leg that is on it (a ramp).
int n = Math.Clamp((int)Math.Ceiling(Math.Sqrt(l2) / 0.5), 8, 200);
double best = double.PositiveInfinity, bestT = t;
for (int i = 0; i <= n; i++)
{
double s = (double)i / n;
if (!SameLevel(p, az + (bz - az) * s)) continue;
double ds = Dist(ax + dx * s, ay + dy * s, p.X, p.Y);
if (ds < best) { best = ds; bestT = s; }
}
t = bestT;
return best;
}
// On the floor and through no wall: the leg's least clearance at least PortalLegWalkMin.
private static bool LegWalkable(DungeonGeometry geo, NavPoint a, NavPoint b)
=> geo.LegClearance(X(a), Y(a), a.Z * 240.0, X(b), Y(b), b.Z * 240.0, 1.0, 0.3, out _, out _, out _) >= PortalLegWalkMin;
private static void NotePortal(NavPoint p, string why)
{
if (PointLog == null) return;
var info = Info(p);
info.Why = info.Why.Length > 0 ? info.Why + "," + why : why;
}
// Where (0..1) the point (x, y) projects onto the segment a-b.
private static double Along(double ax, double ay, double bx, double by, double x, double y)
{
double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
return l2 < 1e-12 ? 0 : Math.Clamp(((x - ax) * dx + (y - ay) * dy) / l2, 0, 1);
}
private static double Wrap2Pi(double a)
{
a %= 2 * Math.PI;
return a < 0 ? a + 2 * Math.PI : a;
}
private static double Dist(double ax, double ay, double bx, double by) => Math.Sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
private static double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW);
private static double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS);
}

View file

@ -795,15 +795,25 @@ internal static partial class DungeonPathfinder
/// of a loop and backtracking the way it came. Only true dead-ends and bridges are
/// re-tread (the unavoidable in-and-out), via the shortest reconnecting path. The walk is
/// closed back to the start so the Circular route returns home.
///
/// <paramref name="portals"/> (the landblock's live portals): the patrol keeps out of their
/// circles, turning round before a portal it can't get past (DungeonPathfinder.Portals.cs;
/// what it did about each: <see cref="LastPortalAvoidance"/>). <paramref name="startAt"/>
/// (world): where the character stands, so a portal that splits its room leaves it the part it
/// is in.
/// </summary>
public static NavRouteParser BuildPatrolRoute(
Dictionary<uint, DungeonNavNode> graph,
uint startCell,
IReadOnlySet<uint>? hazardCells = null,
DungeonGeometry? geo = null,
DungeonPatrolOptions? options = null)
DungeonPatrolOptions? options = null,
IReadOnlyList<PatrolPortal>? portals = null,
(double X, double Y, double Z)? startAt = null)
{
LastPortalAvoidance = null;
var o = (options ?? DungeonPatrolOptions.Default).Clamped();
if (portals is { Count: > 0 }) return BuildPatrolRouteAroundPortals(graph, startCell, hazardCells, geo, o, portals, startAt);
// Dead ends are judged room by room when the rooms can be made (the room patrol below).
var rooms = geo != null && geo.DoorwayCount > 0 ? BuildRooms(graph, geo, hazardCells) : null;
var mainRoute = GetMainRouteNodes(graph, startCell, hazardCells, o, rooms);

View file

@ -187,7 +187,7 @@ public sealed class LegacyUiSettings
public bool StopMacroWhenPackFull = false;
public int RestamAt = 30;
/// <summary>
/// In combat, once stamina drops under Re-stam At, keep recharging until it reaches this %
/// Once stamina is under Re-stam At (in a fight, or just after one), keep recharging until it reaches this %
/// (one Revitalize often doesn't get far). 0, or not above Re-stam At = one recharge, as before.
/// </summary>
public int RestamTo = 0;

View file

@ -185,7 +185,11 @@ internal sealed class LegacyWeaponsUi
{
switch (wo.ObjectClass)
{
case AcObjectClass.HealingKit: return (wo.Name ?? "").Contains("Stamina", StringComparison.OrdinalIgnoreCase) ? "StaminaKit" : "HealthKit";
case AcObjectClass.HealingKit:
// A kit restores the vital in its name: a Greater Mana Kit is no healing kit (DreamWeave has them).
if ((wo.Name ?? "").Contains("Stamina", StringComparison.OrdinalIgnoreCase)) return "StaminaKit";
if ((wo.Name ?? "").Contains("Mana", StringComparison.OrdinalIgnoreCase)) return "ManaKit";
return "HealthKit";
case AcObjectClass.Food: return PotionType(wo);
case AcObjectClass.Lockpick: return "Lockpick";
case AcObjectClass.Misc:
@ -230,10 +234,10 @@ internal sealed class LegacyWeaponsUi
name.Contains("Elixir of Healing", StringComparison.OrdinalIgnoreCase))
return "HealthKit";
// Mana items
if (name.Contains("Mana", StringComparison.OrdinalIgnoreCase) ||
name.Contains("Mana Stone", StringComparison.OrdinalIgnoreCase))
return "ManaStone";
// Mana items. A mana kit (it restores your own mana, like a stamina kit) is no stone: typed
// ManaStone it switched off the ordinary stones and Drakkon's gear ran dry (10-23).
if (name.Contains("Mana", StringComparison.OrdinalIgnoreCase))
return name.TrimEnd().EndsWith(" Kit", StringComparison.OrdinalIgnoreCase) ? "ManaKit" : "ManaStone";
// Stamina items. A stamina kit is used on yourself, not drunk: its own type, so the
// potion step never takes it ("Stamina" is the old name for stamina potions).

View file

@ -747,8 +747,7 @@ internal sealed class ManaStoneManager
bool hasRule = false;
foreach (var rule in _settings.ConsumableRules)
{
if (!rule.Type.Equals("ManaStone", StringComparison.OrdinalIgnoreCase)) continue;
if (string.IsNullOrWhiteSpace(rule.Name)) continue;
if (!IsStoneRule(rule)) continue;
hasRule = true;
if (rule.Name.Equals(item.Name, StringComparison.OrdinalIgnoreCase))
return true;
@ -767,6 +766,24 @@ internal sealed class ManaStoneManager
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// A ManaStone line in Items that names a stone. A kit isn't one: "Greater Mana Kit" (a kit that
/// restores your own mana) was typed ManaStone from the word "Mana" (Drakkon, 10-23). As a stone rule
/// it switched off the ordinary stones (rules → named ones only), so his Greater and Major Mana Stones
/// were never used and his shirt ran dry, and RynthAi tried to drain gear into the kit (refused).
/// </summary>
private bool IsStoneRule(ConsumableRule rule)
{
if (!rule.Type.Equals("ManaStone", StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(rule.Name)) return false;
if (!IsKitName(rule.Name)) return true;
if (_kitRulesNoted.Add(rule.Name))
_host.Log($"[RynthAi] ManaStone: '{rule.Name}' is in Items as a mana stone but is a kit: not used as a stone (Items: change its type).");
return false;
}
private readonly HashSet<string> _kitRulesNoted = new(StringComparer.OrdinalIgnoreCase);
internal static bool IsKitName(string name) => name.TrimEnd().EndsWith(" Kit", StringComparison.OrdinalIgnoreCase);
/// <summary>The retail tapping stones (ACE world data names), smallest to largest.</summary>
internal static readonly HashSet<string> OrdinaryStoneNames = new(StringComparer.OrdinalIgnoreCase)
{
@ -802,7 +819,7 @@ internal sealed class ManaStoneManager
if (IsManaStone(item)) return true;
if (_settings.EnableManaTapping || string.IsNullOrEmpty(item.Name)) return false;
foreach (var rule in _settings.ConsumableRules)
if (rule.Type.Equals("ManaStone", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(rule.Name))
if (IsStoneRule(rule))
return false; // rules decide (IsManaStone already said no)
return OrdinaryStoneNames.Contains(item.Name)
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);

View file

@ -54,6 +54,10 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private readonly Dictionary<uint, List<MapPolygon>> _floorPolyCache =
new Dictionary<uint, List<MapPolygon>>();
// Cache: landblock → per EnvCell, the surfaces its walkable floor shows (Detector C)
private readonly Dictionary<uint, Dictionary<uint, ushort[]>> _floorSurfaceCache =
new Dictionary<uint, Dictionary<uint, ushort[]>>();
private const int MAX_ENV_CACHE = 50;
private const int MAX_WALL_CACHE = 20;
@ -242,6 +246,114 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
return result;
}
/// <summary>AC's walkable slope limit (PhysicsGlobals.FloorZ, about 48 degrees): a polygon
/// whose unit normal points up at least this much is floor a character can stand on.</summary>
public const float FloorZ = 0.66417f;
/// <summary>
/// For each EnvCell of the landblock, the surfaces its walkable floor shows: the Surface
/// (0x08) file ids, low 16 bits as the EnvCell's palette stores them, of its render
/// polygons that are not portals and whose front side faces up at least as steeply as
/// <see cref="FloorZ"/> in world orientation. Walls, ceilings and slopes too steep to
/// stand on are left out, so a texture on a cell's walls or ceiling never lists the cell.
/// Cells without such a polygon (a cap cell holding only a ceiling) are absent. Render
/// polygons, not physics ones: physics polygons carry no surface (PosSurface -1).
/// Cached per landblock. Never throws.
/// </summary>
public Dictionary<uint, ushort[]> GetCellFloorSurfaces(uint landblockKey)
{
lock (_cacheGate)
{
if (_floorSurfaceCache.TryGetValue(landblockKey, out var cached)) return cached;
}
var result = new Dictionary<uint, ushort[]>();
if (_cellDat == null || _portalDat == null) return result; // not initialized: nothing to cache
List<uint> cellIds;
try { cellIds = _cellDat.GetLandblockCellIds(landblockKey); }
catch { cellIds = new List<uint>(); }
foreach (uint cellId in cellIds)
{
try
{
byte[] cellData = _cellDat.GetFileData(cellId);
if (cellData == null || cellData.Length < 20) continue;
var envCell = ParseEnvCellHeader(cellData);
if (envCell == null || envCell.Surfaces.Length == 0) continue;
var cellGeo = GetCellRenderGeometry(envCell.EnvironmentId, envCell.CellStructureIndex);
if (cellGeo == null || cellGeo.Polygons.Count == 0) continue;
// Orientation only: the cell's rotation decides which way a polygon
// faces; its position doesn't (and large world offsets cost precision).
var polys = new List<(IReadOnlyList<Vector3> Verts, short PosSurface, bool IsPortal)>(cellGeo.Polygons.Count);
foreach (var poly in cellGeo.Polygons)
{
var rotated = new Vector3[poly.Vertices.Count];
for (int i = 0; i < rotated.Length; i++)
rotated[i] = RotateByQuat(poly.Vertices[i], envCell.RotW, envCell.RotX, envCell.RotY, envCell.RotZ);
polys.Add((rotated, poly.PosSurface, poly.IsPortal));
}
var floor = FloorSurfaceIds(envCell.Surfaces, polys);
if (floor.Count > 0) result[cellId] = floor.ToArray();
}
catch { }
}
lock (_cacheGate)
{
if (_floorSurfaceCache.Count >= MAX_WALL_CACHE)
{
foreach (var k in _floorSurfaceCache.Keys) { _floorSurfaceCache.Remove(k); break; }
}
_floorSurfaceCache[landblockKey] = result;
}
return result;
}
/// <summary>
/// The palette entries shown on walkable floor among <paramref name="polys"/>: polygons
/// that are not portals, whose PosSurface indexes <paramref name="palette"/>, and that
/// <see cref="IsWalkableFloor"/>. Each surface id once, in first-seen order.
/// </summary>
internal static List<ushort> FloorSurfaceIds(ushort[] palette,
IEnumerable<(IReadOnlyList<Vector3> Verts, short PosSurface, bool IsPortal)> polys)
{
var result = new List<ushort>();
if (palette == null || polys == null) return result;
foreach (var (verts, posSurface, isPortal) in polys)
{
if (isPortal || posSurface < 0 || posSurface >= palette.Length) continue;
if (!IsWalkableFloor(verts)) continue;
ushort s = palette[posSurface];
if (!result.Contains(s)) result.Add(s);
}
return result;
}
/// <summary>
/// True when the polygon (vertices in winding order) faces up at least as steeply as
/// <see cref="FloorZ"/>: its Newell normal, counter-clockwise seen from above = up, has a
/// unit z of 0.66417 or more. Walls (z near 0), ceilings (z negative) and steep slopes
/// are not floor.
/// </summary>
internal static bool IsWalkableFloor(IReadOnlyList<Vector3> v)
{
if (v == null || v.Count < 3) return false;
double nx = 0, ny = 0, nz = 0;
int n = v.Count;
for (int i = 0; i < n; i++)
{
Vector3 a = v[i], b = v[(i + 1) % n];
nx += ((double)a.Y - b.Y) * ((double)a.Z + b.Z);
ny += ((double)a.Z - b.Z) * ((double)a.X + b.X);
nz += ((double)a.X - b.X) * ((double)a.Y + b.Y);
}
double len = Math.Sqrt(nx * nx + ny * ny + nz * nz);
return len > 1e-9 && nz / len >= FloorZ;
}
private List<MapCell> LoadDungeonMapCells(uint landblockKey)
{
var result = new List<MapCell>();
@ -499,6 +611,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
public uint CellStructureIndex;
public float PosX, PosY, PosZ;
public float RotW, RotX, RotY, RotZ;
// The cell's surface palette: Surface (0x08) file ids, low 16 bits. A CellStruct
// polygon's PosSurface indexes this list.
public ushort[] Surfaces = Array.Empty<ushort>();
}
private EnvCellHeader ParseEnvCellHeader(byte[] data)
@ -516,7 +631,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
byte numPortals = reader.ReadByte();
ushort numVisibleCells = reader.ReadUInt16();
ms.Seek(numSurfaces * 2, SeekOrigin.Current);
var surfaces = new ushort[numSurfaces];
for (int i = 0; i < numSurfaces; i++)
surfaces[i] = reader.ReadUInt16();
ushort envIdShort = reader.ReadUInt16();
ushort cellStructure = reader.ReadUInt16();
@ -525,6 +642,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
{
EnvironmentId = 0x0D000000u | envIdShort,
CellStructureIndex = cellStructure,
Surfaces = surfaces,
PosX = reader.ReadSingle(),
PosY = reader.ReadSingle(),
PosZ = reader.ReadSingle(),
@ -551,6 +669,9 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
{
public List<Vector3> Vertices = new List<Vector3>();
public bool IsPortal;
// Index into the EnvCell's surface palette for the polygon's front (positive) side;
// -1 when it has none (physics polygons carry -1).
public short PosSurface = -1;
}
private CellGeometry GetCellGeometry(uint environmentId, uint cellStructIndex)
@ -716,7 +837,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
var poly = renderPolygons[i];
if (poly.VertexIds == null || poly.VertexIds.Count < 3) continue;
var cellPoly = new CellPolygon { IsPortal = portalIndices.Contains(poly.Key) };
var cellPoly = new CellPolygon { IsPortal = portalIndices.Contains(poly.Key), PosSurface = poly.PosSurface };
foreach (var vid in poly.VertexIds)
{
if (vertices.ContainsKey(vid))
@ -749,7 +870,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
foreach (var poly in physicsPolys)
{
if (poly.VertexIds == null || poly.VertexIds.Count < 3) continue;
var cellPoly = new CellPolygon();
var cellPoly = new CellPolygon { PosSurface = poly.PosSurface };
foreach (var vid in poly.VertexIds)
{
if (vertices.ContainsKey(vid))
@ -1022,7 +1143,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
if (numPts == 0 || numPts > 50) return polys;
var poly = new ParsedPolygon { Key = polyKey, VertexIds = new List<ushort>() };
var poly = new ParsedPolygon { Key = polyKey, PosSurface = posSurf, VertexIds = new List<ushort>() };
for (int v = 0; v < numPts; v++)
{
@ -1053,6 +1174,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
private class ParsedPolygon
{
public ushort Key;
public short PosSurface;
public List<ushort> VertexIds;
}
@ -1064,6 +1186,7 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
_mapCache.Clear();
_mapCellCache.Clear();
_floorPolyCache.Clear();
_floorSurfaceCache.Clear();
_envCache.Clear();
_renderEnvCache.Clear();
}

View file

@ -2899,7 +2899,7 @@ public sealed partial class RynthAiPlugin
}
}
private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false)
private void BuildDunPatrol(bool isRebuild, bool settingsChanged = false, bool portalAppeared = false)
{
// The one way into the dungeon patrol (the command, the dashboard button, a meta's "Patrol", the hazard
// reroute): where a server's owners asked for it to be off (a Thread on DreamWeave) nothing is built (ServerPolicy).
@ -2962,14 +2962,14 @@ public sealed partial class RynthAiPlugin
// explored is built clean without having to re-sight and reroute.
_objectCache?.SeedHazardsFromStore(landblockKey);
// Detector C: offline EnvCell-surface hazard cells (lava/acid floor textures). Catches the
// invisible-HotSpot majority the live weenie scan can't see — pure dat reads, cached per
// landblock. No-op unless the user has flagged hazard textures (/ra hazard learnhere|texture).
// Detector C: offline EnvCell hazard cells (lava/acid textures on a cell's walkable floor).
// Catches the invisible-HotSpot majority the live weenie scan can't see — pure dat reads,
// cached per landblock. No-op unless the user has flagged hazard textures (/ra hazard learnhere|texture).
var portalDat = _raycast?.GeometryLoader?.PortalDat;
HashSet<uint>? surfaceHazards = null;
if (portalDat != null)
{
surfaceHazards = DungeonHazardSurfaces.ComputeHazardCells(landblockKey, cellDat, portalDat);
surfaceHazards = DungeonHazardSurfaces.ComputeHazardCells(landblockKey, _raycast?.GeometryLoader?.DungeonLOS, portalDat);
if (surfaceHazards.Count > 0) _objectCache?.SeedSurfaceHazards(surfaceHazards);
}
@ -2998,11 +2998,42 @@ public sealed partial class RynthAiPlugin
// The dungeon map geometry (doorways, floors, walls): doorways taken straight on and
// big rooms crossed directly. Null (old cell walk) until DungeonLOS is up.
var geometry = DungeonPathfinder.GetGeometry(landblockKey, cellDat, _raycast?.GeometryLoader?.DungeonLOS);
// Portals (DungeonPathfinder.Portals.cs, 2026-10-23): the patrol keeps out of every portal the
// client knows in this dungeon (Tiny Hive: it walked onto the Surface Portal). A character
// standing in a portal's circle walks out first, and the patrol is built from where it gets
// to (that cell, that side of the portal).
var portals = PatrolPortalsIn(landblockKey);
double playerWX = ((playerCell >> 24) & 0xFF) * 192.0 + playerLocalX, playerWY = ((playerCell >> 16) & 0xFF) * 192.0 + playerLocalY;
(double X, double Y, double Z) startAt = (playerWX, playerWY, patrolWZ);
NavPoint? walkOut = null;
uint losCell = playerCell;
float losX = playerLocalX, losY = playerLocalY, losZ = patrolWZ;
List<PortalAvoidance>? portalReport = null;
// Diagnostics: record which rule laid each waypoint (logged below, one line each).
var pointLog = new Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo>(ReferenceEqualityComparer.Instance);
DungeonPathfinder.PointLog = pointLog;
NavRouteParser route;
try { route = DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards, geometry, patrolOptions); }
try
{
if (portals.Count > 0)
walkOut = DungeonPathfinder.PortalWalkOut(geometry, portals, playerWX, playerWY, patrolWZ, patrolOptions.WallClearance);
if (walkOut != null)
{
startAt = (DungeonGeometry.NavToWorld(walkOut.EW), DungeonGeometry.NavToWorld(walkOut.NS), walkOut.Z * 240.0);
uint outCell = DungeonPathfinder.CellAt(graph, geometry, walkOut);
if (graph.ContainsKey(outCell))
{
if (!evacuate && (hazards == null || !hazards.Contains(outCell))) startCell = outCell;
losCell = outCell;
losX = (float)(startAt.X - ((outCell >> 24) & 0xFF) * 192.0);
losY = (float)(startAt.Y - ((outCell >> 16) & 0xFF) * 192.0);
losZ = (float)startAt.Z;
}
}
route = DungeonPathfinder.BuildPatrolRoute(graph, startCell, hazards, geometry, patrolOptions, portals, startAt);
portalReport = DungeonPathfinder.LastPortalAvoidance;
}
finally { DungeonPathfinder.PointLog = null; }
// Lead the bot out of the hazard first.
@ -3012,7 +3043,24 @@ public sealed partial class RynthAiPlugin
route.Points.Insert(0, lead);
pointLog[lead] = new DungeonPathfinder.PatrolPointInfo { Kind = "evacuate", Cell = startCell, Why = "start cell is a hazard" };
}
// Pick the first waypoint with a clear line of sight from the player. The patrol
// builder emits its first waypoints at the doorway between startCell and its DFS-
// chosen neighbor — that doorway can sit on the far wall of startCell, so a player
// who logged in near the opposite wall faces a pillar or corner between them and
// waypoint 0. Walking the list forward to the first LOS-clear point sidesteps the
// "patrol immediately runs into a wall on login" failure mode. (From where the character
// walks out of a portal's circle to, when it stands in one.)
int startIdx = FindFirstLineOfSightWaypoint(route, losCell, losX, losY, losZ);
// The way to that waypoint: out of a portal's circle first, round any portal in between.
if (portals.Count > 0 && route.Points.Count > 0)
{
DungeonPathfinder.PointLog = pointLog;
try { startIdx = LeadPatrolPastPortals(route, graph, geometry, portals, portalReport, walkOut, playerWX, playerWY, patrolWZ, startIdx, patrolOptions.WallClearance); }
finally { DungeonPathfinder.PointLog = null; }
}
LogPatrolWaypoints(route, graph, geometry, hazards, pointLog, playerCell, startCell);
LogPatrolPortals(portalReport, portals, route);
// Empty-route guard: a single-cell / hazard-locked start yields no waypoints. Do NOT claim the
// patrol started or enable nav — the bot would just stand in place (in the hazard) taking damage.
@ -3024,14 +3072,6 @@ public sealed partial class RynthAiPlugin
return;
}
// Pick the first waypoint with a clear line of sight from the player. The patrol
// builder emits its first waypoints at the doorway between startCell and its DFS-
// chosen neighbor — that doorway can sit on the far wall of startCell, so a player
// who logged in near the opposite wall faces a pillar or corner between them and
// waypoint 0. Walking the list forward to the first LOS-clear point sidesteps the
// "patrol immediately runs into a wall on login" failure mode.
int startIdx = FindFirstLineOfSightWaypoint(route, playerCell, playerLocalX, playerLocalY, patrolWZ);
if (!isRebuild)
{
if (!settings.IsMacroRunning && RefuseMacroStartForVTank()) // one bot per client (Decal bridge)
@ -3058,13 +3098,19 @@ public sealed partial class RynthAiPlugin
_dunPatrolLandblock = landblockKey;
_dunPatrolHazardVersion = _objectCache?.HazardVersion ?? 0;
_dunPatrolSettings.MarkBuilt(patrolOptions);
MarkPatrolPortals(portals);
int hazardCount = hazards?.Count ?? 0;
string hazardNote = hazardCount > 0 ? $", {hazardCount} hazard cell(s) avoided" : "";
string portalNote = portals.Count > 0 ? $", kept out of {portals.Count} portal(s)" : "";
if (isRebuild && settingsChanged)
{
ChatLine($"[RynthAi] DunNav-Patrol: patrol settings changed → rebuilt from here, {route.Points.Count} waypoints ({patrolOptions.Describe()}).");
}
else if (isRebuild && portalAppeared)
{
ChatLine($"[RynthAi] DunNav-Patrol: a portal came into view → rerouted to keep out of it ({portals.Count} portal(s) kept out of).");
}
else if (isRebuild)
{
ChatLine($"[RynthAi] DunNav-Patrol: new hazard sighted → rerouted around it ({hazardCount} hazard cell(s) avoided).");
@ -3077,7 +3123,7 @@ public sealed partial class RynthAiPlugin
string layout = geometry != null && doorwayPts > 0
? $", {doorwayPts} of them lined up on doorways"
: geometry == null ? " (dungeon map not loaded yet: cell-centre route)" : "";
ChatLine($"[RynthAi] DunNav-Patrol: {graph.Count} cells, {route.Points.Count} waypoints{layout} → circular patrol started{skipNote}{hazardNote}");
ChatLine($"[RynthAi] DunNav-Patrol: {graph.Count} cells, {route.Points.Count} waypoints{layout} → circular patrol started{skipNote}{hazardNote}{portalNote}");
}
}
@ -3110,7 +3156,9 @@ public sealed partial class RynthAiPlugin
var patrolOptions = PatrolOptionsFrom(settings);
bool settingsChanged = _dunPatrolSettings.ShouldRebuild(patrolOptions, Environment.TickCount64);
bool hazardsChanged = _objectCache.HazardVersion != _dunPatrolHazardVersion;
if (!hazardsChanged && !settingsChanged) return; // nothing new sighted, settings as built
// A portal the patrol wasn't built round came into view (RynthAiPlugin.PatrolPortals.cs).
bool portalAppeared = PatrolPortalAppeared();
if (!hazardsChanged && !settingsChanged && !portalAppeared) return; // nothing new sighted, settings as built
// Only reroute if still in the dungeon this patrol was built for. A portal to a new
// landblock means BuildDunPatrol would (correctly) re-home, but that should happen via
@ -3123,9 +3171,10 @@ public sealed partial class RynthAiPlugin
return;
}
BuildDunPatrol(isRebuild: true, settingsChanged: settingsChanged);
BuildDunPatrol(isRebuild: true, settingsChanged: settingsChanged, portalAppeared: portalAppeared && !hazardsChanged);
// A rebuild that gave up (graph not loaded, ...) keeps the old route: don't retry every tick.
if (settingsChanged) _dunPatrolSettings.MarkBuilt(patrolOptions);
if (portalAppeared && _dunPatrolActive) MarkPatrolPortals(PatrolPortalsIn(_dunPatrolLandblock));
}
// ── Patrol-management info / actions (engine-side right-click flyout) ──────
@ -3283,14 +3332,18 @@ public sealed partial class RynthAiPlugin
var surfaces = DungeonHazardSurfaces.GetCellSurfaces(cellDat, portalDat, cell);
if (surfaces.Count == 0) { ChatLine($"[RynthAi] EnvCell 0x{cell:X8}: no readable surfaces."); return; }
ChatLine($"[RynthAi] EnvCell 0x{cell:X8} surfaces ({surfaces.Count}) — texId is the Detector C hazard key:");
// Only a texture on the walkable floor makes a cell a hazard; walls and ceilings don't.
var floorTex = DungeonHazardSurfaces.GetCellFloorTextures(cell, _raycast?.GeometryLoader?.DungeonLOS, portalDat);
ChatLine($"[RynthAi] EnvCell 0x{cell:X8} surfaces ({surfaces.Count}) — texId is the Detector C hazard key (floor textures only):");
foreach (var (surfIdx, texId) in surfaces)
{
string texStr = texId == 0 ? "(solid color)" : $"0x{texId:X8}";
string tag = texId != 0 && DungeonHazardSurfaces.IsHazardTexture(texId) ? " ← HAZARD" : "";
ChatLine($"[RynthAi] surf 0x{surfIdx:X4} tex {texStr}{tag}");
string where = texId != 0 && floorTex.Contains(texId) ? " floor" : "";
string tag = texId != 0 && DungeonHazardSurfaces.IsHazardTexture(texId)
? (floorTex.Contains(texId) ? " ← HAZARD" : " (flagged, but not on this floor)") : "";
ChatLine($"[RynthAi] surf 0x{surfIdx:X4} tex {texStr}{where}{tag}");
}
ChatLine("[RynthAi] On a lava/acid floor, run /ra hazard learnhere (auto) or /ra hazard texture add 0x<texId>.");
ChatLine("[RynthAi] On a lava/acid floor, run /ra hazard learnhere (auto) or /ra hazard texture add 0x<texId> (a floor texture).");
}
/// <summary>Stand on a hazard floor: flags the texture(s) rare across this landblock (the lava texture).</summary>
@ -3304,7 +3357,7 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] Geometry not loaded — raycast must be initialized first."); return;
}
var learned = DungeonHazardSurfaces.LearnFromCell(cell, cellDat, portalDat);
var learned = DungeonHazardSurfaces.LearnFromCell(cell, _raycast?.GeometryLoader?.DungeonLOS, portalDat);
DungeonPathfinder.InvalidateCache();
if (learned.Count == 0)
{

View file

@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The Dungeon Patrol keeps out of portals (2026-10-23). A portal fires when the character touches
/// it, and the patrol walked into one: in Tiny Hive (0x0289, coverage Everything) waypoint 1 sat on
/// the Surface Portal at the back of a nook two cells north of the start, and a client that began
/// its lap there was teleported out. Here: the portals the client knows in the dungeon (live
/// objects, PatrolPortalsIn) go to the patrol builder (DungeonPathfinder.Portals.cs) as circles to
/// keep out of; a character standing in one walks out first; a portal that comes into view after
/// the build rebuilds the patrol, as a new hazard does (TickDunPatrolHazardReroute). One log line per
/// portal says what was done about it.
/// </summary>
public sealed partial class RynthAiPlugin
{
private const uint PatrolItemTypePortal = 0x00010000;
/// <summary>A running patrol looks for portals it doesn't know this often.</summary>
private const long PatrolPortalCheckMs = 1000;
/// <summary>The portals the running patrol was built round.</summary>
private readonly HashSet<uint> _dunPatrolPortalIds = new();
private long _dunPatrolPortalCheckAt;
/// <summary>The keep-out radius for the current nav settings: the touch distance plus the corner a
/// point's reach (FollowNavMin) or the corner rounding (NavLookaheadYards) can cut.</summary>
private double PatrolPortalRadius()
{
var s = _dashboard?.Settings;
double reach = Math.Max(LegacyUiSettings.FollowNavMinLowest, s?.FollowNavMin ?? 1.5f);
double cut = Math.Max(reach, NavigationEngine.CornerLookaheadYards(s?.NavLookaheadYards ?? 4.0f, reach));
return DungeonPathfinder.PortalKeepOutRadius(cut);
}
/// <summary>
/// Every portal the client knows in dungeon landblock <paramref name="landblock"/> (static and
/// summoned: object class Portal, or an unclassified object whose item type says portal), with
/// its world position and cell, sorted by id.
/// </summary>
private List<PatrolPortal> PatrolPortalsIn(uint landblock)
{
var list = new List<PatrolPortal>();
if (_objectCache == null || !Host.HasGetObjectPosition) return list;
double radius = PatrolPortalRadius();
foreach (var wo in _objectCache.GetLandscapeObjects())
{
uint uid = unchecked((uint)wo.Id);
bool portal = wo.ObjectClass == AcObjectClass.Portal
|| (wo.ObjectClass == AcObjectClass.Unknown && Host.TryGetItemType(uid, out uint type) && (type & PatrolItemTypePortal) != 0);
if (!portal) continue;
if (!Host.TryGetObjectPosition(uid, out uint cell, out float x, out float y, out float z) || cell == 0) continue;
if ((cell >> 16) != landblock || (cell & 0xFFFF) < 0x0100) continue;
list.Add(new PatrolPortal
{
Id = uid, Name = wo.Name ?? "", Cell = cell,
X = ((cell >> 24) & 0xFF) * 192.0 + x, Y = ((cell >> 16) & 0xFF) * 192.0 + y, Z = z,
Radius = radius,
});
}
list.Sort((a, b) => a.Id.CompareTo(b.Id));
return list;
}
/// <summary>
/// The running patrol's dungeon has a portal it wasn't built round (one that arrived after the
/// build: a dungeon's objects stream in after portal space, a summoned portal). Checked every
/// PatrolPortalCheckMs.
/// </summary>
private bool PatrolPortalAppeared()
{
long now = Environment.TickCount64;
if (now < _dunPatrolPortalCheckAt) return false;
_dunPatrolPortalCheckAt = now + PatrolPortalCheckMs;
foreach (var p in PatrolPortalsIn(_dunPatrolLandblock))
{
if (_dunPatrolPortalIds.Contains(p.Id)) continue;
Host.Log($"[RynthAi] DunNav-Patrol: portal 0x{p.Id:X8} '{p.Name}' came into view at ({p.X:F1},{p.Y:F1},{p.Z:F1}) cell {p.Cell:X8}: rebuilding round it");
return true;
}
return false;
}
/// <summary>Notes the portals a patrol was built round (so only a new one rebuilds it).</summary>
private void MarkPatrolPortals(List<PatrolPortal> portals)
{
_dunPatrolPortalIds.Clear();
foreach (var p in portals) _dunPatrolPortalIds.Add(p.Id);
_dunPatrolPortalCheckAt = Environment.TickCount64 + PatrolPortalCheckMs;
}
/// <summary>
/// Leads the character from where it stands (or from <paramref name="walkOut"/>, the spot it
/// walks to out of a portal's circle) to the route's first point <paramref name="startIdx"/>
/// without passing a portal: the walk-out spot and any corners round a circle in the way go in
/// front of it, the legs joining them to the rest of the loop are kept out too. Returns the
/// index to start at.
/// </summary>
private int LeadPatrolPastPortals(NavRouteParser route, Dictionary<uint, DungeonNavNode> graph, DungeonGeometry? geometry,
List<PatrolPortal> portals, List<PortalAvoidance>? report, NavPoint? walkOut,
double playerWX, double playerWY, double playerWZ, int startIdx, double wall)
{
if (portals.Count == 0 || route.Points.Count == 0) return startIdx;
if (report != null)
foreach (var r in report)
if (DungeonPathfinder.InsidePortal(r.Portal, playerWX, playerWY, playerWZ)) r.StartInside = true;
startIdx = Math.Clamp(startIdx, 0, route.Points.Count - 1);
var from = walkOut ?? new NavPoint
{
Type = NavPointType.Point,
EW = DungeonGeometry.WorldToNav(playerWX), NS = DungeonGeometry.WorldToNav(playerWY), Z = playerWZ / 240.0,
};
var corners = DungeonPathfinder.PortalLeadIn(graph, geometry, portals, from, route.Points[startIdx], wall, report);
var way = new List<NavPoint> { from };
way.AddRange(corners);
way.Add(route.Points[startIdx]);
bool clear = true;
for (int i = 0; i + 1 < way.Count && clear; i++) clear = DungeonPathfinder.PortalLegClear(null, portals, way[i], way[i + 1]);
if (!clear)
{
// No way round to that one: the nearest waypoint the walk to keeps out (and is walkable).
int best = -1;
double bestD = double.MaxValue;
for (int i = 0; i < route.Points.Count; i++)
{
var q = route.Points[i];
double d = Math.Sqrt((q.NS - from.NS) * (q.NS - from.NS) + (q.EW - from.EW) * (q.EW - from.EW)) * 240.0;
if (d < bestD && DungeonPathfinder.PortalLegClear(geometry, portals, from, q)) { bestD = d; best = i; }
}
if (best >= 0) { startIdx = best; corners.Clear(); }
Host.Log(best >= 0
? $"[RynthAi] DunNav-Patrol: no way round a portal to the first waypoint in sight; starting at waypoint {best} instead"
: "[RynthAi] DunNav-Patrol: no way to the patrol from here that keeps out of the portal(s)");
}
var lead = new List<NavPoint>();
if (walkOut != null) lead.Add(walkOut);
lead.AddRange(corners);
if (lead.Count == 0) return startIdx;
route.Points.InsertRange(startIdx, lead);
DungeonPathfinder.KeepOutOfPortals(route.Points, closed: true, graph, geometry, portals, report, wall);
for (int i = 0; i < route.Points.Count; i++)
if (ReferenceEquals(route.Points[i], lead[0])) return i;
return Math.Min(startIdx, route.Points.Count - 1);
}
/// <summary>One log line per portal the patrol was built round.</summary>
private void LogPatrolPortals(List<PortalAvoidance>? report, List<PatrolPortal> portals, NavRouteParser route)
{
if (portals.Count == 0) return;
try
{
if (report == null)
{
Host.Log($"[RynthAi] DunNav-Patrol: {portals.Count} portal(s) known, none reached by the patrol's dungeon");
return;
}
foreach (var r in report)
{
r.Nearest = DungeonPathfinder.NearestApproach(route.Points, closed: true, r.Portal);
Host.Log("[RynthAi] DunNav-Patrol " + r.Describe());
}
}
catch (Exception ex)
{
Host.Log($"[RynthAi] DunNav-Patrol portal log failed: {ex.Message}");
}
}
}

View file

@ -2489,6 +2489,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
float prevRatio = _objectCache?.GetHealthRatio(unchecked((int)targetId)) ?? -1f;
_sessionStats?.OnUpdateHealth(targetId, currentHealth, maxHealth);
_objectCache?.OnUpdateHealth(targetId, healthRatio);
_combatManager?.NoteServerHealth(unchecked((int)targetId), healthRatio); // kill-shot evidence (fight target only)
_dashboard?.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
if (_loginComplete && targetId == _playerId && maxHealth > 0)
{

View file

@ -88,9 +88,9 @@ public sealed partial class RynthDefectivePlugin
string where = string.Empty;
float relative = float.NaN;
bool carried = false;
foreach (var it in _session.Items()) if (it.Id == sel) { carried = true; break; }
if (carried) where = "in your pack";
Items.CarriedItem? carried = null;
foreach (var it in _session.Items()) if (it.Id == sel) { carried = it; break; }
if (carried != null) where = CarriedText(carried);
else if (Host.TryGetObjectPosition(sel, out uint oc, out float ox, out float oy, out float oz) && oc != 0
&& Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out float qw, out _, out _, out float qz) && pc != 0)
{
@ -105,12 +105,27 @@ public sealed partial class RynthDefectivePlugin
if (dist >= 0.5) relative = (float)rel;
where = $"{dist.ToString(dist < 10 ? "0.0" : "0", CultureInfo.InvariantCulture)} yd {Compass(bearing)}";
}
// Not carried (on the ground, in a corpse or chest): AC's own stack size.
if (carried == null && Host.TryGetObjectIntProperty(sel, StackSizeProperty, out int stack) && stack > 1)
where = "stack of " + stack.ToString("N0", CultureInfo.InvariantCulture) + (where.Length > 0 ? " · " + where : "");
HealthSeen? h = _health;
float health = h != null && h.Id == sel ? h.Ratio : -1f;
return new SelectionView(true, sel, name, where, relative, health, h?.Current ?? 0, h?.Max ?? 0);
}
private const uint StackSizeProperty = 12; // PropertyInt.StackSize
/// <summary>A carried item's line: how many in the stack or uses left, and where (in your pack, in hand, worn).</summary>
private static string CarriedText(Items.CarriedItem it)
{
var parts = new System.Collections.Generic.List<string>(2);
if (it.MaxStack > 1 || it.Stack > 1) parts.Add("stack of " + it.Stack.ToString("N0", CultureInfo.InvariantCulture));
if (it.MaxUses > 0) parts.Add($"{it.Uses.ToString(CultureInfo.InvariantCulture)} of {it.MaxUses.ToString(CultureInfo.InvariantCulture)} uses");
parts.Add(!it.Wielded ? "in your pack" : Items.ItemKinds.IsWeapon(Items.ItemKinds.Classify(it)) ? "in hand" : "worn");
return string.Join(" · ", parts);
}
/// <summary>A landblock coordinate as a world one: 192 units a landblock (the cell's high bytes).</summary>
private static double Global(uint cell, float local, bool x) =>
((x ? cell >> 24 : cell >> 16) & 0xFF) * 192.0 + local;

View file

@ -156,7 +156,13 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
else if (_barWindow != null) { _barWindow.Visible = !_barWindow.Visible; _barWindow.NeedsPass = true; NoteNoUi(_barWindow.Visible); }
break;
case DefVerb.Selection when c.Text.Length > 0:
if (uint.TryParse(c.Text.Replace("0x", "", StringComparison.OrdinalIgnoreCase), System.Globalization.NumberStyles.HexNumber, null, out uint pick))
// Test hooks: "/rdef selection 0x80001234" selects that object; "stack" the first stack in the pack.
if (c.Text.Equals("stack", StringComparison.OrdinalIgnoreCase))
{
foreach (var it in _session.Items())
if (it.Stack > 1 && !it.Wielded) { Host.SelectItem(it.Id); break; }
}
else if (uint.TryParse(c.Text.Replace("0x", "", StringComparison.OrdinalIgnoreCase), System.Globalization.NumberStyles.HexNumber, null, out uint pick))
Host.SelectItem(pick);
break;
case DefVerb.Selection:

View file

@ -382,7 +382,7 @@ internal static class ActionPacer
bool animationGate = true, bool settleGate = true, bool attackRepeat = false)
{
if (!Enabled) { why = ""; return true; }
if (ServerBusyHolds(host, who, attackRepeat, out why, heal)) return false;
if (ServerBusyHolds(host, who, attackRepeat, out why, out bool tryAfterBusy, heal)) return false;
// An emergency heal does not wait for the movement settle (150-600 ms): at Emergency Heal At
// the heal comes first; it still obeys the in-flight rules below (OutstandingAllows, GestureHolds).
if (settleGate && heal != HealNeed.Emergency && MoveAudit.SettleHolds(host, out why))
@ -395,9 +395,26 @@ internal static class ActionPacer
lock (Gate) _settleLogged.Clear();
if (!OutstandingAllows(host, who, heal, out why, attackRepeat)) return false;
if (animationGate && GestureHolds(host, who, heal, out why)) return false;
// The one try after a 'too busy' answer is spent only by a start that goes: one held by the checks
// above left it for the next asker. A Conquest report (10-25): after a corpse pickup and a cast went
// out together, the buff step took all three tries and sent nothing (still animating), combat never
// got one, and the fight stood for the latch's 15 s.
if (tryAfterBusy) SpendTryAfterBusy(host, who);
return true;
}
private static void SpendTryAfterBusy(RynthCoreHost host, string who)
{
int n;
lock (Gate)
{
_probes++;
_lastProbeAt = NowMs();
n = _probes;
}
Log(host, $"[Pace] {who}: one try (#{n}) after the server's 'too busy' answer; no cast of ours is open");
}
private static bool OutstandingAllows(RynthCoreHost host, string who, HealNeed heal, out string why, bool attack = false)
{
why = "";
@ -762,9 +779,10 @@ internal static class ActionPacer
/// a hung cast) or the character is in the air after a breaker jump. Runs the held-cast turn and
/// the stuck-cast breaker. Called by MayStart.
/// </summary>
private static bool ServerBusyHolds(RynthCoreHost host, string who, bool attackRepeat, out string why, HealNeed heal = HealNeed.None)
private static bool ServerBusyHolds(RynthCoreHost host, string who, bool attackRepeat, out string why, out bool tryAfterBusy, HealNeed heal = HealNeed.None)
{
why = "";
tryAfterBusy = false;
bool healStart = heal != HealNeed.None;
long now = NowMs();
long gapEnd, gapLen;
@ -815,9 +833,7 @@ internal static class ActionPacer
if (!attackRepeat && stuck == null && _busySince != 0 && _stage == BreakStage.None && !healWaiting
&& now - Math.Max(_busySince, _lastProbeAt) >= Math.Min(BusyProbeMs << Math.Min(_probes, 8), BusyProbeMaxMs))
{
probe = true;
_probes++;
_lastProbeAt = now;
probe = true; // spent in MayStart once the start passes its other checks (SpendTryAfterBusy)
}
}
@ -860,7 +876,7 @@ internal static class ActionPacer
}
if (probe)
{
Log(host, $"[Pace] {who}: one try (#{_probes}) after the server's 'too busy' answer; no cast of ours is open");
tryAfterBusy = true;
return false;
}

View file

@ -29,6 +29,7 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.cs" Link="Linked\DungeonPathfinder.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.Rooms.cs" Link="Linked\DungeonPathfinder.Rooms.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.Sweep.cs" Link="Linked\DungeonPathfinder.Sweep.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPathfinder.Portals.cs" Link="Linked\DungeonPathfinder.Portals.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonGeometry.cs" Link="Linked\DungeonGeometry.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonPatrolOptions.cs" Link="Linked\DungeonPatrolOptions.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\DungeonHazardSurfaces.cs" Link="Linked\DungeonHazardSurfaces.cs" />

View file

@ -27,6 +27,8 @@ namespace RynthCore.PatrolProof;
// floors off, wall distances, look-in sizes): patrol cells, waypoints, lap length
// pockets for each start, the dead-end areas off the reachable cells (largest first, the
// ones hanging off the trunk), their rooms and the smaller areas inside them
// portal x,y,z[,r] a portal the patrol keeps out of (world metres; r the keep-out radius, default
// 3.5 m), as BuildDunPatrol passes the live ones; repeatable. One line per portal.
// The start cell is handled as BuildDunPatrol does: a start in a hazard moves to NearestSafeCell.
internal static class Waypoints
{
@ -40,6 +42,7 @@ internal static class Waypoints
var inv = CultureInfo.InvariantCulture;
var extra = new HashSet<uint>();
var fileCells = new HashSet<uint>();
var portals = new List<PatrolPortal>();
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
@ -66,6 +69,12 @@ internal static class Waypoints
if (uint.TryParse(l.Replace("0x", ""), NumberStyles.HexNumber, null, out uint c)) fileCells.Add(c);
}
}
else if (a == "portal" && i + 1 < args.Length)
{
double[] v = args[++i].Split(',').Select(t => double.Parse(t, inv)).ToArray();
portals.Add(new PatrolPortal { Id = (uint)portals.Count + 1, Name = "given", X = v[0], Y = v[1], Z = v[2],
Radius = v.Length > 3 ? v[3] : DungeonPathfinder.PortalKeepOutDefault });
}
else if (a == "hz" && i + 1 < args.Length)
foreach (string t in args[++i].Split(',', StringSplitOptions.RemoveEmptyEntries))
extra.Add(uint.Parse(t.Replace("0x", ""), NumberStyles.HexNumber));
@ -80,7 +89,7 @@ internal static class Waypoints
if (!loader.Initialize(acDir)) { Console.WriteLine("Geometry loader failed: " + loader.StatusMessage); return 1; }
var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
var surfaceCells = DungeonHazardSurfaces.ComputeHazardCells(lb, loader.CellDat, loader.PortalDat);
var surfaceCells = DungeonHazardSurfaces.ComputeHazardCells(lb, loader.DungeonLOS, loader.PortalDat);
Console.WriteLine($"Landblock 0x{lb:X4}: {graph.Count} cells; hazard textures {DungeonHazardSurfaces.HazardTextureCount} -> {surfaceCells.Count} Detector C cells: {Ids(surfaceCells)}");
if (fileCells.Count > 0) Console.WriteLine($" hzfile cells: {Ids(fileCells)}");
if (extra.Count > 0) Console.WriteLine($" hz cells: {Ids(extra)}");
@ -120,15 +129,22 @@ internal static class Waypoints
var log = new Dictionary<NavPoint, DungeonPathfinder.PatrolPointInfo>(ReferenceEqualityComparer.Instance);
DungeonPathfinder.PointLog = log;
NavRouteParser route;
try { route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo, opt); }
List<PortalAvoidance> avoided;
try
{
route = DungeonPathfinder.BuildPatrolRoute(graph, start, hazards, geo, opt, portals);
avoided = DungeonPathfinder.LastPortalAvoidance;
}
finally { DungeonPathfinder.PointLog = null; }
var lines = DungeonPathfinder.DescribePatrol(route, graph, geo, hazards, log);
if (avoided != null) lines.AddRange(avoided.Select(r => "wp " + r.Describe()));
Console.WriteLine();
Console.WriteLine($"== start {s0:X8}{(start != s0 ? $" (moved to safe {start:X8})" : "")}, hazards {name} ({cells.Count})");
Console.WriteLine(" " + EnteredRooms(route, graph, geo, hazards, log));
foreach (string l in lines)
{
bool isSummary = l.StartsWith("wp summary", StringComparison.Ordinal) || l.StartsWith("wp main route", StringComparison.Ordinal);
bool isSummary = l.StartsWith("wp summary", StringComparison.Ordinal) || l.StartsWith("wp main route", StringComparison.Ordinal)
|| l.StartsWith("wp portal", StringComparison.Ordinal);
if (summaryOnly && !isSummary) continue;
if (tinyOnly && !isSummary && !IsTiny(l)) continue;
Console.WriteLine(" " + l);

View file

@ -23,6 +23,9 @@ internal static class Program
/// <summary>CreatureProfileStore's folder before Main pointed it at the scratch folder.</summary>
public static string LiveCreatureFolder { get; private set; } = "";
/// <summary>DungeonHazardSurfaces' folder (HazardTextures.txt) before Main pointed it at the scratch folder.</summary>
public static string LiveHazardTextureFolder { get; private set; } = "";
private static int Main(string[] args)
{
if (Directory.Exists(TempRoot)) Directory.Delete(TempRoot, recursive: true);
@ -39,6 +42,10 @@ internal static class Program
// 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");
// Detector C's flagged floor textures are persisted to C:\Games\RynthSuite\RynthAi\HazardTextures.txt.
LiveHazardTextureFolder = RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Folder;
RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Folder = Path.Combine(TempRoot, "HazardTextures");
RynthCore.Plugin.RynthAi.DungeonHazardSurfaces.Reload();
// Appraised creatures are saved to C:\Games\RynthSuite\RynthAi\CreatureData\creatures.json.
LiveCreatureFolder = RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder;
RynthCore.Plugin.RynthAi.CreatureData.CreatureProfileStore.Folder = Path.Combine(TempRoot, "CreatureData");
@ -64,6 +71,7 @@ internal static class Program
PatrolDoorwayTests.Register(runner);
PatrolSettingsTests.Register(runner);
PatrolPocketTests.Register(runner);
PatrolPortalTests.Register(runner);
BuffTests.Register(runner);
SpellCatalogTests.Register(runner);
CombatMathTests.Register(runner);
@ -110,6 +118,7 @@ internal static class Program
NavOverlayTests.Register(runner);
ActionPacingTests.Register(runner);
HazardEscapeTests.Register(runner);
HazardFloorTests.Register(runner);
ManaStoneChoiceTests.Register(runner);
CustomDebuffTests.Register(runner);
DebuffRenewTests.Register(runner);

View file

@ -62,6 +62,7 @@ internal static class ActionPacingTests
r.Add("refusal: a refused peace-before-open is asked again inside the 2.5 s ceiling; exactly one accepted request goes out before the open", PeaceBeforeOpenRefusedRetried);
r.Add("refusal: a streak that went quiet for 10 s+ (a death, a logout) is over - 600 s later a refusal starts a fresh streak, and Forget ends one", RefusalStreakExpires);
r.Add("refusal: wand wielded, a request accepted then dropped (a teleport), 9 s of refusals - the stuck clock restarts, no re-equip UseObject", StuckClockRestartsOnRefusal);
r.Add("stance clock (Drakkon 10-23): Magic seen ends the episode; a request a minute after the last starts a new one (no 'stuck 1123s')", StuckClockEndsInMagicAndAfterAGap);
r.Add("refusal: the stall watchdog's refused mode toggle spends no ladder step (Unfire) and is asked again next tick", StallToggleRefusedSpendsNoStep);
r.Add("refusal: missile crafting asks for peace until accepted, and combines after the 2.5 s ceiling; already in peace it combines on the first tick with no mode request", CraftingPeaceRefusal);
r.Add("pacing (stance): a refused ChangeCombatMode burns no try and no backoff step, and the next tick asks again (pacing on and off)", RefusedStanceBurnsNothing);
@ -751,6 +752,49 @@ internal static class ActionPacingTests
finally { PaceOff(); }
}
// Drakkon 10-23 22:30: the launcher killed him on "[BuffStance] ChangeCombatMode(Magic) retry #4 (stuck 1123s)".
// The clock had started on a Magic request 18 minutes before and never ended: Magic was reached while
// EnsureMagicMode wasn't looking (combat took the stance back to its weapons first).
private static void StuckClockEndsInMagicAndAfterAGap()
{
PaceOff();
try
{
var r = new BuffRig(CombatMode.NonCombat);
SetupBuffRigVitals(r);
FakeHost.Names[Wand] = "Academy Wand";
FakeHost.ItemTypes[Wand] = 0x8000;
FakeHost.Ints[(Wand, 10)] = 0x01000000; // in hand
r.S.WieldUnlistedWandWhenNoneListed = true;
r.B.SetWorldObjectCache(FakeHost.MakeCache(r.Host, Player, new[] { Wand }));
var since = typeof(BuffManager).GetField("_buffStanceStuckSince", Priv)!;
var lastTry = typeof(BuffManager).GetField("_lastBuffStanceAttempt", Priv)!;
var noteMode = typeof(BuffManager).GetMethod("NoteModeChange", Priv)!;
r.At(0); r.B.OnHeartbeat();
Check.True((DateTime)since.GetValue(r.B)! != DateTime.MinValue, "set-up: a Magic request started the stuck clock");
// The client reaches Magic and combat swaps back to its weapons before the buff step looks.
FakeHost.CombatModeValue = CombatMode.Magic;
noteMode.Invoke(r.B, null);
Check.True((DateTime)since.GetValue(r.B)! == DateTime.MinValue, "seen in Magic: the episode is over, the clock stopped");
FakeHost.CombatModeValue = CombatMode.Melee;
noteMode.Invoke(r.B, null);
// A clock left running anyway (any other way out): 20 minutes on, the next request starts afresh.
since.SetValue(r.B, r.T0.AddMinutes(-20));
lastTry.SetValue(r.B, r.T0.AddMinutes(-20));
FakeHost.CombatModeValue = CombatMode.NonCombat;
noteMode.Invoke(r.B, null);
FakeHost.Logs.Clear();
r.At(1); r.B.OnHeartbeat();
string retry = FakeHost.Logs.FirstOrDefault(l => l.Contains("[BuffStance] ChangeCombatMode(Magic) retry")) ?? "";
Check.True(retry.Contains("retry #1 (stuck 0s"), "a new episode: retry #1, stuck 0 s, not 1200 s: " + retry);
Check.True((r.NowAt - (DateTime)since.GetValue(r.B)!).TotalSeconds < 3, "the clock starts now");
}
finally { PaceOff(); }
}
private static void StallToggleRefusedSpendsNoStep()
{
PaceOff();

View file

@ -34,6 +34,29 @@ internal static class BlastTests
r.Add("known spells: a name with several ids resolves to the id the character knows", DuplicateNameIds);
r.Add("monster rules: UseBlast saves and loads; old files load with it off", RuleJson);
r.Add("blast override: Blast Range off keeps today's shape; on, the base is the other shape; defaults 0 / 3", BlastOverrideSettings);
r.Add("rings (10-25): the level-5 rings from tier 5 (named or plain), the level-7 II from tier 7", RingLevels);
}
// The rings are level 5 (Cassius' Ring of Fire, Halo of Frost, ..., and the plain Flame / Acid / Force /
// Lightning Ring) and level 7 (the named II). A tier-5 caster used to get no ring at all: the named one
// waited for tier 6 and the plain ones were looked for as "Ring of Fire V" and the like.
private static void RingLevels()
{
var find = typeof(CombatManager).GetMethod("FindBestRingSpell",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
string Ring(int tier, string element, params string[] known)
{
var rig = new CastRig(tier, known);
return NameOf((int)find.Invoke(rig.C, new object[] { element, RynthCore.Loot.AcSkillType.WarMagic })!);
}
Check.Eq(Ring(5, "Fire", "Cassius' Ring of Fire"), "Cassius' Ring of Fire", "tier 5: the named level-5 ring");
Check.Eq(Ring(5, "Fire", "Flame Ring"), "Flame Ring", "tier 5: the plain level-5 ring when that is the one known");
Check.Eq(Ring(5, "Lightning", "Lightning Ring"), "Lightning Ring", "Lightning's plain ring");
Check.Eq(Ring(6, "Cold", "Halo of Frost"), "Halo of Frost", "tier 6: the level-5 ring");
Check.Eq(Ring(7, "Cold", "Halo of Frost", "Halo of Frost II"), "Halo of Frost II", "tier 7: the II");
Check.Eq(Ring(7, "Cold", "Halo of Frost"), "Halo of Frost", "tier 7 without the II known: the level-5 one");
Check.Eq(Ring(6, "Cold", "Halo of Frost", "Halo of Frost II"), "Halo of Frost", "tier 6 knowing the II: not yet (level 7)");
Check.Eq(Ring(4, "Cold", "Halo of Frost"), "(none)", "tier 4: no ring (none below level 5)");
}
// ── Rig ───────────────────────────────────────────────────────────────────

View file

@ -29,6 +29,171 @@ internal static class CastNoDamageTests
r.Add("no-damage casts: the chat after a combat cast is logged, swings at us left out, capped, 4 s", CastChatTrace);
r.Add("no-damage casts (flight 63260): 3 magic casts landing nothing -> one short real sidestep, no cast meanwhile; a hit resets; 30 s apart", ResyncSidestep);
r.Add("no-damage casts (R-20261021 c788): a corpse selected mid-fight stops the target's health; its chat hits still count, it is not blacklisted", SelectionElsewhereChatHitsCount);
r.Add("kill shot (R-20261025 727b): cast #37 of ~37 is no kill with ~155k of a 450k boss left", KillShotVetoedByHpPool);
r.Add("kill shot (R-20261025 727b): fresh server health vetoes it; stale health doesn't", KillShotVetoedByFreshHealth);
r.Add("kill shot (R-20261025 727b): a normal 3-cast mob is still predicted on its last cast", KillShotNormalMobStillPredicted);
r.Add("kill shot (R-20261025 727b): the armed cast's own hit calls the swap off; the previous bolt's doesn't", ArmedSwapCalledOffByHit);
}
// ── A boss swapped off as dead (report R-20261025-183343-727b, Conquest) ─────────────────────
// "Predicted kill shot 0x80621EBC 'Curator of Torment' (cast#37 hp~450250 dealt~294989)": the
// learned casts-to-kill (~37) fired on the count alone with ~155,000 HP left; the bot locked a
// Rynthid that died at once and looted a corpse while the Curator (34%) hit the player.
private const uint Boss = 0x80621EBC, Rynthid = 0x80539C4E, BossWcid = 40001, RynthidWcid = 40010;
private const int FlameBolt8 = 8;
private const string BossHit = "You singe Curator of Torment for 8194 points with Incantation of Flame Bolt.";
private sealed class BossRig
{
public readonly LegacyUiSettings S = new() { MonsterRange = 30 };
public readonly MonsterDamageStore Store = new();
public readonly CombatManager C;
public DateTime Now = new(2026, 10, 25, 19, 29, 24);
/// <param name="pool">The Curator's HP (the Damage panel's manual HP); 0 = unknown.</param>
/// <param name="castsToKill">What the store learned: casts of Flame Bolt VIII to kill one.</param>
public BossRig(double pool, int castsToKill, uint wcid = BossWcid)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true;
FakeHost.CombatModeValue = CombatMode.Magic;
FakeHost.Names[Player] = "Me";
FakeHost.Positions[Player] = (Lb | 0x0141, 96f, 96f, 0f);
FakeHost.PlayerPose = (Lb | 0x0141, 96f, 96f, 0f);
FakeHost.Names[Boss] = "Curator of Torment";
FakeHost.Positions[Boss] = (Lb | 0x0141, 96f, 97.9f, 0f);
FakeHost.ItemTypes[Boss] = 0x10;
FakeHost.Wcids[Boss] = wcid;
FakeHost.Names[Rynthid] = "Discorporate Rynthid of Rage";
FakeHost.Positions[Rynthid] = (Lb | 0x0141, 97.7f, 96f, 0f);
FakeHost.ItemTypes[Rynthid] = 0x10;
FakeHost.Wcids[Rynthid] = RynthidWcid;
var host = FakeHost.Create();
var cache = FakeHost.MakeCache(host, Player, new[] { Boss, Rynthid }, null);
C = new CombatManager(host, S, cache);
C.SetPlayerId(Player);
C.SetDamageStores(null, Store);
C.TargetClock = () => Now;
for (int i = 0; i < 3; i++)
{
Store.RecordKill(Wand, wcid, "Curator of Torment", "Fire", FlameBolt8, castsToKill, 0);
Store.RecordHit(Wand, wcid, "Curator of Torment", "Fire", FlameBolt8, 8194, false);
}
if (pool > 0) Store.SetManualHp(wcid, pool, "Curator of Torment");
C.SetScannedTargetsForTests(new[]
{
new CombatManager.ScannedTarget { Id = unchecked((int)Boss), Distance = 1.9, Angle = 0, Bearing = double.NaN, Name = "Curator of Torment" },
new CombatManager.ScannedTarget { Id = unchecked((int)Rynthid), Distance = 1.7, Angle = 87, Bearing = double.NaN, Name = "Discorporate Rynthid of Rage" },
});
C.EngageForTest(unchecked((int)Boss));
}
public bool Cast() => C.CastAndPredictForTest(Wand, "Fire", FlameBolt8);
/// <summary><paramref name="casts"/> casts, each landing <paramref name="hit"/>, 3.7 s apart; false if any predicted a kill.</summary>
public bool CastAndHit(int casts, string hit)
{
bool any = false;
for (int i = 0; i < casts; i++)
{
any |= Cast();
Now = Now.AddSeconds(3.7);
C.HandleChatForDamage(hit, 7);
}
return any;
}
public int LogCount(string part) => FakeHost.Logs.Count(l => l.Contains(part, StringComparison.Ordinal));
}
private static void KillShotVetoedByHpPool()
{
var r = new BossRig(pool: 450250, castsToKill: 37);
Check.False(r.CastAndHit(36, BossHit), "casts 1-36: no prediction (count not reached, ~155k+ left)");
Check.False(r.Cast(), "cast #37: the count is reached but ~155k of 450k HP are left: no kill predicted");
Check.Eq(r.LogCount("Kill shot not predicted for 0x80621EBC 'Curator of Torment'"), 1, "said, naming the boss");
Check.True(r.LogCount("of its ~450250 HP are left") == 1, "with the HP evidence");
Check.False(r.Cast(), "cast #38: still none");
Check.Eq(r.LogCount("Kill shot not predicted"), 1, "the line is once a fight, not per cast");
Check.Eq(unchecked((uint)r.C.activeTargetId), Boss, "still on the Curator");
// Hit on until the evidence agrees: predicted once what is left is within a cast and a half.
int hits = 36;
bool predicted = false;
while (!predicted && hits < 60)
{
r.C.HandleChatForDamage(BossHit, 7);
hits++;
double before = 450250 - hits * 8194.0;
predicted = r.Cast();
if (!predicted)
Check.True(before > 1.5 * 8194, $"not predicted only while more than 1.5 casts are left (~{before:0})");
}
double leftAt = 450250 - hits * 8194.0;
Check.True(predicted, "the finishing cast is still predicted");
Check.True(leftAt > 0 && leftAt <= 1.5 * 8194, $"with ~{leftAt:0} left (within a cast and a half)");
}
private static void KillShotVetoedByFreshHealth()
{
// HP pool unknown: only the server's health can say. 36 casts landed (~295k), the Curator at 34%.
var r = new BossRig(pool: 0, castsToKill: 37);
r.CastAndHit(36, BossHit);
r.C.NoteServerHealth(unchecked((int)Boss), 0.34f); // came with the last hit (selected)
Check.False(r.Cast(), "cast #37 at 34% health (~152k left by the damage dealt): no kill predicted");
Check.True(r.LogCount("the server says its health is 34%") == 1, "the health is the reason given");
// The same fight with a health reading from before the last hit: it doesn't count that
// hit, so it is no evidence, and the count alone predicts as before.
r = new BossRig(pool: 0, castsToKill: 37);
r.CastAndHit(35, BossHit);
r.C.NoteServerHealth(unchecked((int)Boss), 0.34f);
r.CastAndHit(1, BossHit); // a hit 3.7 s after the reading
Check.True(r.Cast(), "stale health: cast #37 is predicted (no evidence against it)");
Check.Eq(r.LogCount("Kill shot not predicted"), 0, "nothing vetoed");
// Another monster's health is not the fight target's.
r = new BossRig(pool: 0, castsToKill: 37);
r.CastAndHit(36, BossHit);
r.C.NoteServerHealth(unchecked((int)Rynthid), 0.34f);
Check.True(r.Cast(), "the Rynthid's health says nothing about the Curator");
}
private static void KillShotNormalMobStillPredicted()
{
// A mob of 24,000 HP that 3 bolts kill: cast #3 is the kill, by count and by the damage left.
const string hit = "You singe Curator of Torment for 8000 points with Incantation of Flame Bolt.";
var r = new BossRig(pool: 24000, castsToKill: 3, wcid: 40020);
Check.False(r.CastAndHit(2, hit), "casts 1-2: no prediction");
Check.True(r.Cast(), "cast #3: predicted (8,000 left, one cast ~8,000)");
// With its health in: 33% left of 24,000 agrees.
r = new BossRig(pool: 24000, castsToKill: 3, wcid: 40020);
r.CastAndHit(2, hit);
r.C.NoteServerHealth(unchecked((int)Boss), 0.33f);
Check.True(r.Cast(), "fresh health at 33% agrees: predicted");
// A low roll on the way (dealt 13,000 of 24,000): 11,000 left is within reach of one cast, still predicted.
r = new BossRig(pool: 24000, castsToKill: 3, wcid: 40020);
r.CastAndHit(1, hit);
r.CastAndHit(1, "You singe Curator of Torment for 5000 points with Incantation of Flame Bolt.");
Check.True(r.Cast(), "a low roll before the last cast doesn't hold the prediction back");
Check.Eq(r.LogCount("Kill shot not predicted"), 0, "nothing vetoed for the normal mob");
}
private static void ArmedSwapCalledOffByHit()
{
var r = new BossRig(pool: 0, castsToKill: 37);
r.C.ArmPredictedSwapForTest(castAgoMs: 2900); // the bolt went out 2.9 s ago
r.C.HandleChatForDamage("You singe Curator of Torment for 7883 points with Incantation of Flame Bolt.", 7);
Check.False(r.C.PredictedSwapArmed, "its hit landed and it is alive: the swap is called off");
Check.Eq(r.LogCount("Predicted kill shot 0x80621EBC 'Curator of Torment' called off"), 1, "and logged");
Check.Eq(unchecked((uint)r.C.activeTargetId), Boss, "still on the Curator");
r = new BossRig(pool: 0, castsToKill: 37);
r.C.ArmPredictedSwapForTest(castAgoMs: 200); // the line can't be this cast's: no windup is that short
r.C.HandleChatForDamage(BossHit, 7);
Check.True(r.C.PredictedSwapArmed, "the previous bolt landing just after the arming cast doesn't call it off");
r.C.HandleChatForDamage("Discorporate Rynthid of Rage catches your attack, with dire consequences!", 0);
Check.True(r.C.PredictedSwapArmed, "nor does another monster's line");
}
// ── A corpse selected during the fight (report R-20261021-191720-c788, Conquest) ─────────────

View file

@ -0,0 +1,226 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Detector C, "Avoid Lava/Acid Floors" (2026-10-23): a cell is a hazard when a texture in
// HazardTextures.txt is on its walkable FLOOR (a render polygon facing up at least as steeply as
// AC's FloorZ 0.66417), not merely in its surface palette. Before, the palette test flagged cells
// for their walls: Tiny Hive (0x0289) on +Buffy patrolled 2 waypoints, because the learned
// 0x0500279D is the Olthoi hive wall texture (on walls in 3,530 cells of the dats, on a floor in
// none) and 12 cells round the entrance were "hazards". Learning (/ra hazard learnhere) looks at
// floors too, so it can't learn a wall texture again.
//
// Synthetic polygons for the rule; the real Tiny Hive cells when the dat files are on this PC
// (C:\Turbine\Asheron's Call, as DungeonMapBakeTests and FloodPerfTests). The texture set lives in
// the scratch folder (Program.Main points DungeonHazardSurfaces there).
internal static class HazardFloorTests
{
private const string AcDir = @"C:\Turbine\Asheron's Call";
public static void Register(Runner r)
{
r.Add("hazard floors: a polygon facing up at FloorZ or more is floor; walls, ceilings, steep slopes are not", WalkableFloor);
r.Add("hazard floors: a cell's floor surfaces are its floor polygons', not its walls', ceiling's or portals'", FloorSurfaces);
r.Add("hazard floors: a hazard texture on a cell's wall doesn't make it a hazard; on its floor it does", WallVersusFloor);
r.Add("hazard floors: learnhere takes a rare floor texture, never a wall texture", LearnIgnoresWalls);
r.Add("hazard floors: Tiny Hive 0x0289 on the real dats - the wall texture flags nothing, the floor texture its floors", TinyHiveRealDats);
}
// ── Synthetic geometry ──────────────────────────────────────────────────
private static Vector3 V(float x, float y, float z) => new Vector3(x, y, z);
// A 2 x 2 square at height z, counter-clockwise seen from above: faces up.
private static Vector3[] FloorSquare(float z = 0) => new[] { V(0, 0, z), V(2, 0, z), V(2, 2, z), V(0, 2, z) };
// The same square wound the other way: faces down (a ceiling).
private static Vector3[] CeilingSquare(float z = 3) => FloorSquare(z).Reverse().ToArray();
// Upright, facing -y.
private static Vector3[] WallSquare() => new[] { V(0, 0, 0), V(0, 0, 3), V(2, 0, 3), V(2, 0, 0) };
// A ramp rising along +x at the given angle from horizontal, facing up.
private static Vector3[] Ramp(double degrees)
{
float rise = (float)(2 * Math.Tan(degrees * Math.PI / 180));
return new[] { V(0, 0, 0), V(2, 0, rise), V(2, 2, rise), V(0, 2, 0) };
}
private static (IReadOnlyList<Vector3> Verts, short PosSurface, bool IsPortal) P(Vector3[] v, short surf, bool portal = false) => (v, surf, portal);
private static void WalkableFloor()
{
Check.True(DungeonLOS.IsWalkableFloor(FloorSquare()), "flat floor");
Check.False(DungeonLOS.IsWalkableFloor(CeilingSquare()), "ceiling (faces down)");
Check.False(DungeonLOS.IsWalkableFloor(WallSquare()), "upright wall");
Check.True(DungeonLOS.IsWalkableFloor(Ramp(30)), "30 degree ramp (nz 0.87, Tiny Hive's bowl floors are 0.81-0.86)");
Check.True(DungeonLOS.IsWalkableFloor(Ramp(45)), "45 degree ramp (nz 0.71)");
Check.False(DungeonLOS.IsWalkableFloor(Ramp(50)), "50 degree slope (nz 0.64, steeper than FloorZ)");
Check.False(DungeonLOS.IsWalkableFloor(new[] { V(0, 0, 0), V(1, 1, 0) }), "two points");
Check.False(DungeonLOS.IsWalkableFloor(new[] { V(0, 0, 0), V(1, 1, 0), V(2, 2, 0) }), "collinear");
Check.Near(DungeonLOS.FloorZ, 0.66417, 1e-5, "FloorZ is AC's PhysicsGlobals.FloorZ");
}
// Palette: 0 = wall surface, 1 = floor surface, 2 = ceiling surface, 3 = portal surface, 4 = unused.
private const ushort SWall = 0x04C7, SFloor = 0x0112, SCeil = 0x0113, SPortal = 0x0034, SUnused = 0x04C6;
private static readonly ushort[] Palette = { SWall, SFloor, SCeil, SPortal, SUnused };
private static void FloorSurfaces()
{
var polys = new[]
{
P(WallSquare(), 0), P(WallSquare(), 0),
P(FloorSquare(), 1), P(Ramp(30), 1),
P(CeilingSquare(), 2),
P(FloorSquare(), 3, portal: true), // a floor-level portal (a shaft) is an opening
P(FloorSquare(), -1), // no front surface
P(FloorSquare(), 9), // index past the palette
};
var floor = DungeonLOS.FloorSurfaceIds(Palette, polys);
Check.Eq(string.Join(",", floor.Select(s => s.ToString("X4"))), SFloor.ToString("X4"), "only the floor's surface");
// A cap cell: ceiling and portals only - no floor surfaces at all.
Check.Eq(DungeonLOS.FloorSurfaceIds(Palette, new[] { P(CeilingSquare(), 2), P(FloorSquare(), 3, portal: true) }).Count, 0, "ceiling-only cell has no floor");
Check.Eq(DungeonLOS.FloorSurfaceIds(null!, polys).Count, 0, "no palette");
}
// Surface -> texture as portal.dat would resolve it.
private const uint TLava = 0x0500AAA1, TStone = 0x0500AAA2, TWallRare = 0x0500AAA3, TCeil = 0x0500AAA4;
private static HashSet<uint> Textures(ushort[] palette, (IReadOnlyList<Vector3>, short, bool)[] polys, Dictionary<ushort, uint> surfTex)
=> DungeonLOS.FloorSurfaceIds(palette, polys).Select(s => surfTex[s]).ToHashSet();
private static void ResetSet()
{
DungeonHazardSurfaces.Reload();
foreach (uint t in DungeonHazardSurfaces.ListHazardTextures()) DungeonHazardSurfaces.RemoveHazardTexture(t);
}
private static void WallVersusFloor()
{
Check.True(DungeonHazardSurfaces.Folder.StartsWith(Program.TempRoot, StringComparison.OrdinalIgnoreCase), "texture set is in the scratch folder: " + DungeonHazardSurfaces.Folder);
ResetSet();
try
{
const ushort SHz = 0x0700, SStone = 0x0701;
var surfTex = new Dictionary<ushort, uint> { [SHz] = TLava, [SStone] = TStone };
ushort[] pal = { SHz, SStone };
var floors = new Dictionary<uint, HashSet<uint>>
{
// A: hazard texture on the walls, stone floor.
[0xA] = Textures(pal, new[] { P(WallSquare(), 0), P(FloorSquare(), 1) }, surfTex),
// B: stone walls, hazard texture on the floor.
[0xB] = Textures(pal, new[] { P(WallSquare(), 1), P(FloorSquare(), 0) }, surfTex),
// C: hazard texture in the palette and on the ceiling only.
[0xC] = Textures(pal, new[] { P(CeilingSquare(), 0), P(FloorSquare(), 1) }, surfTex),
// D: part of the floor is the hazard texture (a pool in a stone room).
[0xD] = Textures(pal, new[] { P(FloorSquare(), 1), P(FloorSquare(), 0) }, surfTex),
};
Check.True(DungeonHazardSurfaces.AddHazardTexture(TLava), "flag the texture");
Check.True(File.Exists(Path.Combine(Program.TempRoot, "HazardTextures", "HazardTextures.txt")), "persisted to the scratch folder");
var hz = DungeonHazardSurfaces.HazardCellsFrom(floors);
Check.False(hz.Contains(0xA), "wall uses the hazard texture: not a hazard");
Check.True(hz.Contains(0xB), "floor uses the hazard texture: hazard");
Check.False(hz.Contains(0xC), "ceiling uses the hazard texture: not a hazard");
Check.True(hz.Contains(0xD), "part of the floor uses it: hazard");
Check.Eq(hz.Count, 2, "two hazard cells");
}
finally { ResetSet(); }
}
private static void LearnIgnoresWalls()
{
ResetSet();
try
{
const ushort SStone = 0x0701, SWallRare = 0x0702, SLava = 0x0703, SCeilS = 0x0704;
var surfTex = new Dictionary<ushort, uint> { [SStone] = TStone, [SWallRare] = TWallRare, [SLava] = TLava, [SCeilS] = TCeil };
ushort[] pal = { SStone, SWallRare, SLava, SCeilS };
var floors = new Dictionary<uint, HashSet<uint>>();
// 20 ordinary rooms: stone floor and walls, ceiling texture overhead.
for (uint c = 0x100; c < 0x114; c++)
floors[c] = Textures(pal, new[] { P(FloorSquare(), 0), P(WallSquare(), 0), P(CeilingSquare(), 3) }, surfTex);
// A room with a rare WALL texture (only this cell has it) and the common stone floor.
const uint RareWallRoom = 0x200;
floors[RareWallRoom] = Textures(pal, new[] { P(FloorSquare(), 0), P(WallSquare(), 1) }, surfTex);
// A lava room: lava floor, stone walls.
const uint LavaRoom = 0x201;
floors[LavaRoom] = Textures(pal, new[] { P(FloorSquare(), 2), P(WallSquare(), 0) }, surfTex);
Check.Eq(DungeonHazardSurfaces.RareFloorTextures(RareWallRoom, floors, 0.25).Count, 0, "rare wall texture is not learned (its floor is common stone)");
var lava = DungeonHazardSurfaces.RareFloorTextures(LavaRoom, floors, 0.25);
Check.Eq(string.Join(",", lava.Select(t => t.ToString("X8"))), TLava.ToString("X8"), "the lava room's floor texture is learned");
Check.Eq(DungeonHazardSurfaces.RareFloorTextures(0x100, floors, 0.25).Count, 0, "a common floor is never learned");
Check.Eq(DungeonHazardSurfaces.RareFloorTextures(0x999, floors, 0.25).Count, 0, "a cell without floor data learns nothing");
Check.False(floors.Values.Any(s => s.Contains(TWallRare) || s.Contains(TCeil)), "wall and ceiling textures never reach the floor map");
}
finally { ResetSet(); }
}
// ── The real dats ───────────────────────────────────────────────────────
private static GeometryLoader? _geo;
private static bool _geoTried;
private static GeometryLoader? Geo()
{
if (!_geoTried)
{
_geoTried = true;
if (Directory.Exists(AcDir))
{
var g = new GeometryLoader();
if (g.Initialize(AcDir)) _geo = g;
else Console.WriteLine(" geometry loader failed: " + g.StatusMessage);
}
}
return _geo;
}
private const uint TinyHive = 0x0289;
private const uint HiveFloor = 0x0500279C, HiveWall = 0x0500279D; // the two ids in the live HazardTextures.txt
private static string Ids(IEnumerable<uint> cells) => string.Join(",", cells.OrderBy(c => c).Select(c => (c & 0xFFFF).ToString("X4")));
private static void TinyHiveRealDats()
{
var geo = Geo();
if (geo?.DungeonLOS is null || geo.PortalDat is null) { Console.WriteLine(" skipped: no dats at " + AcDir); return; }
var los = geo.DungeonLOS;
ResetSet();
try
{
var floors = DungeonHazardSurfaces.GetFloorTextures(TinyHive, los, geo.PortalDat);
Check.True(floors.Count > 300, $"floor textures for most of Tiny Hive's 450 cells ({floors.Count})");
Check.False(floors.Values.Any(s => s.Contains(HiveWall)), "0x0500279D is on no floor in Tiny Hive");
// The wall texture alone flags nothing (before: 02A2-02B0, the 12 cells round the entrance).
DungeonHazardSurfaces.AddHazardTexture(HiveWall);
var wallOnly = DungeonHazardSurfaces.ComputeHazardCells(TinyHive, los, geo.PortalDat);
Console.WriteLine($" 0x0500279D flagged: {wallOnly.Count} cells {Ids(wallOnly)}");
Check.Eq(wallOnly.Count, 0, "wall texture flags no cell");
// The floor texture flags the cells it's the floor of: 02A6 (walls only), 02A8 and
// 02A9 (in the palette, on no polygon / a different floor) are not among them.
DungeonHazardSurfaces.AddHazardTexture(HiveFloor);
var floorCells = DungeonHazardSurfaces.ComputeHazardCells(TinyHive, los, geo.PortalDat);
Console.WriteLine($" + 0x0500279C flagged: {floorCells.Count} cells {Ids(floorCells)}");
Check.Eq(Ids(floorCells), "02A2,02A3,02A4,02A7,02AA,02AB,02AE,02AF,02B0", "exactly the cells whose floor is 0x0500279C");
Check.False(floorCells.Contains(0x028902A5), "the entrance cell 02A5 is not a hazard");
// Learning standing in 02A6 (hive wall texture on its walls, common floor 0x05002627)
// takes nothing; before, the palette rule offered both 0x0500279C and 0x0500279D.
ResetSet();
var learned = DungeonHazardSurfaces.LearnFromCell(0x028902A6, los, geo.PortalDat);
Check.Eq(learned.Count, 0, "learnhere in 02A6 learns nothing: " + string.Join(",", learned.Select(t => t.ToString("X8"))));
Check.Eq(DungeonHazardSurfaces.HazardTextureCount, 0, "and the set stays empty");
}
finally { ResetSet(); }
}
}

View file

@ -118,6 +118,7 @@ internal static class InstallPathsTests
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");
Check.Eq(Program.LiveHazardTextureFolder, @"C:\Games\RynthSuite\RynthAi", "hazard floor textures (HazardTextures.txt)");
Check.Eq(Program.LiveCreatureFolder, @"C:\Games\RynthSuite\RynthAi\CreatureData", "creature data");
}

View file

@ -53,6 +53,8 @@ internal static class LootCorpseTests
r.Add("boost loot: the wait ends after BoostLootKillWaitMs, for a close monster, and with Boost Loot off", BoostLootHoldLimits);
r.Add("boost loot: looting the kill's corpse ends the wait; an older corpse does not", BoostLootWaitEndsOnKillCorpse);
r.Add("monster ignore: a close Priority 0 monster neither holds combat nor starves the corpse", IgnoredMonsterDoesNotHoldLoot);
r.Add("loot gate (R-20261025 727b): a predicted kill still alive holds the corpse; after its window combat has it again", PredictedKillHoldsCorpse);
r.Add("loot gate (R-20261025 727b): the kill notice, health 0 or a hit after the swap settle a predicted kill at once", PredictedKillSettled);
r.Add("corpse close: a finished corpse is closed once (CloseContainer, API v76)", FinishedCorpseClosedOnce);
r.Add("corpse close: an engine without CloseContainer leaves it to the next open (no close)", FinishedCorpseNotClosedOnOldEngine);
r.Add("corpse close: an abandoned open corpse is closed once", AbandonedCorpseClosed);
@ -400,6 +402,96 @@ internal static class LootCorpseTests
Check.Eq(ActivityArbiter.Decide(in inputs), BotActivity.Looting, "so looting has the tick without needing a starved turn");
}
// ── A predicted kill that is still alive (report R-20261025-183343-727b, Conquest) ─────────
// The bot swapped off a Curator of Torment as a predicted kill (34% health left), the Rynthid it
// locked next died at once, and with the Curator kept out of the scan HasTargets went false:
// "Corpse loot: claimed corpse target", 4.6 s of looting with the live Curator 1.9 m away.
/// <summary>The Water Elemental 2 m away fought, then swapped off as a predicted kill (dropped,
/// out of the scan), with combat's target clock at <paramref name="now"/>.</summary>
private static Bot PredictedKillWorld(out CombatManager combat, Func<DateTime> now)
{
var bot = StarvationWorld(2f, out combat);
FakeHost.Wcids[Monster] = 40030;
combat.TargetClock = now;
combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
combat.EngageForTest(unchecked((int)Monster));
combat.CastAndPredictForTest(0x8008AB76, "Fire", 8); // one cast at it (the kill notice credits it)
combat.PredictedSwapForTest();
Rescan(combat);
return bot;
}
private static void Rescan(CombatManager combat)
{
typeof(CombatManager).GetField("_lastScanTime", Any)?.SetValue(combat, DateTime.MinValue);
combat.ScanNearbyTargets();
}
private static void PredictedKillHoldsCorpse()
{
DateTime now = new(2026, 10, 25, 19, 32, 58);
var bot = PredictedKillWorld(out var combat, () => now);
int mob = unchecked((int)Monster);
Check.Eq(combat.activeTargetId, 0, "the swap dropped it");
Check.False(combat.ScannedTargets.Any(t => t.Id == mob), "and the scan is kept off it (its death animation)");
Check.True(combat.HasTargets, "but it still counts as a target in range (corpse gates, nav hold)");
Check.True(combat.HasCloseThreat(RynthAiPlugin.LootStarveCloseYards), "and as a close threat (no starved loot turn)");
Check.True(combat.HasEngageableTarget, "so combat keeps the tick");
Check.True(bot.HasLootWork(), "the corpse is lootable");
bot.Tick(BotActivity.Combat);
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "no corpse claimed while combat holds the tick");
Check.True(FakeHost.Logs.Any(l => l.Contains($"corpse 0x{Corpse:X8} waits for combat")), "the corpse waits for combat, and says so");
bot.Tick(BotActivity.Looting);
Check.Eq(bot.Get<int>("_targetCorpseId"), 0, "nor with the Looting tick (the claim gate holds too)");
Check.False(FakeHost.Uses.Contains(Corpse), "the corpse is not opened");
AgeCorpse(bot, RynthAiPlugin.LootStarveMs + 1000);
bot.HasLootWork();
Check.False((bool)bot.Call("IsLootStarvedTurn", true, true)!, "a long-waiting corpse gets no starved turn past it either");
// Its window passes with no word of its death: it is a target again at once.
now = now.AddSeconds(2.1);
Rescan(combat);
Check.True(combat.ScannedTargets.Any(t => t.Id == mob), "after the window it is scanned again");
Check.True(FakeHost.Logs.Any(l => l.Contains("not confirmed 2.1 s after the swap and it is still alive: it is a target again")),
"said once the window ends");
combat.HandleCombatTrigger();
Check.Eq(combat.activeTargetId, mob, "and combat locks it again");
}
private static void PredictedKillSettled()
{
DateTime now = new(2026, 10, 25, 19, 32, 58);
int mob = unchecked((int)Monster);
// The kill notice confirms it: the corpse may be looted.
var bot = PredictedKillWorld(out var combat, () => now);
combat.OnKillNotification("You killed the Ancient Water Elemental!");
Check.False(combat.HasTargets, "kill notice: dead, nothing in range");
Check.False(combat.HasEngageableTarget, "combat lets the tick go");
Check.True(combat.IsKillSuppressed(mob), "the scan stays off it while its corpse forms");
bot.HasLootWork();
bot.Tick(BotActivity.Looting);
Check.Eq(bot.Get<int>("_targetCorpseId"), unchecked((int)Corpse), "the corpse is claimed");
// Health 0 from the server: dead too.
bot = PredictedKillWorld(out combat, () => now);
Check.True(combat.HasTargets, "pending");
bot.Cache.OnUpdateHealth(Monster, 0f); // the bot's cache is combat's world filter
Check.False(combat.HasTargets, "health 0: dead, nothing in range");
// A damage line on it after the swap (a killing blow sends none): alive, back in the scan now.
PredictedKillWorld(out combat, () => now);
combat.HandleChatForDamage("You singe Ancient Water Elemental for 7883 points with Incantation of Flame Bolt.", 7);
Check.False(combat.IsKillSuppressed(mob), "the hit lifts the suppression");
Check.True(FakeHost.Logs.Any(l => l.Contains("took a 7883-point hit after the swap")), "and says so");
Rescan(combat);
Check.True(combat.ScannedTargets.Any(t => t.Id == mob), "scanned again before the window ends");
combat.HandleCombatTrigger();
Check.Eq(combat.activeTargetId, mob, "combat goes back to it at once");
}
// ── Boost Loot Priority: one kill, one loot (2026-10-14, Kelpie: the next target was locked
// 6 ms after each kill, the corpse came 3 s later, and corpses were looted in batches) ──

View file

@ -26,6 +26,8 @@ internal static class ManaStoneChoiceTests
r.Add("mana charges: used up, the next charge of that name is found (retail: each use destroys one)", NextChargeFoundByName);
r.Add("mana charges: never taken for the empty stone to drain loot into", ChargeIsNeverEmptyStone);
r.Add("mana charges: refill gear even when ManaStone rules name only other stones", ChargesIgnoreStoneRules);
r.Add("mana stones (Drakkon 10-23): a mana kit typed ManaStone in Items is no stone rule: the ordinary stones still refill gear", KitIsNoStoneRule);
r.Add("mana tapping (Drakkon 10-24): mana kits are no empty stones: nothing looted for them; the item goes into the real stone", KitsAreNoEmptyStones);
r.Add("mana stones: the server's 'low on Mana' refills gear whose read is stale-high", ServerLowRefills);
r.Add("mana stones: worn gear is identified again, so a stale-high read follows the gear", GearReadRefreshed);
r.Add("mana stones: worn means worn per the tracker - a packed item with a stale wield record takes no appraisals, gear it says is worn gets refilled", WornPerTracker);
@ -124,6 +126,39 @@ internal static class ManaStoneChoiceTests
Check.True(m.IsRefillStone(W("Tiny Mana Charge")), "tapping off too");
}
// Drakkon 10-23: "Greater Mana Kit" (a kit for his own mana) was in Items typed ManaStone. As the only stone
// rule it switched the ordinary stones off: his Greater and Major Mana Stones were never used, his shirt ran
// dry, and RynthAi tried to drain his necklace into the kit ("Cannot use the Greater Mana Kit with the Necklace").
private static void KitIsNoStoneRule()
{
FakeHost.Reset();
var host = FakeHost.Create();
var cache = new WorldObjectCache(host);
var s = new LegacyUiSettings { EnableManaTapping = true };
s.ConsumableRules.Add(new ConsumableRule { Name = "Greater Mana Kit", Type = "ManaStone" });
var m = new ManaStoneManager(host, s, cache);
WorldObject W(string name, AcObjectClass cls = AcObjectClass.ManaStone) => new(0x60001000, name, cls);
Check.True(m.IsManaStone(W("Greater Mana Stone")) && m.IsManaStone(W("Major Mana Stone")), "the ordinary stones count again");
Check.True(m.IsRefillStone(W("Major Mana Stone")), "and refill worn gear");
Check.False(m.IsManaStone(W("Greater Mana Kit", AcObjectClass.HealingKit)), "the kit is no stone (nothing drained into it)");
Check.True(FakeHost.Logs.Count(l => l.Contains("'Greater Mana Kit' is in Items as a mana stone but is a kit")) == 1, "said once");
s.EnableManaTapping = false;
Check.True(m.IsRefillStone(W("Greater Mana Stone")), "tapping off: still refills gear");
// A real stone named in Items still means "only the named ones".
s.EnableManaTapping = true;
s.ConsumableRules.Add(new ConsumableRule { Name = "Major Mana Stone", Type = "ManaStone" });
Check.True(m.IsManaStone(W("Major Mana Stone")), "the named stone");
Check.False(m.IsManaStone(W("Greater Mana Stone")), "not the unnamed one");
// Adding one to Items types it ManaKit now, and a kit in the pack is no healing kit.
var detect = typeof(LegacyWeaponsUi).GetMethod("DetectConsumableType", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)!;
Check.Eq((string)detect.Invoke(null, new object[] { W("Greater Mana Kit", AcObjectClass.HealingKit) })!, "ManaKit", "Items types a mana kit ManaKit");
Check.Eq((string)detect.Invoke(null, new object[] { W("Greater Mana Stone") })!, "ManaStone", "and a stone ManaStone");
Check.Eq(LegacyWeaponsUi.PackConsumableType(W("Greater Mana Kit", AcObjectClass.HealingKit)), "ManaKit", "a mana kit in the pack is not a healing kit");
Check.Eq(LegacyWeaponsUi.PackConsumableType(W("Treated Healing Kit", AcObjectClass.HealingKit)), "HealthKit", "a healing kit still is");
}
private static void ServerLowRefills()
{
// The mace was identified at 90% and reads that forever (the fake never updates it).
@ -384,6 +419,32 @@ internal static class ManaStoneChoiceTests
Check.Eq(rig.OnPlayer[0], StoneA, "stone A");
}
// Drakkon 10-23/24: with "Greater Mana Kit" typed ManaStone, his 5 kits were empty stones to RynthAi. It looted
// an item for each, every drain into a kit was refused, it gave up after 3 and looted the next: a hundred items.
// Tom: the stone first, then one item for it, drained, and the next only with another empty stone.
private static void KitsAreNoEmptyStones()
{
const uint KitA = 0x80400031, KitB = 0x80400032;
void Kits(List<uint> ids)
{
foreach (uint k in new[] { KitA, KitB }) { FakeHost.Names[k] = "Greater Mana Kit"; FakeHost.Containers[k] = Player; ids.Add(k); }
}
using (var rig = new Rig(tapping: true, Array.Empty<(uint, int?)>(), maceMana: 5000, before: Kits))
{
rig.S.ConsumableRules.Add(new ConsumableRule { Name = "Greater Mana Kit", Type = "ManaStone" });
Check.Eq(rig.M.CountEmptyStones(), 0, "kits only: no empty stone");
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "so no item is looted to tap");
}
using (var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null) }, ringToDrain: true, stoneName: "Major Mana Stone", maceMana: 5000, before: Kits))
{
rig.S.ConsumableRules.Add(new ConsumableRule { Name = "Greater Mana Kit", Type = "ManaStone" });
Check.Eq(rig.M.CountEmptyStones(), 1, "one empty Major Mana Stone (the kits don't count)");
rig.Run(1600);
Check.True(rig.OnRing.Count == 1 && rig.OnRing[0] == StoneA, $"the ring is drained into the stone, never a kit ({string.Join(",", rig.OnRing.Select(x => $"0x{x:X8}"))})");
Check.Eq(rig.M.FreeEmptyStoneSlots(), 0, "and no second item while that drain is out");
}
}
private static void OneTapItemAtATime()
{
using var rig = new Rig(tapping: true, new (uint, int?)[] { (StoneA, null), (StoneB, null), (StoneC, null) }, maceMana: 5000);

View file

@ -0,0 +1,471 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
using V3 = RynthCore.Plugin.RynthAi.Raycasting.Vector3;
namespace RynthCore.RynthAiHostTests.Tests;
// The Dungeon Patrol keeps out of portals (DungeonPathfinder.Portals.cs, 2026-10-23). Tom, Tiny Hive
// (0x0289): with coverage Everything the patrol "takes me right into the portal": waypoint 1 was the
// exit point 1.2 m into the dead-end nook 028902BA, 0.02 m from the Surface Portal, and a client that
// began its lap there was teleported out. On small hand-built dungeons (world metres, floors at z 0,
// as in PatrolDoorwayTests):
// - a patrol across a room with a portal in it: every point and leg stays outside the circle, the
// crossing bends round it, and every doorway is still walked through;
// - a portal at the back of a dead-end nook (Tiny Hive's layout): the nook's doorway is closed, the
// patrol turns round in the corridor before it (without the portal a point was on it); the cell
// walk without map geometry keeps out too;
// - a start next to a portal: the character walks straight away from it first, then round it to the
// first point; a portal across the start's corridor leaves the patrol the side the character is on;
// - a portal on another level changes nothing;
// - Tiny Hive itself on the real dats (when they are on this PC);
// - the plugin: the client's portal objects in the dungeon are the circles, and one that comes into
// view after the build makes the running patrol rebuild.
internal static class PatrolPortalTests
{
public static void Register(Runner r)
{
r.Add("patrol portals: a patrol through a room with a portal keeps its points and legs outside the circle, doorways all walked", RoomWithPortal);
r.Add("patrol portals: a portal in a dead end (Tiny Hive's nook) is turned round before; it used to get a point on it", DeadEndTurnedRoundBefore);
r.Add("patrol portals: without the map geometry (cell walk) the patrol keeps out too", CellWalkKeepsOut);
r.Add("patrol portals: a start next to a portal walks straight away from it first, then round it", StartNextToPortalWalksAway);
r.Add("patrol portals: a portal across the start's corridor leaves the patrol the side the character is on", PortalSplitsStartCorridor);
r.Add("patrol portals: a portal on another level changes nothing", OtherLevelIgnored);
r.Add("patrol portals: Tiny Hive 0x0289 on the real dats keeps out of the Surface Portal (if the dats are here)", TinyHiveRealDats);
r.Add("patrol portals: the client's portals in the dungeon are the circles; one coming into view rebuilds the patrol", PluginCollectsPortals);
}
// ── Fixture builder ──────────────────────────────────────────────────────
private sealed class Dungeon
{
public readonly Dictionary<uint, DungeonNavNode> Graph = new();
public readonly List<(uint, V3[])> Portals = new();
public readonly List<(uint, V3[])> Floors = new();
public readonly List<(uint, V3[])> Walls = new();
private uint _next = 0x7E7E0100;
/// <summary>A cell whose floor is the rectangle (x0,y0)-(x1,y1) at height z; its origin is the middle.</summary>
public uint Cell(double x0, double y0, double x1, double y1, double z = 0)
{
uint id = _next++;
Graph[id] = new DungeonNavNode
{
CellId = id,
EW = DungeonGeometry.WorldToNav((x0 + x1) / 2),
NS = DungeonGeometry.WorldToNav((y0 + y1) / 2),
Z = (float)z,
};
Floors.Add((id, Rect(x0, y0, x1, y1, z)));
return id;
}
public void OpenX(uint a, uint b, double x, double y0, double y1) => Open(a, b, Quad(x, y0, x, y1));
public void OpenY(uint a, uint b, double y, double x0, double x1) => Open(a, b, Quad(x0, y, x1, y));
private void Open(uint a, uint b, V3[] quad)
{
Graph[a].Neighbors.Add(b);
Graph[b].Neighbors.Add(a);
Portals.Add((a, quad));
Portals.Add((b, quad.Reverse().ToArray()));
}
public DungeonGeometry Geo() => DungeonGeometry.Build(Graph, Portals, Floors, Walls);
}
private static V3[] Rect(double x0, double y0, double x1, double y1, double z) => new[]
{
new V3((float)x0, (float)y0, (float)z), new V3((float)x1, (float)y0, (float)z),
new V3((float)x1, (float)y1, (float)z), new V3((float)x0, (float)y1, (float)z),
};
private static V3[] Quad(double x0, double y0, double x1, double y1) => new[]
{
new V3((float)x0, (float)y0, 0f), new V3((float)x1, (float)y1, 0f),
new V3((float)x1, (float)y1, 3f), new V3((float)x0, (float)y0, 3f),
};
private static double X(NavPoint p) => DungeonGeometry.NavToWorld(p.EW);
private static double Y(NavPoint p) => DungeonGeometry.NavToWorld(p.NS);
private static NavPoint At(double x, double y, double z = 0) => new()
{
Type = NavPointType.Point, EW = DungeonGeometry.WorldToNav(x), NS = DungeonGeometry.WorldToNav(y), Z = z / 240.0,
};
private static PatrolPortal Portal(double x, double y, double z = 0, double r = DungeonPathfinder.PortalKeepOutDefault)
=> new() { Id = 0x7E7E9001, Name = "Test Portal", X = x, Y = y, Z = z, Radius = r };
private static string Pts(List<NavPoint> pts) => string.Join(" ", pts.Select(p => $"({X(p):F1},{Y(p):F1})"));
private static double SegDist(double px, double py, double ax, double ay, double bx, double by)
{
double dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
double t = l2 < 1e-12 ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / l2, 0, 1);
double cx = ax + dx * t - px, cy = ay + dy * t - py;
return Math.Sqrt(cx * cx + cy * cy);
}
// The nearest any point, and any leg of the loop, comes to (px, py): checked here independently of
// the code under test.
private static (double Point, double Leg) Nearest(List<NavPoint> pts, double px, double py, bool closed = true)
{
double point = double.MaxValue, leg = double.MaxValue;
for (int i = 0; i < pts.Count; i++)
{
point = Math.Min(point, Math.Sqrt((X(pts[i]) - px) * (X(pts[i]) - px) + (Y(pts[i]) - py) * (Y(pts[i]) - py)));
if (i + 1 < pts.Count || (closed && pts.Count > 1))
{
var b = pts[(i + 1) % pts.Count];
leg = Math.Min(leg, SegDist(px, py, X(pts[i]), Y(pts[i]), X(b), Y(b)));
}
}
return (point, leg);
}
private static void KeptOut(NavRouteParser route, PatrolPortal p, string what)
{
var (point, leg) = Nearest(route.Points, p.X, p.Y);
Check.True(route.Points.Count >= 2, $"{what}: a patrol ({route.Points.Count} points)");
Check.True(point >= p.Radius - 0.02, $"{what}: every point {p.Radius} m or more from the portal (nearest {point:F2} m): {Pts(route.Points)}");
Check.True(leg >= p.Radius - 0.02, $"{what}: every leg {p.Radius} m or more from the portal (nearest {leg:F2} m)");
}
// ── A room with a portal in it ───────────────────────────────────────────
// PatrolDoorwayTests' loop dungeon: a 3x3 room of 10 m cells (x 0..30, y 0..30, wide openings
// inside) entered by a doorway on its west side (y 25) and left by one on its east side (y 5),
// and a corridor loop round its north back to the west corridor. The crossing from door to door
// runs straight through the room's middle.
private static (Dungeon D, uint West) LoopDungeon()
{
var d = new Dungeon();
var c = new uint[3, 3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
c[i, j] = d.Cell(i * 10, j * 10, i * 10 + 10, j * 10 + 10);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
if (i < 2) d.OpenX(c[i, j], c[i + 1, j], i * 10 + 10, j * 10, j * 10 + 10);
if (j < 2) d.OpenY(c[i, j], c[i, j + 1], j * 10 + 10, i * 10, i * 10 + 10);
}
uint west = d.Cell(-10, 22.35, 0, 27.65);
uint east = d.Cell(30, 2.35, 40, 7.65);
d.OpenX(west, c[0, 2], 0, 22.35, 27.65);
d.OpenX(c[2, 0], east, 30, 2.35, 7.65);
uint up1 = d.Cell(-10, 27.65, -4.7, 37.65);
d.OpenY(west, up1, 27.65, -10, -4.7);
uint top1 = d.Cell(-10, 37.65, 10, 42.95);
d.OpenY(up1, top1, 37.65, -10, -4.7);
uint top2 = d.Cell(10, 37.65, 30, 42.95);
d.OpenX(top1, top2, 10, 37.65, 42.95);
uint top3 = d.Cell(30, 37.65, 45.3, 42.95);
d.OpenX(top2, top3, 30, 37.65, 42.95);
uint down1 = d.Cell(40, 7.65, 45.3, 37.65);
d.OpenY(down1, top3, 37.65, 40, 45.3);
uint corner = d.Cell(40, 2.35, 45.3, 7.65);
d.OpenY(corner, down1, 7.65, 40, 45.3);
d.OpenX(east, corner, 40, 2.35, 7.65);
return (d, west);
}
private static void RoomWithPortal()
{
var (d, west) = LoopDungeon();
var geo = d.Geo();
var p = Portal(15, 15);
var before = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo);
Check.True(Nearest(before.Points, p.X, p.Y).Leg < 1.0, $"without the portal the crossing runs through the room's middle ({Nearest(before.Points, p.X, p.Y).Leg:F2} m)");
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, null, new[] { p });
KeptOut(route, p, "portal in the room");
var report = DungeonPathfinder.LastPortalAvoidance;
Check.True(report != null && report.Count == 1, "one line for the one portal");
Check.True(report![0].Bent >= 1, $"the crossing is bent round it ({report[0].Describe()})");
Check.True(report[0].Closed.Count == 0 && report[0].CutCells.Count == 0, "nothing closed: the room is wide enough to go round");
Check.True(report[0].Clear, "the report says clear: " + report[0].Describe());
// Every doorway (narrow opening) still passed through near its centre.
foreach (var (a, b) in d.Graph.Values.SelectMany(n => n.Neighbors.Select(m => (n.CellId, m))).Where(e => e.CellId < e.m))
{
if (!geo.TryGetDoorway(a, b, out var door) || door.IsWide) continue;
double best = double.MaxValue;
for (int i = 0; i < route.Points.Count; i++)
{
var q = route.Points[i]; var s = route.Points[(i + 1) % route.Points.Count];
best = Math.Min(best, SegDist(door.X, door.Y, X(q), Y(q), X(s), Y(s)));
}
Check.True(best < 0.3, $"still through the opening at ({door.X:F1}, {door.Y:F1}) ({best:F2} m off its centre)");
}
// The corners round it are on the room's floor.
foreach (var q in route.Points)
Check.True(geo.OnWalkableFloor(X(q), Y(q), q.Z * 240.0), $"({X(q):F1}, {Y(q):F1}) is on walkable floor");
// A bigger keep-out (a longer nav point reach) keeps further out.
var far = Portal(15, 15, 0, DungeonPathfinder.PortalKeepOutRadius(3.0));
Check.Near(far.Radius, 5.0, 1e-9, "reach 3 yd: keep-out 1.9 + 3.1 m");
KeptOut(DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, null, new[] { far }), far, "a 6 m keep-out");
}
// ── A portal at the back of a dead-end nook (Tiny Hive) ──────────────────
// A 3x3 room of 10 m cells (x 0..30, y -30..0); north of its middle the start cell, a corridor piece
// 5.3 m wide (y 0..10, Tiny Hive's 028902A5), then another (y 10..20, the ramp 028902BB) and a nook
// 4 m deep (y 20..24, 028902BA) with the portal 1.5 m in.
private static (Dungeon D, uint Start, uint Corridor, uint Nook, PatrolPortal P) NookDungeon()
{
var d = new Dungeon();
var c = new uint[3, 3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
c[i, j] = d.Cell(i * 10, -30 + j * 10, i * 10 + 10, -20 + j * 10);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
if (i < 2) d.OpenX(c[i, j], c[i + 1, j], i * 10 + 10, -30 + j * 10, -20 + j * 10);
if (j < 2) d.OpenY(c[i, j], c[i, j + 1], -20 + j * 10, i * 10, i * 10 + 10);
}
uint start = d.Cell(12.35, 0, 17.65, 10);
uint corridor = d.Cell(12.35, 10, 17.65, 20);
uint nook = d.Cell(12.35, 20, 17.65, 24);
d.OpenY(c[1, 2], start, 0, 12.35, 17.65);
d.OpenY(start, corridor, 10, 12.35, 17.65);
d.OpenY(corridor, nook, 20, 12.35, 17.65);
return (d, start, corridor, nook, Portal(15, 21.5));
}
private static readonly DungeonPatrolOptions Everything = new() { Coverage = PatrolCoverage.Everything, LookInRoomMeters = 20 };
private static void DeadEndTurnedRoundBefore()
{
var (d, start, corridor, nook, p) = NookDungeon();
var geo = d.Geo();
var before = DungeonPathfinder.BuildPatrolRoute(d.Graph, start, null, geo, Everything);
Check.True(Nearest(before.Points, p.X, p.Y).Point < DungeonPathfinder.PortalTouchMeters,
$"without the portal a point is within touching distance of it ({Nearest(before.Points, p.X, p.Y).Point:F2} m): {Pts(before.Points)}");
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, start, null, geo, Everything, new[] { p });
KeptOut(route, p, "portal in the nook");
var r = DungeonPathfinder.LastPortalAvoidance![0];
Check.True(r.Closed.Any(e => (e.A == corridor && e.B == nook) || (e.A == nook && e.B == corridor)),
"the nook's doorway is closed: " + r.Describe());
double north = route.Points.Max(Y);
Check.True(north > 10 && north < p.Y - p.Radius,
$"it turns round in the corridor before the portal (northmost point y {north:F1}; corridor 10..20, portal at {p.Y})");
Check.True(r.Nearest < p.Radius + 4.0, $"close up to it, not a whole cell short ({r.Nearest:F1} m)");
Check.True(route.Points.Any(q => Y(q) < -5), "the room south of the start is still walked");
}
private static void CellWalkKeepsOut()
{
// Without the map geometry (DungeonLOS not up yet) the old cell walk: points 30% / 50% of the
// way between cell centres. A portal 1.5 m past the start's north opening.
var (d, start, corridor, _, _) = NookDungeon();
var p = Portal(15, 11.5);
var before = DungeonPathfinder.BuildPatrolRoute(d.Graph, start, null, null, Everything);
Check.True(Nearest(before.Points, p.X, p.Y).Point < DungeonPathfinder.PortalTouchMeters,
$"the cell walk turned round within touching distance of it ({Nearest(before.Points, p.X, p.Y).Point:F2} m): {Pts(before.Points)}");
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, start, null, null, Everything, new[] { p });
KeptOut(route, p, "cell walk, portal past the start's opening");
var r = DungeonPathfinder.LastPortalAvoidance![0];
Check.True(r.Closed.Contains((start, corridor)) || r.Closed.Contains((corridor, start)), "the opening by it is closed: " + r.Describe());
}
// ── A start next to a portal ─────────────────────────────────────────────
private static void StartNextToPortalWalksAway()
{
// An open room (x 0..20, y 0..20) with doorways west and east (y 10) and a loop round its
// north; the portal in its middle, the character 2 m north of it (inside the circle).
var d = new Dungeon();
uint room = d.Cell(0, 0, 20, 20);
uint w = d.Cell(-10, 7.35, 0, 12.65), e = d.Cell(20, 7.35, 30, 12.65);
d.OpenX(w, room, 0, 7.35, 12.65);
d.OpenX(room, e, 20, 7.35, 12.65);
uint wn = d.Cell(-10, 12.65, -4.7, 30), top = d.Cell(-10, 30, 30, 35.3), en = d.Cell(24.7, 12.65, 30, 30);
d.OpenY(w, wn, 12.65, -10, -4.7);
d.OpenY(wn, top, 30, -10, -4.7);
d.OpenY(en, top, 30, 24.7, 30);
d.OpenY(e, en, 12.65, 24.7, 30);
var geo = d.Geo();
var p = Portal(10, 10);
double px = 10, py = 12;
var portals = new[] { p };
var walk = DungeonPathfinder.PortalWalkOut(geo, portals, px, py, 0, 1.0);
Check.NotNull(walk, "standing inside the circle: a spot to walk out to");
double wd = Math.Sqrt((X(walk!) - p.X) * (X(walk) - p.X) + (Y(walk) - p.Y) * (Y(walk) - p.Y));
Check.True(wd >= p.Radius, $"the spot is outside the circle ({wd:F2} m)");
Check.True((X(walk) - px) * (px - p.X) + (Y(walk) - py) * (py - p.Y) > 0, $"straight away from the portal: ({X(walk):F1}, {Y(walk):F1})");
// The walk there never gets nearer the portal than the character already is.
for (int i = 0; i <= 20; i++)
{
double t = i / 20.0, x = px + (X(walk) - px) * t, y = py + (Y(walk) - py) * t;
Check.True(Math.Sqrt((x - p.X) * (x - p.X) + (y - p.Y) * (y - p.Y)) >= 2.0 - 1e-6, $"walking out, {t:F2} of the way: no nearer the portal");
}
Check.Null(DungeonPathfinder.PortalWalkOut(geo, portals, 3, 3, 0, 1.0), "outside the circle: nothing to walk out of");
// The patrol from there keeps out, and the way from the walk-out spot to a first point on the
// portal's other side (south) goes round it.
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, room, null, geo, null, portals, (X(walk), Y(walk), 0));
KeptOut(route, p, "start next to a portal");
var first = At(10, 3);
var lead = DungeonPathfinder.PortalLeadIn(d.Graph, geo, portals, walk, first, 1.0);
Check.True(lead.Count >= 1, "corners round the portal to the first point");
var way = new List<NavPoint> { walk };
way.AddRange(lead);
way.Add(first);
var (_, leg) = Nearest(way, p.X, p.Y, closed: false);
Check.True(leg >= p.Radius - 0.02, $"the way to the first point keeps out ({leg:F2} m): {Pts(way)}");
Check.True(DungeonPathfinder.PortalLeadIn(d.Graph, geo, portals, At(3, 3), At(3, 17), 1.0).Count == 0, "a clear walk needs no corners");
}
private static void PortalSplitsStartCorridor()
{
// A corridor (x 0..5.3, y 0..20) between a room south (y -10..0) and a room north (y 20..30),
// nothing else joining them; the portal across the corridor's middle.
var d = new Dungeon();
uint south = d.Cell(-5, -10, 10.3, 0), corr = d.Cell(0, 0, 5.3, 20), north = d.Cell(-5, 20, 10.3, 30);
uint sw = d.Cell(-15, -7.65, -5, -2.35), nw = d.Cell(-15, 22.35, -5, 27.65);
d.OpenY(south, corr, 0, 0, 5.3);
d.OpenY(corr, north, 20, 0, 5.3);
d.OpenX(sw, south, -5, -7.65, -2.35);
d.OpenX(nw, north, -5, 22.35, 27.65);
var geo = d.Geo();
var p = Portal(2.65, 10);
var portals = new[] { p };
var n = DungeonPathfinder.BuildPatrolRoute(d.Graph, corr, null, geo, Everything, portals, (2.65, 16, 0));
KeptOut(n, p, "character north of the portal");
Check.True(n.Points.All(q => Y(q) > p.Y), $"only the north side: {Pts(n.Points)}");
Check.True(n.Points.Any(q => Y(q) > 20), "the room north is walked");
var s = DungeonPathfinder.BuildPatrolRoute(d.Graph, corr, null, geo, Everything, portals, (2.65, 4, 0));
KeptOut(s, p, "character south of the portal");
Check.True(s.Points.All(q => Y(q) < p.Y), $"only the south side: {Pts(s.Points)}");
Check.True(s.Points.Any(q => Y(q) < 0), "the room south is walked");
}
private static void OtherLevelIgnored()
{
var (d, west) = LoopDungeon();
var geo = d.Geo();
var plain = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo);
var up = Portal(15, 15, 6.0); // a floor 6 m above
var route = DungeonPathfinder.BuildPatrolRoute(d.Graph, west, null, geo, null, new[] { up });
Check.Eq(Pts(route.Points), Pts(plain.Points), "the same patrol as without it");
var r = DungeonPathfinder.LastPortalAvoidance![0];
Check.True(double.IsPositiveInfinity(r.Nearest) && r.Closed.Count == 0 && r.Bent == 0, "nothing done about it: " + r.Describe());
}
// ── Tiny Hive on the real dats ───────────────────────────────────────────
private const string AcDir = @"C:\Turbine\Asheron's Call";
private static void TinyHiveRealDats()
{
if (!Directory.Exists(AcDir)) { Console.WriteLine(" (no dats on this PC: skipped)"); return; }
var loader = new GeometryLoader();
if (!loader.Initialize(AcDir)) { Console.WriteLine(" (geometry loader failed: " + loader.StatusMessage + ")"); return; }
try
{
const uint lb = 0x0289, start = 0x028902A5, nook = 0x028902BA, ramp = 0x028902BB;
var graph = DungeonPathfinder.GetGraph(lb, loader.CellDat);
var geo = DungeonPathfinder.GetGeometry(lb, loader.CellDat, loader.DungeonLOS);
Check.True(graph.Count > 400 && geo != null, $"Tiny Hive loaded ({graph.Count} cells)");
// +Buffy's settings on 2026-10-23: coverage Everything, floors walked, rooms looked into from 20 m.
var opt = new DungeonPatrolOptions { Coverage = PatrolCoverage.Everything, AvoidHazardFloors = false, LookInRoomMeters = 20 };
// The Surface Portal (weenie 11218, 0x7028905D): cell 028902BA, local (110, -3.77927, -23.995).
var p = new PatrolPortal { Id = 0x7028905D, Name = "Surface Portal", Cell = nook, X = 2 * 192 + 110, Y = 0x89 * 192 - 3.77927, Z = -23.995 };
var before = DungeonPathfinder.BuildPatrolRoute(graph, start, null, geo, opt);
Check.Eq(before.Points.Count, 355, "the 355-point patrol of the report");
Check.True(Nearest(before.Points, p.X, p.Y).Point < 0.1, $"its waypoint 1 sat on the portal ({Nearest(before.Points, p.X, p.Y).Point:F2} m)");
var route = DungeonPathfinder.BuildPatrolRoute(graph, start, null, geo, opt, new[] { p });
KeptOut(route, p, "Tiny Hive");
var r = DungeonPathfinder.LastPortalAvoidance![0];
Check.True(r.Closed.Contains((nook, ramp)) || r.Closed.Contains((ramp, nook)), "the nook's doorway closed: " + r.Describe());
Check.True(route.Points.Count > 300, $"the rest of the dungeon still patrolled ({route.Points.Count} points)");
Console.WriteLine(" " + r.Describe());
}
finally { DungeonPathfinder.InvalidateCache(); }
}
// ── The plugin side ──────────────────────────────────────────────────────
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
private const uint Player = 0x50000001;
private static void PluginCollectsPortals()
{
FakeHost.Reset();
const uint surface = 0x7028905D, other = 0x7028905E, lamp = 0x70289060, outside = 0x7029A001;
FakeHost.Names[Player] = "Tester";
FakeHost.Positions[Player] = (0x028902A5, 110f, 92f, -30f);
FakeHost.PlayerPose = (0x028902A5, 110f, 92f, -30f);
FakeHost.Names[surface] = "Surface Portal";
FakeHost.ItemTypes[surface] = 0x00010000;
FakeHost.Positions[surface] = (0x028902BA, 110f, -3.77927f, -23.995f);
FakeHost.Names[lamp] = "Lamp";
FakeHost.ItemTypes[lamp] = 0x00000080;
FakeHost.Positions[lamp] = (0x028902BA, 111f, -3f, -24f);
FakeHost.Names[outside] = "Tiny Hive Portal";
FakeHost.ItemTypes[outside] = 0x00010000;
FakeHost.Positions[outside] = (0x24BD002F, 50f, 50f, 0f);
var host = FakeHost.Create(Player);
var plugin = new RynthAiPlugin();
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(plugin, new object[] { FakeHost.LastApi });
var settings = new LegacyUiSettings();
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, settings);
void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(plugin, v);
object? Call(string m, params object?[] a) => typeof(RynthAiPlugin).GetMethod(m, Any)!.Invoke(plugin, a);
Set("_dashboard", dash);
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
Set("_objectCache", cache);
foreach (uint id in new[] { surface, lamp, outside }) cache.OnCreateObject(id);
cache.Tick();
var portals = (List<PatrolPortal>)Call("PatrolPortalsIn", 0x0289u)!;
Check.Eq(portals.Count, 1, "one portal in Tiny Hive (not the lamp, not the one outside)");
var p = portals[0];
Check.Eq(p.Id, surface, "the Surface Portal");
Check.Eq(p.Cell, 0x028902BAu, "its cell");
Check.Near(p.X, 494.0, 1e-3, "world x = 2 x 192 + 110");
Check.Near(p.Y, 26300.22, 1e-2, "world y = 0x89 x 192 - 3.78");
Check.Near(p.Z, -23.995, 1e-3, "its height");
Check.Near(p.Radius, DungeonPathfinder.PortalKeepOutDefault, 1e-9, "keep-out 3.5 m at the default nav point reach");
settings.FollowNavMin = 3.0f;
Check.True(((List<PatrolPortal>)Call("PatrolPortalsIn", 0x0289u)!)[0].Radius > 5.5, "a 3 yd reach keeps further out");
settings.FollowNavMin = 1.5f;
// Built round it: no rebuild. Another one comes into view: rebuild.
Set("_dunPatrolLandblock", 0x0289u);
Call("MarkPatrolPortals", portals);
Set("_dunPatrolPortalCheckAt", 0L);
Check.False((bool)Call("PatrolPortalAppeared")!, "the portals it was built round: nothing to do");
FakeHost.Names[other] = "Portal to the Hive Depths";
FakeHost.ItemTypes[other] = 0x00010000;
FakeHost.Positions[other] = (0x02890270, 100f, 50f, -36f);
cache.OnCreateObject(other);
cache.Tick();
Set("_dunPatrolPortalCheckAt", 0L);
Check.True((bool)Call("PatrolPortalAppeared")!, "a new portal in the dungeon: rebuild");
Check.True(FakeHost.Logs.Any(l => l.Contains("came into view") && l.Contains("0x7028905E")), "and it says which");
Check.False((bool)Call("PatrolPortalAppeared")!, "checked at most once a second");
}
}

View file

@ -23,6 +23,7 @@ internal static class StuckCastTests
{
r.Add("stuck cast: after a 'too busy' UseDone nothing starts until the server answers; no timer re-send while our cast is open", NoResendAfterTooBusy);
r.Add("stuck cast: with no cast of ours open, one probe after 1.5 s, then doubling; a UseDone(0) clears", ProbeWhenNothingOpen);
r.Add("too busy (Conquest 10-25): a try held by another check (animating) is not spent; the next asker (combat) gets it", TryNotSpentWhenHeld);
r.Add("stuck cast: a held cast is turned to its target at cycle + 1 s, broken by a jump TurnGraceMs after the turn; a normal 4 s cast trips neither", TurnThenJump);
r.Add("stuck cast: already facing the target (no turn), the jump is at cycle + 2 s", JumpWithoutTurn);
r.Add("stuck cast: no starts in the air; after landing, no UseDone in 3 s -> Peace mode, 3 s more -> going on", AfterTheJump);
@ -342,6 +343,36 @@ internal static class StuckCastTests
finally { Done(); }
}
// Conquest report R-20261025-183343 (Dargoth Hera): a corpse pickup and a cast went out together, the
// cast was refused 'too busy', and the buff step took all three tries after it while the character was
// still animating, so it sent nothing; combat never got a try and the fight stood for the latch's 15 s.
private static void TryNotSpentWhenHeld()
{
var host = Setup();
try
{
Check.True(MayAs(host, "Combat", HealNeed.None), "free");
Cast(host, "Heart Rend");
_t += 100;
FakeHost.UseDone(ActionPacer.TooBusyErr); // refused next to a pickup (no UseDone of its own)
Check.False(MayAs(host, "Combat", HealNeed.None), "held right after the 0x1D");
_t += ActionPacer.BusyProbeMs;
FakeHost.CastBusy = 1; // the client still animates
Check.False(MayAs(host, "Buff", HealNeed.None), "the buff step's try is held by the animation");
FakeHost.CastBusy = 0;
Check.True(MayAs(host, "Combat", HealNeed.None), "combat gets the try the buff step couldn't use");
Check.False(MayAs(host, "Buff", HealNeed.None), "and only one start has it");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("one try (#1)")), 1, "one try logged");
Check.True(FakeHost.Logs.Any(l => l.Contains("Combat: one try (#1)")), "and it was combat's");
// The next try is counted from the one that went (doubling as before).
_t += ActionPacer.BusyProbeMs * 2 - 1;
Check.False(MayAs(host, "Combat", HealNeed.None), "the next try waits twice as long");
_t += 1;
Check.True(MayAs(host, "Combat", HealNeed.None), "then goes");
}
finally { Done(); }
}
private static void ProbeWhenNothingOpen()
{
var host = Setup();

View file

@ -23,7 +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: Re-stam To keeps a started recharge going to its line; off = one recharge as before", RestamTo);
r.Add("vitals: a recharge started in a fight finishes to Re-stam To after the fight", RestamRunOutlivesFight);
r.Add("vitals: a recharge started in a fight, or under Re-stam At just after one, finishes to Re-stam To", RestamRunOutlivesFight);
r.Add("vitals: a Re-stam To run counts casts sent, not the ticks spent waiting for one", RestamRunCountsSentCasts);
r.Add("vitals: out of Magic stance a listed stamina potion goes before Revitalize; a caster casts first", StaminaPotionFirst);
r.Add("vitals: a listed potion whose stack ran out is drunk from the next stack of that name", ListedPotionNextStack);
@ -336,6 +336,21 @@ internal static class VitalsTests
Check.Eq(BuffManager.StaminaLine(false, 91, s, ref run, ref casts), 60, "reached 90: done, the top-off line again");
Check.False(run, "the recharge ended");
Check.Eq(BuffManager.StaminaLine(false, 55, s, ref run, ref casts), 60, "no recharge running: idle uses Top Stam");
// Drakkon, 10-23: the fight ended with stamina under Re-stam At before a recharge started (a
// Stamina to Health drained 174 just before the kill): the top-off stopped at 60.
run = false; casts = 0;
Check.Eq(BuffManager.StaminaLine(false, 20, s, ref run, ref casts), 90, "no monster, 20%: under Re-stam At, recharge to 90");
Check.True(run, "a recharge started");
casts++;
Check.Eq(BuffManager.StaminaLine(false, 65, s, ref run, ref casts), 90, "65% after one kit: still to 90, not Top Stam 60");
casts++;
Check.Eq(BuffManager.StaminaLine(false, 92, s, ref run, ref casts), 60, "reached 90: done");
Check.Eq(BuffManager.StaminaLine(false, 40, s, ref run, ref casts), 60, "40% with no recharge running (over Re-stam At): Top Stam as before");
var off = new LegacyUiSettings { RestamAt = 35, RestamTo = 0, TopOffStam = 60 };
run = false; casts = 0;
Check.Eq(BuffManager.StaminaLine(false, 20, off, ref run, ref casts), 60, "Re-stam To off: Top Stam as before");
Check.False(run, "and no recharge run");
}
// Drakkon, 2026-10-20: every Re-stam To run stopped after one Robustification. The stamina chain also

View file

@ -30,6 +30,34 @@ internal static class WallTests
r.Add("walls: far off the target, it turns first and casts after the settle; facing it, no turn", WallFacing);
r.Add("walls: the cast itself waits for the turn, then goes as an area cast", WallCastThroughAttack);
r.Add("walls: UseWall, Wall Range and Min Wall Targets load off / 0 / 3 from old files", OldSettings);
r.Add("rings: a ring is due only when one is known; Void has none, so a Void caster casts its bolt (#rynth-issues 2026-10-23)", RingNeedsAKnownRing);
}
// A Void caster on DreamWeave with Use Ring on stood in the fight once 3+ monsters were near:
// the ring override picked "Nether Ring", which doesn't exist, and nothing else was tried
// ("No spell found: elem=Nether warTier=1 voidTier=7").
private static void RingNeedsAKnownRing()
{
var rig = new Rig(7, "Nether Bolt VII", "Nether Streak VII", "Frost Bolt VI", "Halo of Frost", "Frost Ring II");
rig.S.RingRange = 20; rig.S.MinRingTargets = 3; rig.S.WallRange = 0;
int near = 4;
rig.C.RingCountOverride = () => near;
var boltRing = new MonsterRule { Name = "Gilded Shade", UseBolt = true, UseRing = true };
Check.Eq(rig.Cast("Nether", boltRing), ("Nether Bolt VII", "Bolt"), "Void, 4 near (3 needed), no Void ring exists: Nether Bolt");
var streakRing = new MonsterRule { Name = "Gilded Shade", UseBolt = false, UseStreak = true, UseRing = true };
Check.Eq(rig.Cast("Nether", streakRing), ("Nether Streak VII", "Streak"), "Void, Streak + Ring: Nether Streak");
Check.True(FakeHost.Logs.Any(l => l.Contains("no Nether ring spell known")), "logged once");
Check.Eq(FakeHost.Logs.Count(l => l.Contains("no Nether ring spell known")), 1, "only once");
Check.Eq(rig.Cast("Cold", boltRing).Shape, "Ring", "War with a cold ring known: still the ring");
near = 2;
Check.Eq(rig.Cast("Cold", boltRing), ("Frost Bolt VI", "Bolt"), "too few near: Bolt");
var noRing = new Rig(7, "Flame Bolt VI");
noRing.S.RingRange = 20; noRing.S.MinRingTargets = 3; noRing.S.WallRange = 0;
noRing.C.RingCountOverride = () => 5;
Check.Eq(noRing.Cast("Fire", boltRing), ("Flame Bolt VI", "Bolt"), "War with no fire ring known: Flame Bolt, not nothing");
}
private static int Id(string name) => SpellTable.Named(name).Select(r => r.Id).First();