feat: port SK test branch (2026.10.18.24) onto sk

Squash of test/hotbuild-2026-10-16 as merged onto aelrynth main 2026.10.17.1, matching the
2026.10.18.24 test installer. The test branch wins where both changed the same lines; sk-only
changes kept; duplicate features cut to the test branch's copy. RynthAi HandWrittenVersion stays
0.5.0-legacy-ui on sk.

Highlights: RynthOracle 0.6.0 (Legendary, Markers, Dynamic Stamps and Temple guardians merged into
the Quests list, RynthNav Go to), RynthILT 0.2.20 (ub-IT auto-chunk rules, rating level,
RynthILT.Data v3), RynthAi ub-IT /ub and VT/MT meta compatibility and the loot attribute checklist,
RynthNav destination alternatives. Changelog/2026-10-18-sk-port-test-branch-2026.10.18.24.md.
This commit is contained in:
BlankenshipG 2026-10-18 16:22:40 -04:00
commit 7797901d69
287 changed files with 22602 additions and 1090 deletions

View file

@ -0,0 +1,119 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Per-monster attack power (2026-10-12): MonsterRule.AttackPower.
//
// Default the DEFAULT line's choice; on the DEFAULT line, the global
// Melee/Missile Power settings (Auto = 100%, or 80% with Use
// Recklessness and the skill trained)
// High 100% every swing or shot
// Reckless 80%: inside the band where Recklessness adds damage (ACE:
// 10%-90% of the bar, retail wiki: 20%-80%, so 80% is in both)
// Variable a new random power each attack, Variable Power Min..Max
// Reckless + Variable random each attack, inside the Recklessness band (20%-80%)
// and the Variable range
//
// Recklessness only adds damage when the skill is trained or specialized; with it
// untrained a reckless choice falls back to High (or Variable), since a short bar
// would only cost damage. Magic doesn't use attack power.
// ============================================================================
/// <summary>Names and resolution of <see cref="MonsterRule.AttackPower"/>.</summary>
public static class AttackPowerModes
{
public const string Default = "Default";
public const string High = "High";
public const string Reckless = "Reckless";
public const string Variable = "Variable";
public const string RecklessVariable = "Reckless + Variable";
/// <summary>Every choice, in the order the editors list them.</summary>
public static readonly string[] All = { Default, High, Reckless, Variable, RecklessVariable };
/// <summary>The bar fraction a fixed reckless attack uses.</summary>
public const float RecklessPower = 0.8f;
/// <summary>The Recklessness band used for a varied reckless attack (retail wiki: 20%-80%).</summary>
public const int RecklessBandMinPct = 20;
public const int RecklessBandMaxPct = 80;
/// <summary>A saved value as one of <see cref="All"/>; blank or unknown is Default.</summary>
public static string Normalize(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return Default;
string v = value.Trim();
foreach (string m in All)
if (m.Equals(v, StringComparison.OrdinalIgnoreCase)) return m;
// Hand-typed and meta spellings: "RecklessVariable", "reckless+variable".
string squeezed = v.Replace(" ", "").Replace("+", "");
if (squeezed.Equals("RecklessVariable", StringComparison.OrdinalIgnoreCase)) return RecklessVariable;
return Default;
}
/// <summary>
/// The mode that applies to a monster: its own rule's, else the DEFAULT line's, else
/// Default (the global settings). <paramref name="defaultRule"/> may be the same object.
/// </summary>
public static string Effective(MonsterRule? rule, MonsterRule? defaultRule)
{
string own = Normalize(rule?.AttackPower);
if (own != Default) return own;
return Normalize(defaultRule?.AttackPower);
}
/// <summary>
/// The power bar fraction (0..1) for one attack.
/// <paramref name="globalPct"/> is the global Melee/Missile Power (-1 = Auto);
/// <paramref name="random01"/> returns a value in [0, 1).
/// </summary>
public static float Resolve(string mode, int globalPct, bool useRecklessness, bool recklessTrained,
int variableMinPct, int variableMaxPct, Func<double> random01)
{
switch (Normalize(mode))
{
case High:
return 1.0f;
case Reckless:
return recklessTrained ? RecklessPower : 1.0f;
case Variable:
{
var (lo, hi) = VariableRange(variableMinPct, variableMaxPct);
return Pick(lo, hi, random01);
}
case RecklessVariable:
{
var (lo, hi) = VariableRange(variableMinPct, variableMaxPct);
if (!recklessTrained) return Pick(lo, hi, random01);
int rlo = Math.Max(lo, RecklessBandMinPct);
int rhi = Math.Min(hi, RecklessBandMaxPct);
// The Variable range doesn't overlap the band (e.g. 85-100): the whole band.
if (rlo > rhi) { rlo = RecklessBandMinPct; rhi = RecklessBandMaxPct; }
return Pick(rlo, rhi, random01);
}
default:
if (globalPct < 0)
return useRecklessness && recklessTrained ? RecklessPower : 1.0f;
return Math.Clamp(globalPct, 0, 100) / 100f;
}
}
/// <summary>The Variable range in percent, clamped to 0..100 and put in order.</summary>
public static (int Lo, int Hi) VariableRange(int minPct, int maxPct)
{
int lo = Math.Clamp(minPct, 0, 100), hi = Math.Clamp(maxPct, 0, 100);
return lo <= hi ? (lo, hi) : (hi, lo);
}
private static float Pick(int loPct, int hiPct, Func<double> random01)
{
double r = Math.Clamp(random01(), 0.0, 1.0);
double pct = loPct + (hiPct - loPct) * r;
return (float)(Math.Round(pct) / 100.0);
}
}

View file

@ -0,0 +1,523 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Environment-impact throttle (2026-10-12). Rules and bookkeeping in EnvironmentImpact.cs.
///
/// missile "Your missile attack hit the environment." in Missile mode counts one hit on the
/// target the server's attack is bound to.
/// magic each single-target war/void cast is watched: our projectiles (named like the
/// shape, "Flame Bolt") are claimed as they appear next to the player, followed until
/// they stop or vanish, and the cast counts one hit when every projectile stopped
/// short of the target (ProjectileImpactJudge) and no hit, resist or evade line came
/// back for it. Rings and walls aren't watched: they don't fly at the target.
///
/// At EnvironmentImpactLimit hits within the window the throttle trips: the server's attack is
/// released (a magic cast in flight finishes first) and the chosen response runs: an approach
/// (autorun toward the target, at most EnvironmentApproachMeters, never nearer than
/// EnvironmentMinDistance, bounded in time and by progress), or a new target (this one skipped
/// for EnvironmentSkipSec). Off = no detection at all.
/// </summary>
public partial class CombatManager
{
/// <summary>Clock for the throttle and the projectile watch; tests replace it.</summary>
internal Func<DateTime> EnvClock { get; set; } = () => DateTime.Now;
internal EnvironmentImpactThrottle EnvThrottle { get; } = new();
/// <summary>The start of the chat line ACE sends the shooter (ProjectileCollisionHelper.OnCollideEnvironment,
/// a Broadcast line). Matched at the line's start only: a player's copy has their name in front.</summary>
internal const string MissileEnvironmentText = "Your missile attack hit the environment";
// A cast's projectiles appear once its windup ends (up to ~2.5 s for a high tier).
private const double CastClaimWindowMs = 4000;
// Our projectile spawns at the caster; farther than this at its first sight it isn't ours.
private const double ClaimRadiusMeters = 8.0;
// Still this long after flying counts as stopped (ACE zeroes its velocity on impact).
private const double StoppedForMs = 250;
private const double StillMeters = 0.05;
// A projectile still flying after this is dropped from the watch (no verdict).
private const double ProjectileMaxFlightMs = 8000;
// After the last projectile stops, a hit/resist/evade line still has this long to arrive.
private const double ImpactEvidenceGraceMs = 1000;
private const int MaxCastWatches = 4;
// An approach that hasn't gained this much ground in ApproachNoProgressMs is blocked.
private const double ApproachProgressMeters = 0.5;
private const double ApproachNoProgressMs = 2500;
private const double ApproachMaxMs = 8000;
private const double ApproachRunRefreshMs = 1000;
private const double ApproachTurnRefreshMs = 300;
private const double ApproachFaceToleranceDeg = 10;
// Think stopped driving the approach (buffing took over, out of range): let go of autorun.
private const double ApproachOrphanMs = 1500;
private enum EnvKind { Missile, Magic }
private sealed class TrackedProjectile
{
public uint Id;
public double StartX, StartY, StartZ;
public double LastX, LastY, LastZ;
public DateTime FirstSeen, LastMoved;
public double Travel;
public bool Resolved, Short;
}
private sealed class CastWatch
{
public int TargetId;
public string SpellName = "";
public DateTime CastAt;
public double CasterX, CasterY, CasterZ;
public bool HasCasterPos;
public readonly List<TrackedProjectile> Projectiles = new();
public DateTime LastImpactAt = DateTime.MinValue;
}
// Creates are queued and claimed by the heartbeat poll (the name lands a moment later).
private readonly ConcurrentQueue<(uint Id, DateTime At)> _envCreated = new();
private readonly List<(uint Id, DateTime At)> _envCandidates = new();
private readonly List<CastWatch> _castWatches = new();
private readonly Dictionary<int, DateTime> _envSkipUntil = new();
private DateTime _envLastEvidenceAt = DateTime.MinValue;
// The trip waiting for Think, and the approach in progress.
private int _envPendingTargetId;
private EnvKind _envPendingKind;
private int _envApproachTargetId;
private EnvKind _envApproachKind;
private double _envApproachGoal, _envApproachBestDist;
private DateTime _envApproachStartedAt, _envApproachProgressAt, _envApproachRunAt, _envApproachTurnAt, _envApproachTickAt;
private bool _envApproachUsedMotions;
/// <summary>True while combat is walking toward a target for its environment hits.</summary>
internal bool EnvironmentApproachActive => _envApproachTargetId != 0;
private EnvironmentResponse ResponseFor(EnvKind kind) => EnvironmentImpactPlanner.Parse(
kind == EnvKind.Missile ? _settings.MissileEnvironmentResponse : _settings.MagicEnvironmentResponse);
// ── Signals ────────────────────────────────────────────────────────────────
/// <summary>A new object. Only queued while the macro runs with magic detection on
/// (the heartbeat poll that drains the queue runs only then). Separate from OnObjectCreated,
/// which feeds the ghost tracker on every create.</summary>
public void OnEnvironmentObjectCreated(uint objectId)
{
if (objectId == 0 || _settings.MagicEnvironmentResponse == 0 || !_settings.IsMacroRunning) return;
_envCreated.Enqueue((objectId, EnvClock()));
}
/// <summary>From OnObjectDeleted: a projectile that vanished has hit something, and a
/// monster id that's gone forgets its hits, approaches and skip.</summary>
private void OnEnvironmentObjectDeleted(uint objectId)
{
int id = (int)objectId;
EnvThrottle.Forget(id);
_envSkipUntil.Remove(id);
if (_castWatches.Count == 0) return;
DateTime now = EnvClock();
foreach (var w in _castWatches)
foreach (var p in w.Projectiles)
if (p.Id == objectId && !p.Resolved) ResolveProjectile(w, p, now);
}
/// <summary>The missile line, from HandleChatForDamage. True when it was that line.</summary>
private bool NoteMissileEnvironmentChat(string text)
{
if (!ChatSource.StartsWithMarker(text, MissileEnvironmentText, StringComparison.OrdinalIgnoreCase)) return false;
if (ResponseFor(EnvKind.Missile) == EnvironmentResponse.Off) return true;
if (CurrentCombatMode != CombatMode.Missile) return true;
int target = _serverAttackTargetId != 0 ? _serverAttackTargetId : activeTargetId;
if (target != 0) RecordEnvironmentImpact(target, EnvKind.Missile, "missile hit the environment");
return true;
}
/// <summary>Any sign an attack reached a monster (hit, resist, evade, a health drop):
/// a cast with one of these after it didn't only hit the environment.</summary>
private void NoteEnvironmentEvidence() => _envLastEvidenceAt = EnvClock();
/// <summary>A single-target cast just went out (AttackWithMagic): watch its projectiles.</summary>
internal void RegisterCastWatch(int targetId, string spellName)
{
if (ResponseFor(EnvKind.Magic) == EnvironmentResponse.Off || targetId == 0) return;
DateTime now = EnvClock();
var w = new CastWatch { TargetId = targetId, SpellName = spellName, CastAt = now };
if (TryGetPlayerGlobal(out double px, out double py, out double pz))
{
w.CasterX = px; w.CasterY = py; w.CasterZ = pz; w.HasCasterPos = true;
}
if (_castWatches.Count >= MaxCastWatches) _castWatches.RemoveAt(0);
_castWatches.Add(w);
}
/// <summary>Counts one environment hit; at the limit, arms the response for Think.</summary>
private void RecordEnvironmentImpact(int targetId, EnvKind kind, string detail)
{
DateTime now = EnvClock();
int limit = Math.Max(1, _settings.EnvironmentImpactLimit);
int window = Math.Max(1, _settings.EnvironmentImpactWindowSec);
int n = EnvThrottle.Record(targetId, now, window);
string name = _worldFilter[targetId]?.Name ?? "";
_host.Log($"[EnvImpact] {kind.ToString().ToLowerInvariant()}: {detail} — 0x{(uint)targetId:X8} '{name}' {n}/{limit} in {window}s");
if (n < limit || targetId != activeTargetId) return;
if (_envApproachTargetId == targetId) return; // already moving closer to it
_envPendingTargetId = targetId;
_envPendingKind = kind;
}
// ── Heartbeat: projectile watch and the approach's safety net ─────────────
/// <summary>Every heartbeat while the macro runs (pump thread).</summary>
internal void PollEnvironmentImpact()
{
DateTime now = EnvClock();
if (_settings.MagicEnvironmentResponse == 0)
{
while (_envCreated.TryDequeue(out _)) { }
_envCandidates.Clear();
_castWatches.Clear();
}
else
{
while (_envCreated.TryDequeue(out var c)) _envCandidates.Add(c);
ClaimProjectiles(now);
TrackProjectiles(now);
JudgeCastWatches(now);
}
// Think drives the approach; when it stops (another activity, out of range, combat off)
// or the deadline passes, autorun must not be left on.
if (_envApproachTargetId != 0
&& ((now - _envApproachTickAt).TotalMilliseconds > ApproachOrphanMs
|| (now - _envApproachStartedAt).TotalMilliseconds > ApproachMaxMs + ApproachOrphanMs
|| !_settings.EnableCombat))
EndEnvironmentApproach("combat stopped driving it");
// Same for the re-sync sidestep's movement key: Think releases it after ResyncStepMs,
// but only while it keeps ticking in magic mode.
if (_resyncState == 2 && (TargetClock() - _resyncAt).TotalMilliseconds > ResyncStepMs + ApproachOrphanMs)
AbandonResync("combat stopped driving it");
}
private void ClaimProjectiles(DateTime now)
{
if (_envCandidates.Count == 0) return;
bool havePlayer = TryGetPlayerGlobal(out double px, out double py, out double pz);
for (int i = _envCandidates.Count - 1; i >= 0; i--)
{
var (id, at) = _envCandidates[i];
string name = _worldFilter[(int)id]?.Name ?? "";
if (name.Length == 0 && _host.TryGetObjectName(id, out string n2)) name = n2;
if (name.Length == 0)
{
// The name lands a moment after the create; give it a second.
if ((now - at).TotalMilliseconds > 1000) _envCandidates.RemoveAt(i);
continue;
}
_envCandidates.RemoveAt(i);
if (!IsWatchedProjectileName(name)) continue;
if (!havePlayer || !TryGetObjectGlobal(id, out double x, out double y, out double z)) continue;
if (Dist(px, py, pz, x, y, z) > ClaimRadiusMeters) continue;
// The newest cast still taking projectiles (a blast's several share one cast).
CastWatch? owner = null;
for (int w = _castWatches.Count - 1; w >= 0; w--)
{
double age = (at - _castWatches[w].CastAt).TotalMilliseconds;
if (age >= -50 && age <= CastClaimWindowMs) { owner = _castWatches[w]; break; }
}
if (owner == null) continue;
owner.Projectiles.Add(new TrackedProjectile
{
Id = id, StartX = x, StartY = y, StartZ = z, LastX = x, LastY = y, LastZ = z,
FirstSeen = now, LastMoved = now,
});
}
}
/// <summary>A war/void projectile: the shape names (SpellShapes/VoidSpellShapes), or any
/// name ending in a flying shape (lore-named projectiles of the same shapes).</summary>
internal static bool IsWatchedProjectileName(string name)
{
if (IsSpellProjectileName(name)) return !name.EndsWith(" Ring", StringComparison.OrdinalIgnoreCase);
return name.EndsWith(" Bolt", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Streak", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Arc", StringComparison.OrdinalIgnoreCase)
|| name.EndsWith(" Blast", StringComparison.OrdinalIgnoreCase);
}
private void TrackProjectiles(DateTime now)
{
foreach (var w in _castWatches)
{
foreach (var p in w.Projectiles)
{
if (p.Resolved) continue;
if ((now - p.FirstSeen).TotalMilliseconds > ProjectileMaxFlightMs)
{
p.Resolved = true; // no verdict: treated as not short
continue;
}
if (!TryGetObjectGlobal(p.Id, out double x, out double y, out double z)) continue;
if (Dist(x, y, z, p.LastX, p.LastY, p.LastZ) > StillMeters)
{
p.LastX = x; p.LastY = y; p.LastZ = z;
p.LastMoved = now;
p.Travel = Math.Max(p.Travel, Dist(x, y, z, p.StartX, p.StartY, p.StartZ));
continue;
}
if (p.Travel >= ProjectileImpactJudge.MinTravelMeters
&& (now - p.LastMoved).TotalMilliseconds >= StoppedForMs)
ResolveProjectile(w, p, now);
}
}
}
private void ResolveProjectile(CastWatch w, TrackedProjectile p, DateTime now)
{
p.Resolved = true;
w.LastImpactAt = now;
if (p.Travel < ProjectileImpactJudge.MinTravelMeters) return;
if (!TryGetObjectGlobal((uint)w.TargetId, out double tx, out double ty, out double tz)) return;
double cx = w.CasterX, cy = w.CasterY, cz = w.CasterZ;
if (!w.HasCasterPos) { cx = p.StartX; cy = p.StartY; cz = p.StartZ; }
p.Short = ProjectileImpactJudge.StoppedShort(
Dist(p.LastX, p.LastY, p.LastZ, tx, ty, tz),
Dist(cx, cy, cz, p.LastX, p.LastY, p.LastZ),
Dist(cx, cy, cz, tx, ty, tz));
}
private void JudgeCastWatches(DateTime now)
{
for (int i = _castWatches.Count - 1; i >= 0; i--)
{
var w = _castWatches[i];
double age = (now - w.CastAt).TotalMilliseconds;
if (w.Projectiles.Count == 0)
{
if (age > CastClaimWindowMs + 500) _castWatches.RemoveAt(i); // refused or never seen
continue;
}
// A blast's projectiles all appear together; wait out the claim window only briefly.
bool allResolved = w.Projectiles.TrueForAll(p => p.Resolved);
if (!allResolved) continue;
if ((now - w.LastImpactAt).TotalMilliseconds < ImpactEvidenceGraceMs) continue;
_castWatches.RemoveAt(i);
bool reached = _envLastEvidenceAt >= w.CastAt;
bool allShort = w.Projectiles.TrueForAll(p => p.Short);
if (!reached && allShort)
RecordEnvironmentImpact(w.TargetId, EnvKind.Magic,
$"'{w.SpellName}' stopped short of the target ({w.Projectiles.Count} projectile{(w.Projectiles.Count == 1 ? "" : "s")})");
}
}
// ── Think: the response ───────────────────────────────────────────────────
/// <summary>
/// In ThinkCore once the target is valid and in reach. True = this tick belongs to the
/// response (an approach under way, or the target just switched): no attack.
/// </summary>
internal bool RunEnvironmentImpact(WorldObject targetObj, double currentDist)
{
DateTime now = EnvClock();
if (_envApproachTargetId != 0)
{
if (_envApproachTargetId == activeTargetId)
return ContinueEnvironmentApproach(targetObj, currentDist, now);
EndEnvironmentApproach("the target changed");
}
if (_envPendingTargetId == 0) return false;
if (_envPendingTargetId != activeTargetId) { _envPendingTargetId = 0; return false; }
EnvKind kind = _envPendingKind;
// The cast in flight finishes first: turning or running now would cancel it.
if (kind == EnvKind.Magic && IsCastInFlight()) return true;
// A re-sync sidestep already holding a movement key finishes first: running or turning
// over it would send two movement states at once.
if (_resyncState == 2) return true;
int id = activeTargetId;
_envPendingTargetId = 0;
EnvThrottle.ResetHits(id);
EnvironmentResponse response = ResponseFor(kind);
int minDist = Math.Max(1, _settings.EnvironmentMinDistance);
EnvironmentAction action = EnvironmentImpactPlanner.Decide(response, EnvThrottle.Approaches(id),
currentDist, minDist, HasAlternateTarget(id));
string who = $"0x{(uint)id:X8} '{targetObj.Name}' at {currentDist:0.0}m";
string why = kind == EnvKind.Missile ? "missiles" : "spells";
switch (action)
{
case EnvironmentAction.NewTarget:
{
if (_serverAttackTargetId != 0) ReleaseServerAttack("environment hits", log: false);
int skip = Math.Max(1, _settings.EnvironmentSkipSec);
_envSkipUntil[id] = now.AddSeconds(skip);
_host.Log($"[EnvImpact] {why} keep hitting the environment: leaving {who}, skipping it {skip}s ({EnvironmentImpactPlanner.Name((int)response)})");
SupersedeResync("a new target");
ForgetScanned(id);
DropTarget("environment hits: new target");
return true;
}
case EnvironmentAction.Approach:
{
if (_serverAttackTargetId != 0) ReleaseServerAttack("environment hits", log: false);
double goal = EnvironmentImpactPlanner.ApproachGoal(currentDist, _settings.EnvironmentApproachMeters, minDist);
EnvThrottle.NoteApproach(id);
_envApproachTargetId = id;
_envApproachKind = kind;
_envApproachGoal = goal;
_envApproachBestDist = currentDist;
_envApproachStartedAt = _envApproachProgressAt = _envApproachTickAt = now;
_envApproachRunAt = _envApproachTurnAt = DateTime.MinValue;
_envApproachUsedMotions = false;
_host.Log($"[EnvImpact] {why} keep hitting the environment: moving closer to {who}, stopping at {goal:0.0}m ({EnvironmentImpactPlanner.Name((int)response)})");
SupersedeResync("moving closer");
return ContinueEnvironmentApproach(targetObj, currentDist, now);
}
default:
_host.Log($"[EnvImpact] {why} keep hitting the environment on {who}, but it's the only monster in reach and already close: attacking on");
return false;
}
}
/// <summary>
/// The throttle acted on misses the magic re-sync (TickResyncStep) was also counting. The
/// misses are explained (a wall in the way), so the re-sync's count starts over, and a
/// sidestep that is wanted but not yet started is dropped. Moving closer is itself real
/// movement, which re-syncs the server's copy of our position anyway.
/// </summary>
private void SupersedeResync(string by)
{
_magicMissesSinceHit = 0;
if (_resyncState != 1) return;
_resyncState = 0;
_host.Log($"[EnvImpact] re-sync sidestep dropped: {by} answers the misses");
}
/// <summary>Stops a re-sync sidestep where it is, letting go of its movement key if held.</summary>
private void AbandonResync(string why)
{
if (_resyncState == 0) return;
if (_resyncState == 2) _host.SetMotionBy("Combat/Resync", _resyncMotion, false);
_resyncState = 0;
_host.Log($"[CombatCast] re-sync sidestep stopped: {why}");
}
private bool ContinueEnvironmentApproach(WorldObject targetObj, double currentDist, DateTime now)
{
_envApproachTickAt = now;
if (currentDist <= _envApproachGoal)
{
EndEnvironmentApproach($"reached {currentDist:0.0}m");
return false;
}
if ((now - _envApproachStartedAt).TotalMilliseconds > ApproachMaxMs)
{
EndEnvironmentApproach($"timed out at {currentDist:0.0}m");
return false;
}
if (currentDist < _envApproachBestDist - ApproachProgressMeters)
{
_envApproachBestDist = currentDist;
_envApproachProgressAt = now;
}
else if ((now - _envApproachProgressAt).TotalMilliseconds > ApproachNoProgressMs)
{
EndEnvironmentApproach($"no progress (blocked?) at {currentDist:0.0}m");
return false;
}
// Face the target, then run. A held call (the pacer, a use) is simply tried next tick.
if ((now - _envApproachTurnAt).TotalMilliseconds >= ApproachTurnRefreshMs
&& TryGetHeadingTo(activeTargetId, out double desiredDeg, out double err)
&& err > ApproachFaceToleranceDeg)
{
if (_host.HasTurnToHeading)
{
if (_host.TurnToHeadingBy("Combat/Approach", (float)desiredDeg)) _envApproachTurnAt = now;
}
else
{
FaceTarget(activeTargetId);
_envApproachUsedMotions = true;
_envApproachTurnAt = now;
}
}
if ((now - _envApproachRunAt).TotalMilliseconds >= ApproachRunRefreshMs
&& _host.SetAutoRunBy("Combat/Approach", true))
_envApproachRunAt = now;
_stallWatch.Hold(now);
LastCombatSkipReason = "env-approach"; // D4 record-only
return true;
}
/// <summary>Stops an approach in progress (autorun off). Safe to call when none is.</summary>
private void EndEnvironmentApproach(string why)
{
if (_envApproachTargetId == 0) return;
int id = _envApproachTargetId;
_envApproachTargetId = 0;
if (_envApproachRunAt != DateTime.MinValue) _host.SetAutoRunBy("Combat/Approach", false);
if (_envApproachUsedMotions) ClearCombatTurnMotions();
_host.Log($"[EnvImpact] {_envApproachKind.ToString().ToLowerInvariant()} approach to 0x{(uint)id:X8} ended: {why}");
}
/// <summary>True while <paramref name="id"/> is being skipped for its environment hits.</summary>
private bool IsEnvironmentSkipped(int id)
{
if (_envSkipUntil.Count == 0 || !_envSkipUntil.TryGetValue(id, out DateTime until)) return false;
if (EnvClock() < until) return true;
_envSkipUntil.Remove(id);
return false;
}
/// <summary>Clears every environment-impact state (macro stop, new character).</summary>
private void ResetEnvironmentImpact(string why)
{
EndEnvironmentApproach(why);
AbandonResync(why);
_envPendingTargetId = 0;
_castWatches.Clear();
_envCandidates.Clear();
while (_envCreated.TryDequeue(out _)) { }
EnvThrottle.Clear();
_envSkipUntil.Clear();
}
// ── Positions (global metres: landblock x/y * 192 + the in-block offset) ──
private bool TryGetObjectGlobal(uint id, out double x, out double y, out double z)
{
x = y = z = 0;
if (!_host.TryGetObjectPosition(id, out uint cell, out float lx, out float ly, out float lz)) return false;
x = ((cell >> 24) & 0xFF) * 192.0 + lx;
y = ((cell >> 16) & 0xFF) * 192.0 + ly;
z = lz;
return true;
}
private bool TryGetPlayerGlobal(out double x, out double y, out double z)
{
x = y = z = 0;
if (!_host.TryGetPlayerPose(out uint cell, out float lx, out float ly, out float lz,
out _, out _, out _, out _)) return false;
x = ((cell >> 24) & 0xFF) * 192.0 + lx;
y = ((cell >> 16) & 0xFF) * 192.0 + ly;
z = lz;
return true;
}
private static double Dist(double ax, double ay, double az, double bx, double by, double bz)
{
double dx = ax - bx, dy = ay - by, dz = az - bz;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
}

View file

@ -0,0 +1,246 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.Shared; // TurnToHeadingBy / SetAutoRunBy
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Kite / pull-away (2026-10-16). Rules in KiteModes.cs; distance in LegacyUiSettings.KitePullMeters.
///
/// When the effective monster rule is PullAway, combat tags the mob (one hit window), then
/// autoruns away from its lock-spot origin until the mob has been dragged that many metres
/// clear of where it stood, then stops and kills it. Default and per-mob via MonsterRule.Kite.
/// </summary>
public partial class CombatManager
{
/// <summary>Clock for the kite state machine; tests replace it.</summary>
internal Func<DateTime> KiteClock { get; set; } = () => DateTime.Now;
// Face-away + autorun cadence (mirrors EnvironmentApproach).
private const double KiteTurnRefreshMs = 300;
private const double KiteRunRefreshMs = 1000;
// Think stopped driving the kite (buffing took over): let go of autorun.
private const double KiteOrphanMs = 1500;
// Tag window: allow attacks so aggro sticks before we turn and run.
private const double KiteTagMaxMs = 2500;
// A pull that never gets far enough (blocked, mob leashed) gives up and fights in place.
private const double KiteMaxMs = 20000;
// Don't outrun the chase: stop autorun when farther than this from the mob.
private const double KiteCatchUpSlackMeters = 1.5;
// Progress toward the pull goal; no gain in this long ⇒ blocked / leashed.
private const double KiteProgressMeters = 0.75;
private const double KiteNoProgressMs = 4000;
private enum KitePhase { None, Tag, Flee, Done }
private int _kiteTargetId;
private KitePhase _kitePhase = KitePhase.None;
private double _kiteOriginX, _kiteOriginY, _kiteOriginZ;
private bool _kiteHasOrigin;
private double _kiteBestPull;
private DateTime _kiteStartedAt, _kiteProgressAt, _kiteRunAt, _kiteTurnAt, _kiteTickAt;
private bool _kiteUsedMotions;
// Targets already pulled this engagement (object id): do not re-kite mid-fight.
private readonly HashSet<int> _kiteDoneIds = new();
/// <summary>True while combat is tagging or running a pull-away for the locked target.</summary>
internal bool KiteActive => _kitePhase is KitePhase.Tag or KitePhase.Flee;
/// <summary>
/// In ThinkCore once the target is valid. True = this tick belongs to the kite (flee under
/// way): no attack. Tag phase returns false so the first hit(s) can land.
/// </summary>
internal bool RunKite(WorldObject targetObj, double currentDist)
{
DateTime now = KiteClock();
int id = activeTargetId;
if (id == 0) { EndKite("no target"); return false; }
// Already pulled this object id for this engagement: fight in place.
if (_kiteDoneIds.Contains(id))
{
if (_kiteTargetId == id) EndKite("already pulled");
return false;
}
var rule = GetRuleForTarget(targetObj);
if (!KiteModes.WantsPullAway(rule, DefaultMonsterRule()))
{
if (_kiteTargetId == id) EndKite("rule Off");
return false;
}
// Start (or retarget) a pull for this lock.
if (_kiteTargetId != id || _kitePhase == KitePhase.None)
{
if (_kiteTargetId != 0 && _kiteTargetId != id)
EndKite("the target changed");
BeginKite(id, targetObj, now);
}
_kiteTickAt = now;
double pullMeters = Math.Max(3.0, _settings.KitePullMeters);
if (_kitePhase == KitePhase.Tag)
{
bool tagged = _lastDamageDealtAt != DateTime.MinValue && _lastDamageDealtAt >= _kiteStartedAt;
bool tagTimedOut = (now - _kiteStartedAt).TotalMilliseconds >= KiteTagMaxMs;
if (!_settings.KiteTagFirst || tagged || tagTimedOut)
{
_kitePhase = KitePhase.Flee;
_kiteBestPull = PullDistance(id);
_kiteProgressAt = now;
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
string why = !_settings.KiteTagFirst ? "tag skipped"
: tagged ? "tagged"
: "tag timed out";
_host.Log($"[Kite] pull-away on 0x{(uint)id:X8} '{targetObj.Name}': fleeing ({why}), goal {pullMeters:0}m from origin");
EndEnvironmentApproach("kite pull-away");
}
else
{
LastCombatSkipReason = "kite-tag";
return false; // let Think attack once so aggro sticks
}
}
if (_kitePhase != KitePhase.Flee) return false;
double pulled = PullDistance(id);
if (pulled >= pullMeters)
{
FinishKite(id, $"pulled {pulled:0.0}m");
return false;
}
if ((now - _kiteStartedAt).TotalMilliseconds > KiteMaxMs)
{
FinishKite(id, $"timed out at {pulled:0.0}m");
return false;
}
if (pulled > _kiteBestPull + KiteProgressMeters)
{
_kiteBestPull = pulled;
_kiteProgressAt = now;
}
else if ((now - _kiteProgressAt).TotalMilliseconds > KiteNoProgressMs)
{
FinishKite(id, $"no progress (blocked/leashed?) at {pulled:0.0}m");
return false;
}
// Don't outrun the chase past disengage: wait for the mob to catch up.
double catchUp = Math.Max(1.0, DisengageDistance - KiteCatchUpSlackMeters);
bool waiting = currentDist > catchUp;
// Face away from the mob while fleeing; face it while waiting for catch-up.
if ((now - _kiteTurnAt).TotalMilliseconds >= KiteTurnRefreshMs
&& TryGetHeadingTo(id, out double towardDeg, out _))
{
double faceDeg = waiting ? towardDeg : (towardDeg + 180.0) % 360.0;
if (_host.HasTurnToHeading)
{
if (_host.TurnToHeadingBy("Combat/Kite", (float)faceDeg)) _kiteTurnAt = now;
}
else
{
// No heading snap: FaceTarget only faces toward the mob (useful while waiting).
if (waiting) { FaceTarget(id); _kiteUsedMotions = true; }
_kiteTurnAt = now;
}
}
if (waiting)
{
if (_kiteRunAt != DateTime.MinValue)
{
_host.SetAutoRunBy("Combat/Kite", false);
_kiteRunAt = DateTime.MinValue;
}
LastCombatSkipReason = "kite-wait";
_stallWatch.Hold(now);
return true;
}
if ((now - _kiteRunAt).TotalMilliseconds >= KiteRunRefreshMs
&& _host.SetAutoRunBy("Combat/Kite", true))
_kiteRunAt = now;
_stallWatch.Hold(now);
LastCombatSkipReason = "kite-flee";
return true;
}
private void BeginKite(int id, WorldObject targetObj, DateTime now)
{
_kiteTargetId = id;
_kitePhase = _settings.KiteTagFirst ? KitePhase.Tag : KitePhase.Flee;
_kiteHasOrigin = TryGetObjectGlobal((uint)id, out _kiteOriginX, out _kiteOriginY, out _kiteOriginZ);
if (!_kiteHasOrigin)
_kiteHasOrigin = TryGetPlayerGlobal(out _kiteOriginX, out _kiteOriginY, out _kiteOriginZ);
_kiteBestPull = 0;
_kiteStartedAt = _kiteProgressAt = _kiteTickAt = now;
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
_kiteUsedMotions = false;
string phase = _kitePhase == KitePhase.Tag ? "tag then flee" : "flee";
_host.Log($"[Kite] pull-away start 0x{(uint)id:X8} '{targetObj.Name}' ({phase}, {_settings.KitePullMeters}m)");
if (_kitePhase == KitePhase.Flee)
EndEnvironmentApproach("kite pull-away");
}
/// <summary>How far the mob has been dragged from its lock-spot origin (metres).</summary>
private double PullDistance(int id)
{
if (!_kiteHasOrigin) return 0;
if (!TryGetObjectGlobal((uint)id, out double x, out double y, out double z))
return _kiteBestPull;
return Dist(x, y, z, _kiteOriginX, _kiteOriginY, _kiteOriginZ);
}
/// <summary>Pull succeeded or gave up: remember the id and fight in place.</summary>
private void FinishKite(int id, string why)
{
_kiteDoneIds.Add(id);
if (_kiteDoneIds.Count > 64) _kiteDoneIds.Clear();
EndKite(why);
_host.Log($"[Kite] pull-away done 0x{(uint)id:X8}: {why} — attacking");
}
/// <summary>Stops a kite in progress (autorun off). Safe to call when none is.</summary>
private void EndKite(string why)
{
if (_kitePhase == KitePhase.None && _kiteTargetId == 0) return;
int id = _kiteTargetId;
bool wasRunning = _kiteRunAt != DateTime.MinValue;
_kiteTargetId = 0;
_kitePhase = KitePhase.None;
_kiteHasOrigin = false;
if (wasRunning) _host.SetAutoRunBy("Combat/Kite", false);
if (_kiteUsedMotions) ClearCombatTurnMotions();
_kiteRunAt = _kiteTurnAt = DateTime.MinValue;
if (id != 0)
_host.Log($"[Kite] ended 0x{(uint)id:X8}: {why}");
}
/// <summary>Clears kite state (macro stop, new character).</summary>
private void ResetKite(string why)
{
EndKite(why);
_kiteDoneIds.Clear();
}
/// <summary>
/// Pump-thread orphan watch: Think drives the flee; when it stops (another activity,
/// combat off) autorun must not be left on.
/// </summary>
internal void PollKite()
{
// The Handler-ring run-away has the same orphan rule (autorun must not outlive Think).
PollRingEscape();
if (_kitePhase == KitePhase.None) return;
DateTime now = KiteClock();
if ((now - _kiteTickAt).TotalMilliseconds > KiteOrphanMs
|| !_settings.EnableCombat
|| !_settings.IsMacroRunning)
EndKite("combat stopped driving it");
}
}

View file

@ -1033,6 +1033,9 @@ public partial class CombatManager : IDisposable
// A ghost (the server doesn't have it for us): skipped until it shows it is real.
if (Ghosts.IsGhost(wo.Id)) { _ghostsSkippedInScan++; continue; }
// Left for hitting the environment (New target): skipped for EnvironmentSkipSec.
if (IsEnvironmentSkipped(wo.Id)) continue;
// Just killed (KillerNotification) but not yet a corpse — skip so we
// don't re-lock and cast at it during its death animation.
if (_recentlyKilled.ContainsKey(wo.Id)) continue;
@ -1135,6 +1138,7 @@ public partial class CombatManager : IDisposable
_hitAt.Remove(id);
_blacklistManager.ForgetTarget(id);
Ghosts.NoteDeleted(id);
OnEnvironmentObjectDeleted(objectId);
if (id == activeTargetId || id == _lockedTargetId || id == _lastAttackedTargetId)
_awaitingCastResolution = false;
@ -1436,13 +1440,15 @@ public partial class CombatManager : IDisposable
_damageStore!.RecordTaken(src, name, ElementFromWord(m.Groups["type"].Value), amount);
}
/// <summary>A chat line for the damage meter and the stall watchdog.
/// <summary>A chat line for the damage meter, the stall watchdog and the environment throttle.
/// <paramref name="chatType"/> is the line's eChatTypes (-1 = not known).</summary>
public void HandleChatForDamage(string text, int chatType = -1)
{
if (string.IsNullOrEmpty(text)) return;
// Combat lines come from the server; one in a player's chat type is someone's imitation.
if (RynthCore.Plugin.Shared.ChatSource.IsPlayerAuthored(chatType)) return;
if (ChatSource.IsPlayerAuthored(chatType)) return;
// An arrow into a wall: the environment-impact throttle's missile signal.
if (NoteMissileEnvironmentChat(text)) return;
// A miss is a swing too (stall watchdog). "You evaded X!" is the monster's miss, not ours.
if (text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase) > 0)
NoteSwingEvidence("miss");
@ -1455,6 +1461,7 @@ public partial class CombatManager : IDisposable
if (critLine) _lastCritChatAt = now;
if (!CombatText.TryParseOutgoingHit(text, out string victim, out int amount)) return;
NoteEnvironmentEvidence(); // a cast that hit something didn't only hit the environment
bool crit = critLine || (now - _lastCritChatAt).TotalMilliseconds <= CRIT_WINDOW_MS;
// Which monster the line is about. One spell can hurt several (rings, walls, blasts,
@ -1878,14 +1885,24 @@ public partial class CombatManager : IDisposable
/// <summary>Test seam: one judged magic cast with no damage.</summary>
internal void MagicMissForTest(int tid) => NoteMagicMissForResync(tid);
// ── Empyrean Handler lethal-ring evade (chat-triggered back-jump) ─────────
// ── Empyrean Handler / Chaser lethal-ring evade (chat-triggered run-away) ──
// ACECustom Handler emote: "The handler briefly channels infused Empyrean hatred
// to release a lethal ring." The ring can't be melee-evaded — if the character is
// inside its cast radius they die. On that line, when still in range of a Handler,
// cancel the current swing/cast and back-jump away, then resume combat (target kept).
private const string HandlerRingChannelHint = "channels infused Empyrean hatred to release a lethal ring";
private const string HandlerRingChannelStart = "The handler briefly channels";
private const string HandlerNameHint = "Empyrean Handler";
// 2026-10-17: Empyrean Chasers cast the same lethal ring. Their emote isn't in any log yet, so
// the line is matched loosely: "The handler ..." / "The chaser ..." naming a lethal ring, or
// (any non-speech line) the ring phrase itself. The emote heard is logged once per session.
private const string RingReleaseHint = "release a lethal ring";
/// <summary>The ring casters: the monster name and the word their emote starts with ("The handler").</summary>
private static readonly (string Name, string Subject)[] RingCasters =
{
("Empyrean Handler", "handler"),
("Empyrean Chaser", "chaser"),
};
private bool _ringLineLogged;
/// <summary>Yards: Handler lethal ring is treated as at least this wide (RingRange when larger).</summary>
internal const double HandlerRingDangerYards = 12.0;
/// <summary>Back-jump charge (ms) — run-back + jump must clear ~ring radius.</summary>
@ -1897,6 +1914,27 @@ public partial class CombatManager : IDisposable
private int _handlerRingEvadeId;
private bool _handlerRingJumpStarted;
// Run-away escape (2026-10-17): one back-jump covered a few metres (backwards is AC's slowest
// motion, and the 150 ms turn settle let it jump the wrong way): Silentkelpie died 1.5 m from
// the Handler 3.2 s after the channel line. Now: face away and run forward (the fastest
// motion), re-aiming away from the Handler, until outside the ring plus a margin.
/// <summary>Yards past the ring radius to run before stopping.</summary>
private const double HandlerRingSafeMarginYards = 4.0;
/// <summary>Longest the run lasts (the ring has gone off by then).</summary>
private const double HandlerRingRunMaxMs = 5_000;
/// <summary>Attacks are held at least this long after the channel line (the ring's cast time).</summary>
private const double HandlerRingHoldMinMs = 3_500;
private const double HandlerRingTurnRefreshMs = 250;
private const double HandlerRingRunRefreshMs = 1_000;
/// <summary>Pump-thread orphan watch: Think stopped driving the run this long ago -> autorun off.</summary>
private const double HandlerRingOrphanMs = 1_500;
private const string RingEscapeSource = "Combat/RingEscape";
private bool _ringRunActive;
private bool _ringRunning; // autorun is on (else holding at a safe distance)
private double _ringSafeYards;
private double _ringDanger;
private DateTime _ringRunAt = DateTime.MinValue, _ringTurnAt = DateTime.MinValue, _ringTickAt = DateTime.MinValue;
/// <summary>
/// Plugin wires this to <c>Jumper.Start("xs", faceHeading, ms)</c> — face the Handler
/// then run-back jump (x+s) so the body moves away. Returns false if the jumper refused.
@ -1906,9 +1944,9 @@ public partial class CombatManager : IDisposable
/// <summary>True while the wired jumper is mid-turn / charge / settle.</summary>
public Func<bool>? JumpBusy { get; set; }
/// <summary>True while a Handler-ring evade is holding combat (jump or settle).</summary>
/// <summary>True while a Handler-ring evade is holding combat (run, wait, or jump/settle).</summary>
public bool RingEvadeActive =>
_handlerRingEvadeUntil != DateTime.MinValue && DateTime.Now < _handlerRingEvadeUntil;
_ringRunActive || (_handlerRingEvadeUntil != DateTime.MinValue && DateTime.Now < _handlerRingEvadeUntil);
/// <summary>
/// Chat line from RynthAiPlugin.OnChatWindowText. Starts a back-jump evade when the
@ -1920,10 +1958,20 @@ public partial class CombatManager : IDisposable
// Handler channel is an Emote (0x0C). ChatSource.IsPlayerAuthored treats Emote as
// player speech, which would skip every real Handler line — anchor on the unique
// phrase starting the line instead (player copies are "Name says, \"...\").
bool anchored =
RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, HandlerRingChannelStart, StringComparison.OrdinalIgnoreCase)
|| (RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, "The handler", StringComparison.OrdinalIgnoreCase)
&& text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) >= 0);
bool mentionsRing = text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) >= 0
|| text.IndexOf(RingReleaseHint, StringComparison.OrdinalIgnoreCase) >= 0;
if (!mentionsRing) return;
// Which caster the emote names ("The handler ..." / "The chaser ..."), or null.
string? subject = null;
foreach ((string _, string word) in RingCasters)
if (RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, "The " + word, StringComparison.OrdinalIgnoreCase))
{
subject = word;
break;
}
bool anchored = subject != null
|| RynthCore.Plugin.Shared.ChatSource.StartsWithMarker(text, HandlerRingChannelStart, StringComparison.OrdinalIgnoreCase);
if (!anchored)
{
// Mid-line only when the type is clearly not player speech (some clients strip "The ").
@ -1935,64 +1983,91 @@ public partial class CombatManager : IDisposable
or RynthCore.Plugin.Shared.ChatSource.Allegiance
or RynthCore.Plugin.Shared.ChatSource.Fellowship)
return;
if (text.IndexOf(HandlerRingChannelHint, StringComparison.OrdinalIgnoreCase) < 0) return;
if (text.IndexOf(" says,", StringComparison.OrdinalIgnoreCase) >= 0
|| text.IndexOf(" tells you,", StringComparison.OrdinalIgnoreCase) >= 0)
return;
}
// The wording that triggered, once per session (the Chaser's emote wasn't known when this
// was written; the log shows it the first time one is heard).
if (!_ringLineLogged)
{
_ringLineLogged = true;
_host.Log($"[CombatEvade] lethal-ring line heard (type 0x{chatType:X2}): \"{text.Trim()}\"");
}
DateTime now = DateTime.Now;
if (_handlerRingEvadeAt != DateTime.MinValue
&& (now - _handlerRingEvadeAt).TotalMilliseconds < HandlerRingEvadeCooldownMs)
return;
if (!TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name))
if (!TryFindHandlerForRingEvade(subject, out int handlerId, out double dist, out string name))
{
_host.Log("[CombatEvade] Handler lethal-ring channel heard, but no Empyrean Handler is nearby — no jump.");
_host.Log("[CombatEvade] Lethal-ring channel heard, but no Empyrean Handler or Chaser is nearby — no evade.");
return;
}
double danger = Math.Max(HandlerRingDangerYards, Math.Max(1, _settings.RingRange));
if (dist > danger)
{
_host.Log($"[CombatEvade] Handler lethal-ring channel; '{name}' at {dist:0.0} m (outside {danger:0.#} m) — staying put.");
_host.Log($"[CombatEvade] Lethal-ring channel; '{name}' at {dist:0.0} m (outside {danger:0.#} m) — staying put.");
return;
}
// Face the Handler, then Jumper "xs" (back + run) moves the body away from it.
// Facing away + back-jump would leap into the ring.
float faceHandler = 0f;
if (TryGetHeadingTo(handlerId, out double toHandler, out _))
faceHandler = (float)(toHandler % 360.0);
else if (_host.TryGetPlayerHeading(out float curr))
faceHandler = curr;
bool haveHeading = TryGetHeadingTo(handlerId, out double toHandler, out _);
_handlerRingEvadeAt = now;
_handlerRingEvadeId = handlerId;
_handlerRingJumpStarted = false;
// Hold combat long enough for turn + charge + land + one re-engage tick.
_handlerRingEvadeUntil = now.AddMilliseconds(HandlerRingJumpHoldMs + 2_200);
// Stop the bound melee/missile attack so the jump isn't eaten by the swing servo.
// Stop the bound melee/missile attack (and any kite run) so the escape isn't eaten by
// the swing servo or steered by the pull-away.
try
{
if (_host.HasCancelAttack) _host.CancelAttack();
ReleaseHeldTurn();
EndKite("Handler lethal ring");
}
catch { }
// Run away: face directly away from the Handler and autorun (forward is the fastest motion).
if (haveHeading && _host.HasTurnToHeading && _host.HasSetAutoRun)
{
float away = (float)((toHandler + 180.0) % 360.0);
_host.TurnToHeadingBy(RingEscapeSource, away);
bool running = _host.SetAutoRunBy(RingEscapeSource, true);
_ringRunActive = true;
_ringRunning = running;
_ringDanger = danger;
_ringSafeYards = danger + HandlerRingSafeMarginYards;
_ringRunAt = running ? now : DateTime.MinValue;
_ringTurnAt = _ringTickAt = now;
_handlerRingEvadeUntil = DateTime.MinValue;
_host.Log($"[CombatEvade] Lethal ring — running away from '{name}' at {dist:0.0} m " +
$"(ring {danger:0.#} m, stop at {_ringSafeYards:0.#} m), heading {away:0}°" +
(running ? "." : " (autorun refused; holding and re-trying)."));
return;
}
// No heading snap / autorun on this engine: the older back-jump. Face the Handler, then
// Jumper "xs" (back + run) moves the body away from it.
float faceHandler = haveHeading ? (float)(toHandler % 360.0)
: _host.TryGetPlayerHeading(out float curr) ? curr : 0f;
// Hold combat long enough for turn + charge + land + one re-engage tick.
_handlerRingEvadeUntil = now.AddMilliseconds(HandlerRingJumpHoldMs + 2_200);
bool started = RequestBackJump?.Invoke(faceHandler, HandlerRingJumpHoldMs) == true;
if (started)
{
_handlerRingJumpStarted = true;
_host.Log($"[CombatEvade] Empyrean Handler lethal ring — back-jump away from '{name}' " +
_host.Log($"[CombatEvade] Lethal ring — back-jump away from '{name}' " +
$"at {dist:0.0} m (danger {danger:0.#} m), face {faceHandler:0}° then xs.");
}
else
{
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_host.Log("[CombatEvade] Empyrean Handler lethal ring heard in range, but the back-jump did not start.");
_host.Log("[CombatEvade] Lethal ring heard in range, but the back-jump did not start.");
}
}
@ -2002,6 +2077,7 @@ public partial class CombatManager : IDisposable
/// </summary>
private bool TickRingEvade()
{
if (_ringRunActive) return TickRingRun();
if (_handlerRingEvadeUntil == DateTime.MinValue) return false;
DateTime now = DateTime.Now;
bool jumperBusy = JumpBusy?.Invoke() == true;
@ -2012,7 +2088,7 @@ public partial class CombatManager : IDisposable
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Handler ring evade done — re-engaging.");
_host.Log("[CombatEvade] Ring evade done — re-engaging.");
return false;
}
@ -2026,28 +2102,140 @@ public partial class CombatManager : IDisposable
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
_handlerRingJumpStarted = false;
_host.Log("[CombatEvade] Handler ring evade done — re-engaging.");
_host.Log("[CombatEvade] Ring evade done — re-engaging.");
return false;
}
/// <summary>Nearest Empyrean Handler (active target preferred when it is one).</summary>
private bool TryFindHandlerForRingEvade(out int handlerId, out double dist, out string name)
/// <summary>
/// The run-away escape, from Think: run (re-aiming away from the Handler) until outside the
/// ring plus a margin or the run times out, then hold attacks until the ring has gone off
/// (running again if the Handler closes back inside the ring). Keeps the target, so combat
/// re-engages after.
/// </summary>
private bool TickRingRun()
{
DateTime now = DateTime.Now;
_ringTickAt = now;
double elapsed = (now - _handlerRingEvadeAt).TotalMilliseconds;
int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId();
double d = me != 0 && _handlerRingEvadeId != 0 ? _worldFilter.Distance(me, _handlerRingEvadeId) : -1;
bool gone = d < 0;
if (_ringRunning)
{
string? stopWhy = gone ? "the caster is gone"
: d >= _ringSafeYards ? "outside the ring"
: elapsed >= HandlerRingRunMaxMs ? "run timed out"
: null;
if (stopWhy != null)
{
_host.SetAutoRunBy(RingEscapeSource, false);
_ringRunning = false;
_ringRunAt = DateTime.MinValue;
_host.Log($"[CombatEvade] Ring run stopped after {elapsed:0} ms: {stopWhy}" +
(gone ? "." : $" ({d:0.0} m from the caster)."));
}
}
else if (!gone && d < _ringDanger && elapsed < HandlerRingHoldMinMs)
{
// Holding, but the Handler came back inside the ring before it went off: run again.
_ringRunning = true;
_ringTurnAt = _ringRunAt = DateTime.MinValue;
_host.Log($"[CombatEvade] Caster back inside the ring ({d:0.0} m) — running again.");
}
if (_ringRunning)
{
if ((now - _ringTurnAt).TotalMilliseconds >= HandlerRingTurnRefreshMs
&& TryGetHeadingTo(_handlerRingEvadeId, out double toward, out _))
{
_host.TurnToHeadingBy(RingEscapeSource, (float)((toward + 180.0) % 360.0));
_ringTurnAt = now;
}
if ((now - _ringRunAt).TotalMilliseconds >= HandlerRingRunRefreshMs
&& _host.SetAutoRunBy(RingEscapeSource, true))
_ringRunAt = now;
LastCombatSkipReason = "handler-ring-run";
_tickWait = CombatLatencyTracker.Wait.Other;
_stallWatch.Hold(now);
return true;
}
if (!gone && elapsed < HandlerRingHoldMinMs)
{
LastCombatSkipReason = "handler-ring-wait";
_tickWait = CombatLatencyTracker.Wait.Other;
_stallWatch.Hold(now);
return true;
}
EndRingRun();
_host.Log($"[CombatEvade] Ring evade done after {elapsed:0} ms" +
(gone ? "." : $" ({d:0.0} m away) — re-engaging."));
return false;
}
/// <summary>Clears the run-away escape (autorun off if it was on).</summary>
private void EndRingRun()
{
if (_ringRunning) _host.SetAutoRunBy(RingEscapeSource, false);
_ringRunActive = _ringRunning = false;
_ringRunAt = _ringTurnAt = DateTime.MinValue;
_handlerRingEvadeUntil = DateTime.MinValue;
_handlerRingEvadeId = 0;
}
/// <summary>Stops a Handler-ring escape now (macro stop, death). Safe to call when none is running.</summary>
public void StopRingEscape(string why)
{
if (!_ringRunActive) return;
EndRingRun();
_host.Log($"[CombatEvade] Ring escape stopped: {why}.");
}
/// <summary>Pump-thread orphan watch: Think drives the run; when it stops (death, another
/// activity, combat or the macro off) autorun must not be left on.</summary>
internal void PollRingEscape()
{
if (!_ringRunActive) return;
if ((DateTime.Now - _ringTickAt).TotalMilliseconds > HandlerRingOrphanMs
|| !_settings.EnableCombat
|| !_settings.IsMacroRunning)
StopRingEscape("combat stopped driving it");
}
/// <summary>
/// The nearest ring caster (Empyrean Handler or Chaser). When the emote named one ("The chaser
/// ..."), the nearest of that kind is taken if there is one in range of the scan; otherwise the
/// nearest of either kind.
/// </summary>
private bool TryFindHandlerForRingEvade(string? subject, out int handlerId, out double dist, out string name)
{
handlerId = 0; dist = double.MaxValue; name = "";
int me = _host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId();
if (me == 0) return false;
int bestId = 0;
double bestDist = double.MaxValue;
string bestName = "";
string? preferred = null;
if (subject != null)
foreach ((string n, string word) in RingCasters)
if (word == subject) preferred = n;
int bestId = 0, prefId = 0;
double bestDist = double.MaxValue, prefDist = double.MaxValue;
string bestName = "", prefName = "";
void Consider(int id, string? nm)
{
if (id == 0 || string.IsNullOrEmpty(nm)) return;
if (nm.IndexOf(HandlerNameHint, StringComparison.OrdinalIgnoreCase) < 0) return;
bool caster = false;
foreach ((string n, string _) in RingCasters)
if (nm.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) { caster = true; break; }
if (!caster) return;
double d = _worldFilter.Distance(me, id);
if (d < 0 || d >= bestDist) return;
bestDist = d; bestId = id; bestName = nm;
if (d < 0) return;
if (d < bestDist) { bestDist = d; bestId = id; bestName = nm; }
if (preferred != null && nm.IndexOf(preferred, StringComparison.OrdinalIgnoreCase) >= 0 && d < prefDist)
{ prefDist = d; prefId = id; prefName = nm; }
}
if (activeTargetId != 0)
@ -2070,6 +2258,7 @@ public partial class CombatManager : IDisposable
catch { }
}
if (prefId != 0) { handlerId = prefId; dist = prefDist; name = prefName; return true; }
if (bestId == 0) return false;
handlerId = bestId; dist = bestDist; name = bestName;
return true;
@ -2081,6 +2270,7 @@ public partial class CombatManager : IDisposable
// Damage / health change on the cast we're judging → that cast HIT.
if (targetId == _pendingJudgeTargetId)
_damageSincePendingCast = true;
NoteEnvironmentEvidence();
// Immediate positive feedback on the engaged target clears the streak.
if (targetId == _lastAttackedTargetId)
_consecutiveCastMisses = 0;
@ -2101,6 +2291,7 @@ public partial class CombatManager : IDisposable
int i = text.IndexOf(" evaded your attack", StringComparison.OrdinalIgnoreCase);
if (i < 0) i = text.IndexOf(" resists your spell", StringComparison.OrdinalIgnoreCase);
if (i <= 0) return;
NoteEnvironmentEvidence(); // the spell or swing reached a monster
string who = text.Substring(0, i).Trim();
if (who.StartsWith("The ", StringComparison.Ordinal)) who = who.Substring(4);
if (who.Length == 0) return;
@ -2422,6 +2613,9 @@ public partial class CombatManager : IDisposable
_host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason} [{DescribeTargetPos(activeTargetId)}]");
activeTargetId = 0;
_lockedTargetId = 0;
EndKite("target dropped");
EndEnvironmentApproach("target dropped");
_envPendingTargetId = 0;
// A turn held toward the dropped target must be let go, or the character keeps
// spinning until something else happens to release it.
if (_facingTarget) ClearCombatTurnMotions();
@ -2924,6 +3118,7 @@ public partial class CombatManager : IDisposable
int id = _scannedTargets[i].Id;
if (id == excludeId) continue;
if (_recentlyKilled.ContainsKey(id)) continue;
if (IsEnvironmentSkipped(id)) continue;
return true;
}
return false;
@ -3179,7 +3374,7 @@ public partial class CombatManager : IDisposable
ForgetScanned(activeTargetId);
DropTarget("hp=0");
}
else if (target != null &&
else if (target != null && !KiteActive &&
_worldFilter.Distance(_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId) > disengageLimit)
DropTarget("out of range");
// If target == null here it's a transient world-filter miss — keep the lock,
@ -3299,9 +3494,18 @@ public partial class CombatManager : IDisposable
// step-back — instead of dropping to peace and restarting the approach.
double currentDist = _worldFilter.Distance(
_host.GetPlayerId() == 0 ? 0 : (int)_host.GetPlayerId(), activeTargetId);
// Pull-away kite runs before the disengage gate: fleeing intentionally stretches
// range, and the kite itself waits for catch-up rather than idling here.
if (RunKite(targetObj, currentDist))
return true;
if (currentDist > disengageLimit)
return true;
// Environment-impact throttle: too many missiles/spells into walls short of this target
// stop the attack and move closer or switch target (CombatManager.EnvironmentImpact.cs).
if (RunEnvironmentImpact(targetObj, currentDist))
return true;
// Melee/missile stall safety net (see CombatStallWatchdog). Holds the attack while
// one of its steps is settling.
if (RunStallWatchdog(targetObj, currentDist))
@ -4130,6 +4334,9 @@ public partial class CombatManager : IDisposable
{
_wasMacroRunning = false;
ClearCombatTurnMotions();
ResetEnvironmentImpact("macro stopped");
ResetKite("macro stopped");
StopRingEscape("macro stopped");
}
return;
}
@ -4137,6 +4344,13 @@ public partial class CombatManager : IDisposable
LogCombatStateIfChanged();
// Environment-impact throttle: follow our spell projectiles, judge finished casts, and
// let go of an approach Think stopped driving.
try { PollEnvironmentImpact(); }
catch (Exception ex) { _host.Log($"[EnvImpact] poll crashed: {ex.Message}"); }
try { PollKite(); }
catch (Exception ex) { _host.Log($"[Kite] poll crashed: {ex.Message}"); }
// A combat mode change ends the server's attack (HandleActionChangeCombatMode →
// HandleActionCancelAttack), so out of Melee/Missile there is nothing bound to release.
if (_serverAttackTargetId != 0)
@ -4217,6 +4431,8 @@ public partial class CombatManager : IDisposable
{
if (_scannedTargets.Count == 0) return;
if (TryLockForcedTarget()) return; // Target lock (/ra targetlock): CombatManager.TargetLock.cs
// Pull-away in progress: keep the incumbent until the kite ends (do not switch mid-flee).
if (KiteActive && _lockedTargetId != 0) return;
// Boost Loot Priority: the next target waits for the last kill's corpse. Without this the
// next lock went out a few ms after each kill, 1-3 s before ACE creates the corpse, so the
// arbiter always saw combat engaged and corpses were looted in batches (2026-10-14).
@ -6080,17 +6296,19 @@ public partial class CombatManager : IDisposable
return false;
}
float power;
// Power: the monster rule's Attack Power (High / Reckless / Variable / Reckless +
// Variable), else the global Melee/Missile Power (AttackPowerPlanner.cs).
int powerPct = isMissile ? _settings.MissileAttackPower : _settings.MeleeAttackPower;
if (powerPct < 0)
bool recklessTrained = _charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2;
var powerTarget = _worldFilter[activeTargetId];
string powerMode = AttackPowerModes.Effective(GetRuleForTarget(powerTarget), DefaultMonsterRule());
float power = AttackPowerModes.Resolve(powerMode, powerPct, _settings.UseRecklessness, recklessTrained,
_settings.VariablePowerMin, _settings.VariablePowerMax, PowerRandom);
if (powerMode != AttackPowerModes.Default && _powerLoggedTargetId != activeTargetId)
{
power = 1.0f;
if (_settings.UseRecklessness && (_charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2))
power = 0.8f;
}
else
{
power = powerPct / 100f;
_powerLoggedTargetId = activeTargetId;
_host.Log($"[AttackPower] 0x{targetId:X8} '{powerTarget?.Name}': {powerMode}" +
(recklessTrained ? "" : " (Recklessness untrained: no reckless band)") + $", first attack at {power * 100:0}%");
}
int uiHeight = isMissile ? _settings.MissileAttackHeight : _settings.MeleeAttackHeight;
@ -6151,10 +6369,17 @@ public partial class CombatManager : IDisposable
if (matches) return r;
}
return _settings.MonsterRules.FirstOrDefault(
m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
return DefaultMonsterRule();
}
/// <summary>The Monsters tab's DEFAULT line (the catch-all rule), or null.</summary>
private MonsterRule? DefaultMonsterRule() => _settings.MonsterRules.FirstOrDefault(
m => m.Name.Equals("Default", StringComparison.OrdinalIgnoreCase));
/// <summary>Random source for Variable attack power, [0, 1); tests replace it.</summary>
internal Func<double> PowerRandom { get; set; } = Random.Shared.NextDouble;
private int _powerLoggedTargetId;
private void AttackWithMagic(WorldObject target)
{
_wallFaceHeld = false;
@ -6331,6 +6556,10 @@ public partial class CombatManager : IDisposable
_pendingOffensiveCastAt = DateTime.Now;
_pendingOffensiveTargetId = activeTargetId;
NoteOffensiveSeq();
// Environment-impact throttle: follow this cast's projectiles (rings and walls
// don't fly at the target, so they aren't judged).
if (!multiTarget)
RegisterCastWatch(activeTargetId, SpellTableStub.GetById(offensiveSpellId)?.Name ?? $"spell {offensiveSpellId}");
// Tag this cast's weapon + element + tier so the pushed damage event
// can be attributed to it, count it for casts-to-kill learning, then

View file

@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Environment-impact throttle (2026-10-12): pure rules and bookkeeping.
//
// A missile or a war/void projectile that hits a wall, a pillar, the ceiling
// or another object short of the target does no damage, and before this the bot
// kept firing into it until the no-damage blacklist (several settle windows) or
// the no-progress timeout gave up. Now, once a target has taken
// EnvironmentImpactLimit such hits within EnvironmentImpactWindowSec, combat
// stops attacking it and does what the player chose for that kind of combat:
// move closer, pick another target, or move closer once and then pick another.
//
// The signals (CombatManager.EnvironmentImpact.cs):
// missile ACE ProjectileCollisionHelper.OnCollideEnvironment sends the shooter
// "Your missile attack hit the environment." (also when the arrow hits
// an object that isn't its target).
// magic ACE sends nothing (SpellProjectile.OnCollideEnvironment only
// explodes the projectile), so the bot follows its own projectiles and
// judges where they stopped (ProjectileImpactJudge).
//
// Everything here is pure (no host, no clock of its own) so the host tests can
// drive it directly.
// ============================================================================
/// <summary>What combat does once a target has taken too many environment hits.
/// Stored as an int in the settings (MissileEnvironmentResponse / MagicEnvironmentResponse).</summary>
public enum EnvironmentResponse
{
/// <summary>No detection; keep attacking (the behaviour before 2026-10-12).</summary>
Off = 0,
/// <summary>Move toward the target each time; once already close, pick another target.</summary>
MoveCloser = 1,
/// <summary>Skip the target for a while and pick another (moves closer when there is no other).</summary>
NewTarget = 2,
/// <summary>Move closer once; if the shots still hit the environment, pick another target.</summary>
CloserThenNewTarget = 3,
}
/// <summary>The step combat takes for one throttle trip.</summary>
public enum EnvironmentAction { None, Approach, NewTarget }
/// <summary>Choices and the decision for one throttle trip.</summary>
public static class EnvironmentImpactPlanner
{
/// <summary>Combo labels, in <see cref="EnvironmentResponse"/> order (plugin and engine settings panels).</summary>
public static readonly string[] ResponseNames =
{ "Off", "Move closer", "New target", "Move closer, then new target" };
/// <summary>Approaching is pointless within this much of the closest allowed distance.</summary>
public const double ApproachSlackMeters = 0.5;
/// <summary>A saved int as a response; anything out of range is Off.</summary>
public static EnvironmentResponse Parse(int value)
=> value is >= 0 and <= 3 ? (EnvironmentResponse)value : EnvironmentResponse.Off;
/// <summary>The label for a saved value (logs and the settings panels).</summary>
public static string Name(int value) => ResponseNames[(int)Parse(value)];
/// <summary>
/// The step for a throttle trip on a target <paramref name="distance"/> metres away that
/// has already been approached <paramref name="approachesDone"/> times for this reason.
/// Never approaches nearer than <paramref name="minDistance"/>. A new target needs another
/// monster in reach: skipping the only one would leave it free to hit the bot while combat
/// idles, so then the bot moves closer if it still can, or keeps attacking (None).
/// </summary>
public static EnvironmentAction Decide(EnvironmentResponse response, int approachesDone,
double distance, double minDistance, bool hasAlternateTarget)
{
bool canApproach = double.IsFinite(distance) && distance > minDistance + ApproachSlackMeters;
EnvironmentAction approachElseNone = canApproach ? EnvironmentAction.Approach : EnvironmentAction.None;
EnvironmentAction newTargetElse = hasAlternateTarget ? EnvironmentAction.NewTarget : approachElseNone;
return response switch
{
EnvironmentResponse.MoveCloser => canApproach ? EnvironmentAction.Approach : newTargetElse,
EnvironmentResponse.NewTarget => newTargetElse,
EnvironmentResponse.CloserThenNewTarget => approachesDone == 0 && canApproach
? EnvironmentAction.Approach : newTargetElse,
_ => EnvironmentAction.None,
};
}
/// <summary>
/// Where an approach stops: <paramref name="stepMeters"/> nearer than now, never nearer
/// than <paramref name="minDistance"/>.
/// </summary>
public static double ApproachGoal(double distance, double stepMeters, double minDistance)
=> Math.Max(Math.Max(0.5, minDistance), distance - Math.Max(1.0, stepMeters));
}
/// <summary>
/// Environment hits per target inside a sliding window, and how many times each target has
/// been approached for them. Pump thread only.
/// </summary>
public sealed class EnvironmentImpactThrottle
{
private readonly Dictionary<int, List<DateTime>> _hits = new();
private readonly Dictionary<int, int> _approaches = new();
// A long session meets thousands of monsters; ids are forgotten on delete, this is the backstop.
private const int MaxTracked = 256;
/// <summary>Records one hit on <paramref name="targetId"/> and returns the hits within the window.</summary>
public int Record(int targetId, DateTime now, double windowSec)
{
if (targetId == 0) return 0;
if (_hits.Count >= MaxTracked && !_hits.ContainsKey(targetId)) _hits.Clear();
if (!_hits.TryGetValue(targetId, out var list)) _hits[targetId] = list = new List<DateTime>(4);
list.Add(now);
Prune(list, now, windowSec);
return list.Count;
}
/// <summary>Hits on <paramref name="targetId"/> within the window (no new hit).</summary>
public int Count(int targetId, DateTime now, double windowSec)
{
if (!_hits.TryGetValue(targetId, out var list)) return 0;
Prune(list, now, windowSec);
return list.Count;
}
/// <summary>Starts the count again (after the bot acted on it).</summary>
public void ResetHits(int targetId) => _hits.Remove(targetId);
public int Approaches(int targetId) => _approaches.TryGetValue(targetId, out int n) ? n : 0;
public void NoteApproach(int targetId)
{
if (_approaches.Count >= MaxTracked && !_approaches.ContainsKey(targetId)) _approaches.Clear();
_approaches[targetId] = Approaches(targetId) + 1;
}
/// <summary>The object is gone (deleted): a respawn reusing the id starts clean.</summary>
public void Forget(int targetId)
{
_hits.Remove(targetId);
_approaches.Remove(targetId);
}
public void Clear()
{
_hits.Clear();
_approaches.Clear();
}
private static void Prune(List<DateTime> list, DateTime now, double windowSec)
{
double window = Math.Max(1.0, windowSec);
list.RemoveAll(t => (now - t).TotalSeconds > window);
}
}
/// <summary>
/// Where a spell projectile stopped, against where the target is. A projectile that reaches
/// the target stops at its surface; one that hits the environment stops short of it, toward
/// the caster. Both conditions must hold, so a large monster (its surface a few metres from its
/// centre) isn't read as a wall. The caller also requires that no hit, resist or evade line
/// arrived for the cast: that is the final word for a large monster or an odd stop.
/// </summary>
public static class ProjectileImpactJudge
{
/// <summary>A stop farther than this from the target's centre didn't touch it.</summary>
public const double MissRadiusMeters = 4.0;
/// <summary>A stop at least this much nearer to the caster than the target is "short".</summary>
public const double ShortByMeters = 2.0;
/// <summary>A projectile that flew less than this never really left (or was never ours).</summary>
public const double MinTravelMeters = 1.0;
/// <summary>True when the projectile stopped short of the target and away from it.</summary>
public static bool StoppedShort(double impactToTarget, double casterToImpact, double casterToTarget)
{
if (!double.IsFinite(impactToTarget) || !double.IsFinite(casterToImpact) || !double.IsFinite(casterToTarget))
return false;
return impactToTarget > MissRadiusMeters && casterToImpact + ShortByMeters < casterToTarget;
}
}

View file

@ -0,0 +1,79 @@
using System;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi;
// ============================================================================
// Per-monster kite / pull-away (2026-10-16): MonsterRule.Kite.
//
// Default the DEFAULT line's choice; on the DEFAULT line, Off (fight in place)
// Off engage and kill where the mob stands
// PullAway after a brief tag, run away until the mob has been pulled
// KitePullMeters from its lock-spot origin, then kill it alone
//
// Resolution matches AttackPowerModes: a rule's own value wins; "Default" falls
// through to the DEFAULT row; blank/unknown is Default (→ Off via the DEFAULT row).
// ============================================================================
/// <summary>Names and resolution of <see cref="MonsterRule.Kite"/>.</summary>
public static class KiteModes
{
public const string Default = "Default";
public const string Off = "Off";
public const string PullAway = "PullAway";
/// <summary>Every choice, in the order the editors list them.</summary>
public static readonly string[] All = { Default, Off, PullAway };
/// <summary>Combo labels (plugin Advanced + engine Monsters/Damage panels).</summary>
public static readonly string[] DisplayNames = { "Default", "Off", "Pull away" };
/// <summary>A saved value as one of <see cref="All"/>; blank or unknown is Default.</summary>
public static string Normalize(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return Default;
string v = value.Trim();
foreach (string m in All)
if (m.Equals(v, StringComparison.OrdinalIgnoreCase)) return m;
// Hand-typed / UI spellings: "Pull away", "pull-away", "Kite".
string squeezed = v.Replace(" ", "").Replace("-", "").Replace("_", "");
if (squeezed.Equals("PullAway", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Kite", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Pull", StringComparison.OrdinalIgnoreCase))
return PullAway;
if (squeezed.Equals("None", StringComparison.OrdinalIgnoreCase)
|| squeezed.Equals("Disabled", StringComparison.OrdinalIgnoreCase))
return Off;
return Default;
}
/// <summary>
/// The mode that applies to a monster: its own rule's, else the DEFAULT line's.
/// On the DEFAULT line, Default resolves to Off (safe: no pull until the player opts in).
/// </summary>
public static string Effective(MonsterRule? rule, MonsterRule? defaultRule)
{
string own = Normalize(rule?.Kite);
if (own != Default) return own;
// The DEFAULT row itself: Default means Off.
if (rule != null && defaultRule != null
&& ReferenceEquals(rule, defaultRule))
return Off;
if (rule != null && string.Equals(rule.Name, "Default", StringComparison.OrdinalIgnoreCase))
return Off;
string fromDefault = Normalize(defaultRule?.Kite);
return fromDefault == Default ? Off : fromDefault;
}
/// <summary>True when combat should pull this monster before finishing it.</summary>
public static bool WantsPullAway(MonsterRule? rule, MonsterRule? defaultRule)
=> Effective(rule, defaultRule) == PullAway;
/// <summary>Label for logs and tooltips.</summary>
public static string Name(string? value) => Normalize(value) switch
{
PullAway => "Pull away",
Off => "Off",
_ => "Default",
};
}

View file

@ -54,6 +54,17 @@ public class MissileCraftingManager
private const int EQUIP_DELAY_MS = 500;
private const int ERROR_BACKOFF_MS = 60000;
// An ammo wield the server ignores (ammo that doesn't fit the launcher really in hand) came
// round again every AMMO_CHECK_INTERVAL_MS, and each try stopped nav while it waited for the
// answer: Silentkelpie stood still ~3.5 s of every 5 on 2026-10-15. The same item sent more
// than MAX_EQUIP_REPEATS times inside EQUIP_REPEAT_WINDOW_MS backs off instead.
private const int EQUIP_REPEAT_WINDOW_MS = 30000;
private const int MAX_EQUIP_REPEATS = 2;
private const int EQUIP_IGNORED_BACKOFF_MS = 120000;
private int _lastEquipSentId;
private DateTime _lastEquipSentAt = DateTime.MinValue;
private int _equipRepeats;
private int _headBundleId = 0;
private int _shaftBundleId = 0;
private AmmoRecipe? _currentRecipe = null;
@ -145,13 +156,15 @@ public class MissileCraftingManager
_lastAmmoCheck = DateTime.Now;
var inv = GetInventory(forceRefresh: true);
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category))
if (!TryGetWieldedMissileCategory(inv, out WeaponCategory category, out WorldObject? launcher))
return;
_lastWeaponCategory = category;
if (HasWieldedAmmo(inv, category))
return;
_host.Log($"[RynthAi] MissileCraft: no {GetCategoryLabel(category)} wielded with launcher " +
$"0x{launcher!.Id:X8} '{launcher.Name}' (slot {launcher.WieldedLocation}); evaluating");
ChatLog($"No wielded {GetCategoryLabel(category)}s. Evaluating...");
SetState(CraftState.Evaluating);
}
@ -350,6 +363,18 @@ public class MissileCraftingManager
if (targetId != 0)
{
if (!NoteEquipSent(targetId))
{
string name = inv.FirstOrDefault(i => i.Id == targetId)?.Name ?? $"0x{targetId:X8}";
string why = $"The server didn't wield {name} after {MAX_EQUIP_REPEATS} tries; " +
$"leaving the ammo alone for {EQUIP_IGNORED_BACKOFF_MS / 60000} minutes";
_host.Log($"[RynthAi] MissileCraft: {why} (0x{targetId:X8})");
Reset(why);
_equipRepeats = 0;
_lastAmmoCheck = DateTime.Now.AddMilliseconds(EQUIP_IGNORED_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
return;
}
_host.UseFor((uint)targetId, "Crafting", "missile crafting: wield the new ammo");
ChatLog($"Equipped ammo (id=0x{targetId:X8})");
Reset($"Done: {_currentRecipe?.OutputName ?? "ammo"}");
@ -382,9 +407,9 @@ public class MissileCraftingManager
private List<WorldObject> GetInventory(bool forceRefresh = false)
=> _objectCache?.GetDirectInventory(forceRefresh).ToList() ?? new();
private WeaponCategory ResolveWeaponCategory(IEnumerable<WorldObject> inventory)
private WeaponCategory ResolveWeaponCategory(List<WorldObject> inventory)
{
if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category))
if (TryGetWieldedMissileCategory(inventory, out WeaponCategory category, out _))
{
_lastWeaponCategory = category;
return category;
@ -393,24 +418,29 @@ public class MissileCraftingManager
return _lastWeaponCategory;
}
private bool TryGetWieldedMissileCategory(IEnumerable<WorldObject> inventory, out WeaponCategory category)
private bool TryGetWieldedMissileCategory(List<WorldObject> inventory, out WeaponCategory category,
out WorldObject? launcher)
{
foreach (var item in inventory)
foreach (var item in WornCandidates(inventory))
{
if (!IsPlayerWielded(item) || !LooksLikeMissileWeapon(item))
// AC files ammo as a missile weapon: wielded quarrels must not pass for the launcher
// (no "crossbow" in the name reads as a bow, and arrows went on at the crossbow).
if (WorldObjectCache.IsAmmo(item) || !IsPlayerWielded(item) || !LooksLikeMissileWeapon(item))
continue;
category = GetWeaponCategory(item.Name);
launcher = item;
return true;
}
category = WeaponCategory.Bow;
launcher = null;
return false;
}
private bool HasWieldedAmmo(IEnumerable<WorldObject> inventory, WeaponCategory category)
private bool HasWieldedAmmo(List<WorldObject> inventory, WeaponCategory category)
{
foreach (var item in inventory)
foreach (var item in WornCandidates(inventory))
{
if (!IsPlayerWielded(item))
continue;
@ -422,16 +452,62 @@ public class MissileCraftingManager
return false;
}
/// <summary>
/// The direct scan plus the cache-known items it left out. The scan merges worn gear only when
/// its slot reads above 0, and the slot reads 0 for gear wielded after login (a launcher combat
/// swapped in, and its ammo), so the launcher really in hand was missing from the scan alone.
/// </summary>
private IEnumerable<WorldObject> WornCandidates(List<WorldObject> inventory)
{
foreach (var item in inventory)
yield return item;
if (_objectCache == null)
yield break;
var listed = new HashSet<int>(inventory.Select(i => i.Id));
foreach (var item in _objectCache.GetInventory())
if (listed.Add(item.Id))
yield return item;
}
private bool IsPlayerWielded(WorldObject item)
{
if (item.WieldedLocation <= 0)
// Found inside a pack by the direct scan: AC's container lists never hold worn gear. A
// launcher put away after a swap keeps its old wielder and slot in the client's object
// description, so the slot alone said a stowed bow was in hand while a crossbow was, and
// arrows were wielded at it every 5 s (Silentkelpie, 2026-10-15).
if (item.DirectContainerId != 0)
return false;
uint playerId = _host.GetPlayerId();
if (playerId == 0)
return false;
return item.Wielder == 0 || item.Wielder == unchecked((int)playerId);
if (item.WieldedLocation > 0)
return item.Wielder == 0 || item.Wielder == unchecked((int)playerId);
// The slot reads 0 for gear wielded after login; the wielder still names the player.
return _host.HasGetObjectWielderInfo
&& _host.TryGetObjectWielderInfo(unchecked((uint)item.Id), out uint wielder, out _)
&& wielder == playerId;
}
/// <summary>
/// Counts an ammo wield about to go out; false once the same item was already sent
/// <see cref="MAX_EQUIP_REPEATS"/> times inside <see cref="EQUIP_REPEAT_WINDOW_MS"/>.
/// </summary>
private bool NoteEquipSent(int targetId)
{
DateTime now = DateTime.Now;
if (targetId == _lastEquipSentId && (now - _lastEquipSentAt).TotalMilliseconds < EQUIP_REPEAT_WINDOW_MS)
_equipRepeats++;
else
_equipRepeats = 1;
_lastEquipSentId = targetId;
_lastEquipSentAt = now;
return _equipRepeats <= MAX_EQUIP_REPEATS;
}
private static bool LooksLikeMissileWeapon(WorldObject item)

View file

@ -574,6 +574,8 @@ public sealed partial class RynthAiPlugin
public override void OnVendorClose(uint vendorId)
{
_metaManager?.OnVendorClose(vendorId);
// /mt vendor addbuy / addsell lists belong to the vendor that was open.
ClearMtVendorLists();
var autoVendor = _autoVendor;
if (autoVendor != null)

View file

@ -0,0 +1,209 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// Key and mouse input posted to AC's own window, for the Mag-Tools <c>/mt</c> verbs that drive the
/// client directly: <c>send</c>, <c>click</c>, <c>movement</c>, <c>strafe</c>, <c>get xy</c>,
/// <c>client</c>. A port of Mag-Tools' PostMessageTools (Mag-Plugins\Shared\PostMessageTools.cs):
/// the same virtual keys, scan codes (lParam) and click spots, so metas written for Mag-Tools
/// behave the same.
///
/// The window is the one in this process with AC's class ("Turbine Device Class"), found once.
/// PostMessage is safe from any thread; a key held for a time is released by a one-shot timer.
/// </summary>
internal static class GameInput
{
private const uint WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202;
private const byte VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_PAUSE = 0x13,
VK_SPACE = 0x20, VK_DELETE = 0x2E, VK_F4 = 0x73, VK_F12 = 0x7B;
private const int SW_MINIMIZE = 6, SW_RESTORE = 9;
private static IntPtr _hwnd;
// Pending key releases: kept alive until they fire.
private static readonly System.Collections.Generic.List<Timer> Pending = new();
/// <summary>AC's game window in this process, or IntPtr.Zero.</summary>
public static IntPtr GameWindow
{
get
{
if (_hwnd != IntPtr.Zero && IsWindow(_hwnd)) return _hwnd;
// Every top-level AC window on the desktop, keeping this process's (several clients run).
// FindWindowEx rather than EnumWindows: no callback delegate to marshal under NativeAOT.
uint pid = (uint)Environment.ProcessId;
IntPtr found = IntPtr.Zero, h = IntPtr.Zero;
for (int i = 0; i < 64; i++)
{
h = FindWindowEx(IntPtr.Zero, h, "Turbine Device Class", null);
if (h == IntPtr.Zero) break;
GetWindowThreadProcessId(h, out uint p);
if (p == pid) { found = h; break; }
}
_hwnd = found;
return found;
}
}
public static bool Available => GameWindow != IntPtr.Zero;
// ── Keys (Mag-Tools PostMessageTools) ──────────────────────────────────────
public static void SendEnter() => Key(VK_RETURN, 0x001C0001, 0xC01C0001);
public static void SendPause() => Key(VK_PAUSE, 0x00450001, 0xC0450001);
public static void SendDel() => Key(VK_DELETE, 0x01530001, 0x01530001);
/// <summary>F4: opens / closes the fellowship panel.</summary>
public static void SendF4() => Key(VK_F4, 0x003E0001, 0xC03E0001);
/// <summary>F12: opens / closes the main pack.</summary>
public static void SendF12() => Key(VK_F12, 0x00580001, 0xC0580001);
/// <summary>Ctrl + a letter.</summary>
public static void SendCntrl(char ch)
{
Post(WM_KEYDOWN, VK_CONTROL, 0x001D0001);
Post(WM_KEYDOWN, CharCode(ch), 0x00100001);
Post(WM_KEYUP, CharCode(ch), 0xC0100001);
Post(WM_KEYUP, VK_CONTROL, 0xC01D0001);
}
/// <summary>Types <paramref name="msg"/> key by key (letters, space and "/"; as Mag-Tools).</summary>
public static void SendMsg(string msg)
{
foreach (char ch in msg)
{
uint lparam = (uint)((ScanCode(ch) << 16) | 1);
Post(WM_KEYDOWN, CharCode(ch), lparam);
Post(WM_KEYUP, CharCode(ch), 0xC0000000 | lparam);
}
}
/// <summary>Space (a jump), held <paramref name="msToHoldDown"/> ms, with the shift / w z x c keys
/// pressed as it is released (Mag-Tools /mt jump).</summary>
public static void SendSpace(int msToHoldDown = 0, bool shift = false, bool w = false, bool z = false, bool x = false, bool c = false)
{
Post(WM_KEYDOWN, VK_SPACE, 0x00390001);
void Release()
{
if (shift) Post(WM_KEYDOWN, VK_SHIFT, 0x002A0001);
if (w) Post(WM_KEYDOWN, CharCode('w'), 0x00110001);
if (z) Post(WM_KEYDOWN, CharCode('z'), 0x002C0001);
if (x) Post(WM_KEYDOWN, CharCode('x'), 0x002D0001);
if (c) Post(WM_KEYDOWN, CharCode('c'), 0x002E0001);
Post(WM_KEYUP, VK_SPACE, 0xC0390001);
if (w) Post(WM_KEYUP, CharCode('w'), 0xC0110001);
if (z) Post(WM_KEYUP, CharCode('z'), 0xC02C0001);
if (x) Post(WM_KEYUP, CharCode('x'), 0xC02D0001);
if (c) Post(WM_KEYUP, CharCode('c'), 0xC02E0001);
if (shift) Post(WM_KEYUP, VK_SHIFT, 0xC02A0001);
}
After(msToHoldDown, Release);
}
/// <summary>A movement key (a letter of AC's keymap) held <paramref name="msToHoldDown"/> ms.</summary>
public static void SendMovement(char ch, int msToHoldDown = 0)
{
uint scan = (uint)ScanCode(ch) * 0x10000;
Post(WM_KEYDOWN, CharCode(ch), 0x00000001 + scan);
After(msToHoldDown, () => Post(WM_KEYUP, CharCode(ch), 0xC0000001 + scan));
}
// ── Mouse ─────────────────────────────────────────────────────────────────
/// <summary>A left click at window coordinates (<paramref name="x"/>, <paramref name="y"/>).</summary>
public static void SendMouseClick(int x, int y)
{
uint loc = (uint)((y << 16) | (x & 0xFFFF));
Post(WM_MOUSEMOVE, 0, loc);
Post(WM_LBUTTONDOWN, 1, loc);
Post(WM_LBUTTONUP, 0, loc);
}
// AC's confirmation box buttons, relative to the window's centre. Three heights each, as Mag-Tools:
// windowed and windowless clients put the box a few pixels apart.
public static void ClickOK() => ClickCentre(0);
public static void ClickYes() => ClickCentre(-80);
public static void ClickNo() => ClickCentre(80);
private static void ClickCentre(int dx)
{
if (!GetWindowRect(GameWindow, out RECT r)) return;
int w = r.Right - r.Left, h = r.Bottom - r.Top;
foreach (int dy in new[] { 18, 25, 31 })
SendMouseClick(w / 2 + dx, h / 2 + dy);
}
/// <summary>The cursor relative to the game window's top-left (Mag-Tools /mt get xy), or false.</summary>
public static bool TryCursorInWindow(out int x, out int y)
{
x = y = 0;
if (!GetCursorPos(out POINT p) || !GetWindowRect(GameWindow, out RECT r)) return false;
x = p.X - r.Left;
y = p.Y - r.Top;
return true;
}
// ── Window ───────────────────────────────────────────────────────────────
public static bool Minimize() => ShowWindow(GameWindow, SW_MINIMIZE);
public static bool Restore() => ShowWindow(GameWindow, SW_RESTORE);
// ── Internals ────────────────────────────────────────────────────────────
private static void Key(byte vk, uint down, uint up)
{
Post(WM_KEYDOWN, vk, down);
Post(WM_KEYUP, vk, up);
}
private static void Post(uint msg, uint wParam, uint lParam)
{
IntPtr h = GameWindow;
if (h != IntPtr.Zero) PostMessage(h, msg, (IntPtr)wParam, (IntPtr)unchecked((int)lParam));
}
/// <summary>Runs <paramref name="action"/> now, or after <paramref name="ms"/> on a one-shot timer.</summary>
private static void After(int ms, Action action)
{
if (ms <= 0) { action(); return; }
Timer? t = null;
t = new Timer(_ =>
{
try { action(); }
catch (Exception ex) { Debug.WriteLine("GameInput release failed: " + ex.Message); }
finally { lock (Pending) { if (t != null) Pending.Remove(t); } t?.Dispose(); }
}, null, Timeout.Infinite, Timeout.Infinite);
lock (Pending) Pending.Add(t);
t.Change(ms, Timeout.Infinite);
}
private static byte ScanCode(char ch) => char.ToLowerInvariant(ch) switch
{
'a' => 0x1E, 'b' => 0x30, 'c' => 0x2E, 'd' => 0x20, 'e' => 0x12, 'f' => 0x21, 'g' => 0x22, 'h' => 0x23,
'i' => 0x17, 'j' => 0x24, 'k' => 0x25, 'l' => 0x26, 'm' => 0x32, 'n' => 0x31, 'o' => 0x18, 'p' => 0x19,
'q' => 0x10, 'r' => 0x13, 's' => 0x1F, 't' => 0x14, 'u' => 0x16, 'v' => 0x2F, 'w' => 0x11, 'x' => 0x2D,
'y' => 0x15, 'z' => 0x2C, '/' => 0x35, ' ' => 0x39,
_ => 0,
};
private static byte CharCode(char ch)
{
char c = char.ToLowerInvariant(ch);
if (c >= 'a' && c <= 'z') return (byte)(0x41 + (c - 'a'));
return c == '/' ? (byte)0xBF : (byte)0x20;
}
[StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
[DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string? title);
[DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
[DllImport("user32.dll")] private static extern bool IsWindow(IntPtr hWnd);
[DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p);
[DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int cmd);
}

View file

@ -579,7 +579,7 @@ internal sealed class HudController
/// Mini Remote drawer, or with <paramref name="window"/> the engine's Mini Remote window)
/// and returns the content size it wants. Render thread.
/// </summary>
public System.Numerics.Vector2 RenderEmbedded(bool window = false, bool tabs = true)
public System.Numerics.Vector2 RenderEmbedded(bool window = false, bool tabs = true, bool popped = false)
{
long now = NowMs;
System.Threading.Interlocked.Exchange(ref _embeddedDrawnAt, now);
@ -587,7 +587,7 @@ internal sealed class HudController
int pushed = LegacyDashboardRenderer.PushDashboardStyle();
try
{
return _miniRemote.RenderEmbedded(window, tabs);
return _miniRemote.RenderEmbedded(window, tabs, popped);
}
finally
{

View file

@ -60,7 +60,7 @@ internal sealed class HudSetupUi
private void RenderItemLists(HudState s)
{
ImGui.TextWrapped("Left = shown on the HUD. Right = in your pack but not on the HUD. "
SafeImGui.TextWrapped("Left = shown on the HUD. Right = in your pack but not on the HUD. "
+ "< pins the highlighted right row; > removes the highlighted left row. "
+ "Add from inventory uses the item selected in the game.");

View file

@ -38,6 +38,11 @@ public sealed class HudState
public bool MiniShowTarget = true;
/// <summary>Pet row: the summon that is out (health, time left), else the next combat essence.</summary>
public bool MiniShowPet = true;
/// <summary>
/// Pet capture row (ILT / ACECustom): auto-capture enable, lens pick, and status.
/// The same AutoCaptureEnabled setting as Mini Remote > Pets > Monster capture.
/// </summary>
public bool MiniShowCapture = true;
public bool MiniShowGems = true;
public bool MiniShowToggles = true;
public bool MiniShowBank = true;

View file

@ -11,8 +11,9 @@
// Quest Timers and Fellowship, Skills, Inventory, Item Count, Inventory HUDs: windows every server
// has), then "Server: <name>", i.e. the installed server plugins' windows for the world you're on,
// which RynthCore sends (ServerMenuModel), or a link to RynthCore's Options > Diagnostics (where a
// server is forced) when none matches. The Options button opens RynthAi Settings; right-click it for
// the Mini Remote's own section/layout settings.
// server is forced) when none matches. Options: docked left-click opens RynthAi Settings
// (right-click = Mini Remote section/layout popup); undocked left-click opens that expanded
// Options popup. Float / Dock next to Options (and in the popup) call /rc miniremote undock|dock.
// The V/H button stacks the sections (vertical) or lays them out in three columns (horizontal).
//
// Remote sections (each can be hidden from the Options menu):
@ -74,6 +75,7 @@ internal sealed class MiniRemoteHud
private bool _columnOpen; // horizontal layout: a column was already started this frame (next one goes SameLine)
private bool _embedded; // true only inside RenderEmbedded (an engine surface)
private bool _inWindow; // with _embedded: the engine's Mini Remote window, not the dashboard drawer
private bool _popped; // engine Mini Remote is in its own floating window (:popout)
// A tab switch asked for by a command or the engine (any thread), applied by the next tab bar;
// null = none. Starts as the saved tab so the first tab bar restores it.
private string? _pendingTab;
@ -139,12 +141,13 @@ internal sealed class MiniRemoteHud
/// themselves from the result) instead of a window of their own. Returns the content size it
/// wants: the selected tab's width, and the height drawn.
/// </summary>
public Vector2 RenderEmbedded(bool window = false, bool tabs = true)
public Vector2 RenderEmbedded(bool window = false, bool tabs = true, bool popped = false)
{
var s = _hud.State;
_slotMenuIndex = -1;
_embedded = true;
_inWindow = window;
_popped = popped;
float startY = ImGui.GetCursorPosY();
ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(4, 3));
try
@ -166,6 +169,7 @@ internal sealed class MiniRemoteHud
_slotMenuIndex = -1;
_embedded = false;
_inWindow = false;
_popped = false;
}
}
@ -308,7 +312,7 @@ internal sealed class MiniRemoteHud
float colW = ColumnWidth(s);
if (!s.MiniRemoteHorizontal) return colW;
int cols = 0;
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet) cols++;
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet || s.MiniShowCapture) cols++;
if (s.MiniShowGems || ShowToggles(s)) cols++;
if (s.MiniShowBank || s.MiniShowRebuff || s.MiniShowTranslate || s.MiniShowGuardian) cols++;
cols = Math.Max(1, cols);
@ -317,7 +321,7 @@ internal sealed class MiniRemoteHud
// ── Layout ──────────────────────────────────────────────────────────────
/// <summary>[V/H] and [Options] buttons. Fixed widths so the auto-resizing window can't grow from them.</summary>
/// <summary>[V/H], [Options], and (engine window) Dock/Float buttons. Fixed widths so auto-resize can't grow from them.</summary>
private void RenderHeaderRow(HudState s)
{
if (ImGui.Button((s.MiniRemoteHorizontal ? "H" : "V") + "##mrlayout", new Vector2(HeaderButtonWidth, 0)))
@ -325,15 +329,34 @@ internal sealed class MiniRemoteHud
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(s.MiniRemoteHorizontal ? "Horizontal: sections in columns. Click to stack them." : "Vertical: sections stacked. Click to lay them out in columns.");
ImGui.SameLine();
// Left-click: RynthAi Settings. Right-click: Mini Remote section/layout popup (RenderOptions).
// Undocked: left-click opens the expanded Mini Remote Options popup (sections / layout).
// Docked: left-click opens RynthAi Settings; right-click always opens the Options popup.
if (ImGui.Button("Options##mropts", new Vector2(HeaderButtonWidth, 0)))
{
if (_hud.Host.HasInvokeChatParser) _hud.RunEngineCommand(MovedTabs.Settings);
else _openOptions = true; // no chat parser: fall back to the Mini Remote popup
if (_popped || !_hud.Host.HasInvokeChatParser)
_openOptions = true;
else
_hud.RunEngineCommand(MovedTabs.Settings);
}
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _openOptions = true;
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("Open RynthAi Settings (Advanced Settings).\nRight-click: Mini Remote sections, layout, slot size.");
{
SafeImGui.SetTooltip(_popped
? "Mini Remote sections, layout, slot size (undocked).\nSettings is in this Options menu."
: "Open RynthAi Settings (Advanced Settings).\nRight-click: Mini Remote sections, layout, slot size.\nUse Float to undock for a larger Options window.");
}
// Engine Mini Remote window only: dock / undock without hunting the title ↗.
if (_inWindow && _hud.Host.HasInvokeChatParser)
{
ImGui.SameLine();
string dockLabel = _popped ? "Dock" : "Float";
if (ImGui.Button(dockLabel + "##mrdock", new Vector2(HeaderButtonWidth, 0)))
_hud.RunEngineCommand(_popped ? "/rc miniremote dock" : "/rc miniremote undock");
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(_popped
? "Dock Mini Remote back into the game window (/rc miniremote dock)."
: "Undock Mini Remote into a floating window for expanded Options (/rc miniremote undock).");
}
}
private void RenderVertical(HudState s, MiniRemoteController? remote)
@ -353,7 +376,7 @@ internal sealed class MiniRemoteHud
{
float colW = ColumnWidth(s);
_columnOpen = false;
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet)
if (s.MiniShowStats || s.MiniShowTarget || s.MiniShowPet || s.MiniShowCapture)
{
BeginColumn("##mrcolstatus", colW);
RenderStatusSections(s, remote);
@ -409,6 +432,7 @@ internal sealed class MiniRemoteHud
if (s.MiniShowStats) RenderStats(remote);
if (s.MiniShowTarget) RenderTarget(combat);
if (s.MiniShowPet) RenderPet(remote, combat);
if (s.MiniShowCapture) RenderCapture(remote);
if (s.MiniShowStats) RenderStatButtons(remote);
}
@ -549,6 +573,42 @@ internal sealed class MiniRemoteHud
SafeImGui.TextColored(col, status);
}
/// <summary>
/// ILT siphon-lens auto-capture: same enable / lens as Pets > Monster capture, on the Remote
/// so Options > Pet capture can show it without opening the Pets tab.
/// </summary>
private static void RenderCapture(MiniRemoteController? remote)
{
if (!IltActive(remote))
{
ImGui.TextDisabled("Capture: ILT only");
return;
}
var pets = remote!.Pets;
bool captureOff = remote.Ilt.IsOff(RynthIltHub.FeatureMonsterCapture);
ImGui.BeginDisabled(captureOff);
bool en = pets.AutoCaptureEnabled;
if (ImGui.Checkbox("Auto-capture##mrcapture", ref en))
pets.AutoCaptureEnabled = en;
if (ImGui.IsItemHovered())
{
SafeImGui.SetTooltip(
"Uses the selected siphon lens on the nearest attackable creature within 5 m once it is\n" +
"at or below 20% health or under 20 HP (ACECustom MonsterCapture). Asheron's Lens skips\n" +
"the health gate. Same setting as Mini Remote > Pets > Monster capture.");
}
ImGui.SameLine();
ImGui.SetNextItemWidth(110);
int lens = Math.Clamp(pets.CaptureLensIndex, 0, PetCaptureRules.LensNames.Length - 1);
if (ImGui.Combo("##mrcapturelens", ref lens, PetCaptureRules.LensNames, PetCaptureRules.LensNames.Length))
pets.CaptureLensIndex = lens;
ImGui.EndDisabled();
if (captureOff)
SafeImGui.TextDisabled("Capture disabled on this server");
else
SafeImGui.TextDisabled(pets.CaptureStatus);
}
private static void RenderSummon(MiniRemoteController? remote, CombatHudSnapshot c)
{
ImGui.TextColored(ColLabel, "Summon:");
@ -800,6 +860,7 @@ internal sealed class MiniRemoteHud
Flag("Session stats", ref s.MiniShowStats);
Flag("Attack target", ref s.MiniShowTarget);
Flag("Pet / summon", ref s.MiniShowPet);
Flag("Pet capture", ref s.MiniShowCapture);
Flag("Item slots", ref s.MiniShowGems);
// The drawer's dashboard has these switches already; the setting is for the windows.
if (!InDrawer) Flag("Toggles", ref s.MiniShowToggles);
@ -812,6 +873,21 @@ internal sealed class MiniRemoteHud
RenderSlotSizeSlider(s);
if (embedded && _inWindow)
{
// Docked Options used to jump straight to Settings; undocked left-click opens this
// popup, so keep a Settings entry here.
if (_popped && _hud.Host.HasInvokeChatParser
&& ImGui.MenuItem("RynthAi Settings...", MovedTabs.Settings))
_hud.RunEngineCommand(MovedTabs.Settings);
if (_hud.Host.HasInvokeChatParser)
{
if (ImGui.MenuItem(_popped ? "Dock Mini Remote" : "Undock Mini Remote",
_popped ? "/rc miniremote dock" : "/rc miniremote undock"))
_hud.RunEngineCommand(_popped ? "/rc miniremote dock" : "/rc miniremote undock");
if (ImGui.IsItemHovered())
ImGui.SetTooltip(_popped
? "Dock back into the game window."
: "Pop out so this Options menu has more room.");
}
if (ImGui.MenuItem("Inventory HUDs setup...")) s.ShowSetup = true;
}
else if (embedded)

View file

@ -34,8 +34,59 @@ internal sealed class Jumper
private bool _pausedNav;
private bool _prevEnableNavigation;
// Face only (/mt face, /ub face; ub-IT's DoFace): navigation is held while turning, the turn
// is sent again every 100 ms until the heading is within 1 degree, and given up after 5 s.
private bool _faceOnly;
private DateTime _lastFaceTurnAt;
private const double FaceToleranceDeg = 1.0;
private static readonly TimeSpan FaceRetry = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan FaceTimeout = TimeSpan.FromSeconds(5);
public bool IsBusy => _isTurning || _needToJump || _charging || _waitingForJump;
/// <summary>Turns to <paramref name="heading"/> (any degrees; normalized to 0-360), holding nav meanwhile.</summary>
public bool Face(double heading)
{
if (IsBusy && !_faceOnly)
{
_chat("[RynthAi] You are jumping. Try again later.");
return false;
}
if (!_host.HasTurnToHeading)
{
_chat("[RynthAi] TurnToHeading not available.");
return false;
}
_targetHeading = (float)(((heading % 360) + 360) % 360);
if (!_faceOnly) PauseNav();
_faceOnly = true;
_isTurning = true;
_turningStartedAt = _lastFaceTurnAt = DateTime.UtcNow;
_host.TurnToHeadingBy("Face", _targetHeading);
RynthLog.Write(LogCat.Jumper, $"[Jumper] Face -> {_targetHeading:F1}");
return true;
}
/// <summary>The face turn: done within <see cref="FaceToleranceDeg"/>, else turn again; nav back when done.</summary>
private void TickFace()
{
DateTime now = DateTime.UtcNow;
if (now - _lastFaceTurnAt < FaceRetry) return;
_lastFaceTurnAt = now;
bool read = _host.TryGetPlayerHeading(out float current);
double off = read ? Math.Abs(((current - _targetHeading) % 360 + 540) % 360 - 180) : 0;
if (read && off >= FaceToleranceDeg && now - _turningStartedAt < FaceTimeout)
{
_host.TurnToHeadingBy("Face", _targetHeading);
return;
}
_isTurning = _faceOnly = false;
RestoreNav();
RynthLog.Write(LogCat.Jumper, read && off >= FaceToleranceDeg
? $"[Jumper] Face {_targetHeading:F1}: still {off:F1} deg off after {FaceTimeout.TotalSeconds:0} s, gave up"
: $"[Jumper] Face {_targetHeading:F1} done (heading {(read ? current.ToString("F1") : "?")})");
}
public Jumper(RynthCoreHost host, LegacyUiSettings settings, Action<string> chat)
{
_host = host;
@ -45,6 +96,12 @@ internal sealed class Jumper
public bool Start(string directionLetters, float? faceHeading, int msToHoldDown)
{
// A face still turning (a meta's "/mt face 90" then "/ub jumpw 90") gives way to the jump.
if (_faceOnly)
{
_faceOnly = _isTurning = false;
RestoreNav();
}
if (IsBusy)
{
_chat("[RynthAi] You are already jumping. Try again later.");
@ -101,7 +158,7 @@ internal sealed class Jumper
public void Cancel()
{
RestoreNav();
_isTurning = _needToJump = _charging = _waitingForJump = false;
_isTurning = _needToJump = _charging = _waitingForJump = _faceOnly = false;
_addW = _addX = _addZ = _addC = _addShift = false;
}
@ -111,6 +168,11 @@ internal sealed class Jumper
try
{
if (_faceOnly)
{
TickFace();
return;
}
// TurnToHeading is an instant quaternion snap; the heading read
// doesn't always reflect it immediately, so just wait a short
// settle window rather than polling for a match.

View file

@ -15,6 +15,30 @@ internal sealed class LegacyAdvancedSettingsUi
// Server Features list being edited (committed on Enter / focus loss); null = show the saved list.
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
/// <summary>
/// The environment-impact throttle's shared numbers (one set for missiles and magic), drawn
/// under each response combo. <paramref name="id"/> keeps the two copies' ImGui ids apart.
/// </summary>
private void DrawEnvironmentThrottleKnobs(string id)
{
ImGui.Indent();
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Hits to trip##envlimit{id}", ref _settings.EnvironmentImpactLimit, 1, 10);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Environment hits on one target, within the window, before combat reacts.\nShared by missiles and magic.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Window (s)##envwin{id}", ref _settings.EnvironmentImpactWindowSec, 5, 120);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Move closer by (m)##envstep{id}", ref _settings.EnvironmentApproachMeters, 1, 30);
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Closest (m)##envmin{id}", ref _settings.EnvironmentMinDistance, 1, 30);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Never moves nearer than this. Already this close, a new target is picked instead.");
ImGui.SetNextItemWidth(120);
ImGui.SliderInt($"Skip target (s)##envskip{id}", ref _settings.EnvironmentSkipSec, 5, 300);
ImGui.Unindent();
}
private static readonly string[] NavLabelModeNames = { "Off", "Numbers", "Numbers and names" };
private const string NavResumeNearestTip =
"On: starting the macro, loading a Circular or Linear route, and carrying on after a fight, loot, buff or door\n" +
@ -210,12 +234,12 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.InputInt(label, ref value);
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip(tip);
ImGui.SetTooltip(tip);
ImGui.SameLine();
if (value == baseline)
ImGui.TextDisabled("baseline");
else
SafeImGui.TextColored(new Vector4(0.9f, 0.7f, 0.2f, 1.0f), $"baseline {baseline}");
ImGui.TextColored(new Vector4(0.9f, 0.7f, 0.2f, 1.0f), $"baseline {baseline}");
}
/// <summary>Writes the six loot timers' baseline values (LootBaseline.cs) into the settings.</summary>
@ -521,6 +545,45 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetNextItemWidth(120);
ImGui.Combo("Missile Attack Height", ref _settings.MissileAttackHeight, AttackHeights, AttackHeights.Length);
ImGui.Spacing();
ImGui.Text("Variable Power (monster rules)");
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("A monster rule's Power column picks per monster: Default (these settings),\n" +
"High (100%), Reckless (80%, needs Recklessness trained), Variable (a new\n" +
"random power each attack in this range), or Reckless + Variable (random,\n" +
"kept inside the Recklessness band 20-80%).");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Variable Min %", ref _settings.VariablePowerMin, 0, 100);
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Variable Max %", ref _settings.VariablePowerMax, 0, 100);
ImGui.Spacing();
ImGui.Text("Missiles Hitting the Environment");
ImGui.SetNextItemWidth(220);
ImGui.Combo("Missile Response", ref _settings.MissileEnvironmentResponse,
EnvironmentImpactPlanner.ResponseNames, EnvironmentImpactPlanner.ResponseNames.Length);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When arrows or bolts keep hitting walls or objects instead of the target\n" +
"(\"Your missile attack hit the environment.\"), stop shooting and:\n" +
" Move closer - run toward the target for a clearer shot\n" +
" New target - skip this one for a while and fight another\n" +
" Move closer, then new target - one approach, then switch\n" +
"The only monster in reach is never skipped.");
DrawEnvironmentThrottleKnobs("missile");
ImGui.Spacing();
ImGui.Text("Pull Away (Kite)");
ImGui.SetNextItemWidth(150);
ImGui.SliderInt("Pull Distance (m)", ref _settings.KitePullMeters, 3, 100);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When a monster rule's Kite is Pull away (or Default follows the\n" +
"DEFAULT row set to Pull away), tag the mob then run until it has\n" +
"been dragged this many metres from where it stood, then kill it.\n" +
"Set per mob on the Monsters / Damage panels.");
ImGui.Checkbox("Tag Before Fleeing", ref _settings.KiteTagFirst);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Land a hit before running so aggro sticks. Off = flee as soon as locked.");
ImGui.Spacing();
ImGui.Text("Weapon Swaps");
ImGui.SetNextItemWidth(150);
@ -618,6 +681,20 @@ internal sealed class LegacyAdvancedSettingsUi
"The character turns to face the target first. 0 = no walls.");
ImGui.InputInt("Min Wall Targets", ref _settings.MinWallTargets);
ImGui.Spacing();
ImGui.Text("Spells Hitting the Environment");
ImGui.SetNextItemWidth(220);
ImGui.Combo("Magic Response", ref _settings.MagicEnvironmentResponse,
EnvironmentImpactPlanner.ResponseNames, EnvironmentImpactPlanner.ResponseNames.Length);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("When bolts, streaks, arcs or blasts keep stopping short of the target\n" +
"(a wall, a pillar, the ceiling) with no hit or resist, stop casting and:\n" +
" Move closer - run toward the target for a clearer line\n" +
" New target - skip this one for a while and fight another\n" +
" Move closer, then new target - one approach, then switch\n" +
"Rings and walls aren't judged. The only monster in reach is never skipped.");
DrawEnvironmentThrottleKnobs("magic");
ImGui.Spacing();
ImGui.Separator();
ImGui.Text("Spell Difficulty (Min Buffed Skill)");

View file

@ -391,19 +391,32 @@ internal sealed partial class LegacyDashboardRenderer
CopySettings(new LegacyUiSettings(), _settings);
_lastSavedJson = string.Empty;
}
else if (TryReadProfile(_settingsFilePath, out LegacyUiSettings? loaded, out string loadedJson, out string readError))
{
CopySettings(loaded!, _settings);
_lastSavedJson = loadedJson;
}
else if (TryReadProfile(_settingsFilePath + BackupSuffix, out LegacyUiSettings? fromBak, out string bakJson, out _))
{
// The profile didn't read (cut off by a client that died mid-save, say): the copy
// kept by the last good save is used, and saved back as the profile on the next change.
CopySettings(fromBak!, _settings);
_lastSavedJson = bakJson;
KeepUnreadableProfile(_settingsFilePath);
_host.Log($"[RynthAi] Settings: {_settingsFilePath} didn't read ({readError}); loaded the backup instead.");
_host.WriteToChat($"[RynthAi] Your settings file didn't read ({readError}); restored the backup copy.", 1);
}
else
{
try
{
string json = File.ReadAllText(_settingsFilePath);
var loaded = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
if (loaded != null)
{
CopySettings(loaded, _settings);
_lastSavedJson = json;
}
}
catch { }
// Neither reads. Before, the defaults kept here were autosaved over the profile at once,
// so one bad read reset the character for good. Now the file is set aside and nothing is
// written until a setting is actually changed.
CopySettings(new LegacyUiSettings(), _settings);
KeepUnreadableProfile(_settingsFilePath);
try { _lastSavedJson = JsonSerializer.Serialize(_settings, RynthAiJsonContext.Default.LegacyUiSettings); }
catch { _lastSavedJson = string.Empty; }
_host.Log($"[RynthAi] Settings: {_settingsFilePath} didn't read ({readError}) and there's no good backup; using defaults without saving over it.");
_host.WriteToChat($"[RynthAi] Your settings file didn't read ({readError}). A copy was kept next to it (.unreadable); defaults are in use until you change something.", 1);
}
_packSetup = freshProfile ? PackSetup.FillNew
: _settings.ProfileItemsChecked ? PackSetup.None : PackSetup.CheckExisting;
@ -505,9 +518,51 @@ internal sealed partial class LegacyDashboardRenderer
DataWriteGuard.TrySave("the settings profile", path, () =>
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, json);
// Written beside it and swapped in, the previous file kept as .bak: File.WriteAllText
// emptied the profile first, so a client closed or killed mid-save (relaunching for a
// DXVK change, the launcher's stuck-client kill) left a cut-off file that then loaded
// as defaults.
string tmp = path + "." + Environment.ProcessId + ".tmp";
File.WriteAllText(tmp, json);
if (File.Exists(path)) File.Replace(tmp, path, path + BackupSuffix, ignoreMetadataErrors: true);
else File.Move(tmp, path);
}, out reason, callerShows);
/// <summary>The last good profile kept by each save (profile path + this).</summary>
private const string BackupSuffix = ".bak";
/// <summary>Reads and parses a settings profile; false (with the reason) when it's missing or doesn't parse.</summary>
private static bool TryReadProfile(string path, out LegacyUiSettings? settings, out string json, out string error)
{
settings = null; json = string.Empty; error = "";
try
{
if (!File.Exists(path)) { error = "missing"; return false; }
json = File.ReadAllText(path);
if (string.IsNullOrWhiteSpace(json)) { error = "the file is empty"; return false; }
settings = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.LegacyUiSettings);
if (settings == null) { error = "the file holds no settings"; return false; }
return true;
}
catch (Exception ex)
{
error = ex.GetType().Name + ": " + ex.Message;
return false;
}
}
/// <summary>Copies a profile that didn't read to "&lt;name&gt;.unreadable-&lt;time&gt;" so its contents can be recovered.</summary>
private void KeepUnreadableProfile(string path)
{
try
{
if (!File.Exists(path)) return;
string copy = path + ".unreadable-" + DateTime.Now.ToString("yyyyMMdd-HHmmss");
File.Copy(path, copy, overwrite: false);
}
catch (Exception ex) { _host.Log($"[RynthAi] Settings: keeping a copy of {path} failed: {ex.Message}"); }
}
private static bool WriteSettingsFile(string path, string json) => WriteSettingsFile(path, json, out _);
/// <summary>After a failed autosave, when CheckAndSave may try again (not every tick).</summary>
@ -983,12 +1038,46 @@ internal sealed partial class LegacyDashboardRenderer
incoming.Insert(0, existingDefault ?? new MonsterRule { Name = "Default" });
}
// An engine without the Power column (before 2026-10-12) sends no AttackPower, which
// would reset every rule to Default: keep each rule's own (same name and expression).
if (json.IndexOf("\"AttackPower\"", StringComparison.OrdinalIgnoreCase) < 0)
CarryAttackPower(_settings.MonsterRules, incoming);
// Same for kite (2026-10-16): an older Monsters panel omits Kite and would wipe PullAway.
if (json.IndexOf("\"Kite\"", StringComparison.OrdinalIgnoreCase) < 0)
CarryKite(_settings.MonsterRules, incoming);
_settings.MonsterRules = incoming;
SaveMonstersFile();
}
catch { }
}
/// <summary>Copies AttackPower from <paramref name="current"/> onto the matching rules of
/// <paramref name="incoming"/> (same Name and MatchExpression, case-insensitive).</summary>
internal static void CarryAttackPower(List<MonsterRule> current, List<MonsterRule> incoming)
{
foreach (var r in incoming)
{
var old = current.FirstOrDefault(o =>
string.Equals(o.Name, r.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(o.MatchExpression ?? "", r.MatchExpression ?? "", StringComparison.OrdinalIgnoreCase));
if (old != null) r.AttackPower = old.AttackPower;
}
}
/// <summary>Copies Kite from <paramref name="current"/> onto the matching rules of
/// <paramref name="incoming"/> (same Name and MatchExpression, case-insensitive).</summary>
internal static void CarryKite(List<MonsterRule> current, List<MonsterRule> incoming)
{
foreach (var r in incoming)
{
var old = current.FirstOrDefault(o =>
string.Equals(o.Name, r.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(o.MatchExpression ?? "", r.MatchExpression ?? "", StringComparison.OrdinalIgnoreCase));
if (old != null) r.Kite = old.Kite;
}
}
// ── Settings bridge (engine-side Avalonia SettingsPanel) ─────────────────
public string BuildSettingsJson()
@ -1069,10 +1158,21 @@ internal sealed partial class LegacyDashboardRenderer
UseNativeAttack = s.UseNativeAttack,
SummonPets = s.SummonPets,
PetMinMonsters = s.PetMinMonsters,
// Spell Combat
VariablePowerMin = s.VariablePowerMin,
VariablePowerMax = s.VariablePowerMax,
MissileEnvironmentResponse = s.MissileEnvironmentResponse,
MagicEnvironmentResponse = s.MagicEnvironmentResponse,
EnvironmentImpactLimit = s.EnvironmentImpactLimit,
EnvironmentImpactWindowSec = s.EnvironmentImpactWindowSec,
EnvironmentApproachMeters = s.EnvironmentApproachMeters,
EnvironmentMinDistance = s.EnvironmentMinDistance,
EnvironmentSkipSec = s.EnvironmentSkipSec,
KitePullMeters = s.KitePullMeters,
KiteTagFirst = s.KiteTagFirst,
WeaponSwapSettleMs = s.WeaponSwapSettleMs,
WeaponSwapMinHealthPct = s.WeaponSwapMinHealthPct,
WeaponSwapMinGainPct = s.WeaponSwapMinGainPct,
// Spell Combat
SpellCastIntervalMs = s.SpellCastIntervalMs,
AttackSpellIntervalMs = s.AttackSpellIntervalMs,
CastDispelSelf = s.CastDispelSelf,
@ -1312,10 +1412,22 @@ internal sealed partial class LegacyDashboardRenderer
s.UseNativeAttack = p.UseNativeAttack;
s.SummonPets = p.SummonPets;
s.PetMinMonsters = p.PetMinMonsters;
// Spell Combat
// Absent (an engine without these controls) = unchanged.
if (p.VariablePowerMin is int vpMin) s.VariablePowerMin = vpMin;
if (p.VariablePowerMax is int vpMax) s.VariablePowerMax = vpMax;
if (p.MissileEnvironmentResponse is int envMis) s.MissileEnvironmentResponse = envMis;
if (p.MagicEnvironmentResponse is int envMag) s.MagicEnvironmentResponse = envMag;
if (p.EnvironmentImpactLimit is int envLimit) s.EnvironmentImpactLimit = envLimit;
if (p.EnvironmentImpactWindowSec is int envWin) s.EnvironmentImpactWindowSec = envWin;
if (p.EnvironmentApproachMeters is int envStep) s.EnvironmentApproachMeters = envStep;
if (p.EnvironmentMinDistance is int envMinDist) s.EnvironmentMinDistance = envMinDist;
if (p.EnvironmentSkipSec is int envSkip) s.EnvironmentSkipSec = envSkip;
if (p.KitePullMeters is int kitePull) s.KitePullMeters = Math.Clamp(kitePull, 3, 100);
if (p.KiteTagFirst is bool kiteTag) s.KiteTagFirst = kiteTag;
if (p.WeaponSwapSettleMs is int wsSettle) s.WeaponSwapSettleMs = Math.Clamp(wsSettle, 0, 3000);
if (p.WeaponSwapMinHealthPct is int wsHealth) s.WeaponSwapMinHealthPct = Math.Clamp(wsHealth, 0, 100);
if (p.WeaponSwapMinGainPct is int wsGain) s.WeaponSwapMinGainPct = Math.Clamp(wsGain, 0, 200);
// Spell Combat
s.SpellCastIntervalMs = p.SpellCastIntervalMs;
if (p.AttackSpellIntervalMs is int attackDelay) s.AttackSpellIntervalMs = attackDelay; // absent = unchanged
s.CastDispelSelf = p.CastDispelSelf;
@ -1871,6 +1983,17 @@ internal sealed partial class LegacyDashboardRenderer
dst.MeleeAttackPower = tmp.MeleeAttackPower;
dst.MissileAttackPower = tmp.MissileAttackPower;
dst.UseRecklessness = tmp.UseRecklessness;
dst.VariablePowerMin = tmp.VariablePowerMin;
dst.VariablePowerMax = tmp.VariablePowerMax;
dst.MissileEnvironmentResponse = tmp.MissileEnvironmentResponse;
dst.MagicEnvironmentResponse = tmp.MagicEnvironmentResponse;
dst.EnvironmentImpactLimit = tmp.EnvironmentImpactLimit;
dst.EnvironmentImpactWindowSec = tmp.EnvironmentImpactWindowSec;
dst.EnvironmentApproachMeters = tmp.EnvironmentApproachMeters;
dst.EnvironmentMinDistance = tmp.EnvironmentMinDistance;
dst.EnvironmentSkipSec = tmp.EnvironmentSkipSec;
dst.KitePullMeters = Math.Clamp(tmp.KitePullMeters, 3, 100);
dst.KiteTagFirst = tmp.KiteTagFirst;
dst.WeaponSwapSettleMs = Math.Clamp(tmp.WeaponSwapSettleMs, 0, 3000);
dst.WeaponSwapMinHealthPct = Math.Clamp(tmp.WeaponSwapMinHealthPct, 0, 100);
dst.WeaponSwapMinGainPct = Math.Clamp(tmp.WeaponSwapMinGainPct, 0, 200);

View file

@ -472,6 +472,41 @@ public sealed class LegacyUiSettings
public bool UseNativeAttack = false;
public bool UseRecklessness;
/// <summary>
/// The range a monster rule's "Variable" attack power picks from, in percent of the bar
/// (a new value every swing or shot). "Reckless + Variable" also stays inside the
/// Recklessness band (20-80%). See AttackPowerPlanner.
/// </summary>
public int VariablePowerMin = 50;
public int VariablePowerMax = 100;
// ── Environment hits (2026-10-12, Combat/EnvironmentImpact.cs) ─────────────
/// <summary>
/// What missile combat does once a target has taken EnvironmentImpactLimit "Your missile
/// attack hit the environment." within EnvironmentImpactWindowSec: an EnvironmentResponse
/// (0 Off, 1 Move closer, 2 New target, 3 Move closer then new target). Off by default.
/// </summary>
public int MissileEnvironmentResponse;
/// <summary>The same for war/void casts whose projectiles stop short of the target. Off by default.</summary>
public int MagicEnvironmentResponse;
/// <summary>Environment hits on one target, within the window, that trip the response.</summary>
public int EnvironmentImpactLimit = 2;
/// <summary>The window (seconds) the hits are counted in.</summary>
public int EnvironmentImpactWindowSec = 20;
/// <summary>How far (metres) each "move closer" goes toward the target.</summary>
public int EnvironmentApproachMeters = 6;
/// <summary>Never approaches nearer than this (metres); already this close, a new target is picked.</summary>
public int EnvironmentMinDistance = 3;
/// <summary>How long (seconds) a target left for its environment hits is skipped.</summary>
public int EnvironmentSkipSec = 30;
/// <summary>
/// Pull-away kite (2026-10-16, Combat/KiteModes.cs): how far (metres) to drag a PullAway
/// monster from its lock-spot origin before stopping to kill it. Per-mob on/off is
/// MonsterRule.Kite (Default follows the DEFAULT row).
/// </summary>
public int KitePullMeters = 20;
/// <summary>Land a hit before fleeing so aggro sticks (Off = run immediately).</summary>
public bool KiteTagFirst = true;
/// <summary>
/// Combat and buffing only ever wield weapons from the Items list. With this on (the
/// default), a character whose Items list has no wand at all may still buff and cast with a
/// caster from its pack (by object class, never by name). Any listed wand turns it off.
@ -821,6 +856,13 @@ public sealed class MonsterRule
/// <summary>Debuffs the player typed in (Damage panel), comma separated: a spell's base
/// name ("Corrosion Vulnerability Other") casts its best known tier; a full name casts as is.</summary>
public string CustomDebuffs { get; set; } = "";
/// <summary>Melee/missile attack power against the monsters this rule covers: one of
/// AttackPowerModes.All. "Default" = the DEFAULT line's choice (on the DEFAULT line: the global
/// Melee/Missile Power settings). Rules saved before 2026-10-12 load as Default.</summary>
public string AttackPower { get; set; } = AttackPowerModes.Default;
/// <summary>Combat pull-away for this rule: one of KiteModes.All. "Default" = the DEFAULT
/// line's choice (on the DEFAULT line: Off). Rules saved before 2026-10-16 load as Default.</summary>
public string Kite { get; set; } = "Default";
}
public sealed class BuffRule
@ -1061,7 +1103,20 @@ public sealed class SettingsBridgePayload
public bool UseNativeAttack { get; set; }
public bool SummonPets { get; set; }
public int PetMinMonsters { get; set; }
// Variable attack power and the environment-impact throttle (2026-10-12). Null = sent by an
// engine without these controls, which leaves the plugin's own values alone.
public int? VariablePowerMin { get; set; }
public int? VariablePowerMax { get; set; }
public int? MissileEnvironmentResponse { get; set; }
public int? MagicEnvironmentResponse { get; set; }
public int? EnvironmentImpactLimit { get; set; }
public int? EnvironmentImpactWindowSec { get; set; }
public int? EnvironmentApproachMeters { get; set; }
public int? EnvironmentMinDistance { get; set; }
public int? EnvironmentSkipSec { get; set; }
// Pull-away kite (2026-10-16). Null = sender without these controls; leave plugin values alone.
public int? KitePullMeters { get; set; }
public bool? KiteTagFirst { get; set; }
// Weapon swaps (only when the sender includes them).
public int? WeaponSwapSettleMs { get; set; }
public int? WeaponSwapMinHealthPct { get; set; }

View file

@ -184,7 +184,9 @@ internal sealed class LootEditorBridge
d.ItemId = id;
var match = (LootItemMatch)Math.Clamp(req.Match, 0, 2);
d.IncludeT11 = req.IncludeT11;
LootItemFacts? facts = Items.Facts(id, match == LootItemMatch.Like, req.IncludeT11);
d.AttributesSupported = true;
// The checklist shows every attribute whatever the match, so the item is always read in full.
LootItemFacts? facts = Items.Facts(id, true, req.IncludeT11 || req.Choices != null);
if (facts == null) return Refuse(d, $"RynthAi doesn't know item 0x{id:X8} yet. Select it again in a moment.");
d.IsT11 = facts.T11?.IsT11 == true;
d.ItemName = facts.Name;
@ -211,9 +213,11 @@ internal sealed class LootEditorBridge
KeepCount = req.KeepCount < 0 ? null : req.KeepCount,
RuleName = req.RuleName,
IncludeT11 = req.IncludeT11,
Choices = req.Choices,
};
LootItemRuleDraft? draft = LootItemRules.Build(facts, options, out string error);
if (draft == null) return Refuse(d, error);
foreach (LootItemAttribute row in draft.Attributes) d.Attributes.Add(row.ToWire());
d.Match = (int)draft.Match;
d.Action = (int)draft.Action;
d.KeepCount = draft.KeepCount;

View file

@ -0,0 +1,383 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The rest of Mag-Tools' <c>/mt</c> verbs (2026-10-17; checked against Mag-Tools PluginCore and
/// ub-IT's MagToUbCommandTranslator): send (keys), jump / sjump, trade, vendor buy/sell lists,
/// autopack, dumpspells, click, get xy, movement, client, plus ub-IT's config and strafe.
/// Partial class of RynthAiPlugin; dispatched from <see cref="HandleMtCommand"/>.
/// </summary>
public sealed partial class RynthAiPlugin
{
// /mt vendor addbuy/addsell lists, sent by "/mt vendor buy" / "sell" (Mag-Tools keeps them in Decal).
private readonly List<(uint Id, string Name, int Amount)> _mtBuyList = new();
private readonly List<(uint Id, string Name)> _mtSellList = new();
/// <summary>The verbs this file handles, from <see cref="HandleMtCommand"/>'s default branch.</summary>
private bool TryHandleMtExtra(string cmd, string[] parts, string fullCommand)
{
// jump, sjump, jumpw, sjumpwz ... (Mag-Tools matches "jump" anywhere after /mt).
if (cmd.StartsWith("jump", StringComparison.Ordinal) || cmd.StartsWith("sjump", StringComparison.Ordinal))
return HandleMtJump(cmd, parts);
switch (cmd)
{
case "test":
ChatLine("[RynthAi] /mt test: Mag-Tools' debug command - nothing to do.");
return true;
case "trade": return HandleMtTrade(parts);
case "vendor": return HandleMtVendor(parts);
case "autopack":
// Mag-Tools packs by its own rules; RynthAi's equivalent is a cram + stack pass.
_inventoryManager?.RunManual(cram: true, stack: true);
ChatLine("[RynthAi] Autopack: cramming items into side packs and stacking them.");
return true;
case "dumpspells": return HandleMtDumpSpells();
case "click": return HandleMtClick(parts);
case "get":
if (parts.Length >= 3 && parts[2].Equals("xy", StringComparison.OrdinalIgnoreCase)) return HandleMtCursor();
ChatLine("[RynthAi] Usage: /mt get xy");
return true;
case "cursor": return HandleMtCursor();
case "movement": return HandleMtMovement(parts);
case "strafe": return HandleMtStrafe(parts);
case "client": return HandleMtClient(parts);
case "config":
// ub-IT: /mt config = /mt opt (list when bare).
return parts.Length < 3 ? HandleMtOpt(new[] { "/mt", "opt", "list" }) : HandleMtOpt(parts);
default:
return false;
}
}
// ── send: keys, as Mag-Tools ────────────────────────────────────────────────
/// <summary>
/// /mt send enter|pause|del|space|f4|f12|cntrl+&lt;letter&gt;|msg &lt;text&gt;: presses keys in the
/// game window, as Mag-Tools. A line starting with "/" is still sent as a chat command (what
/// this verb did before, which some metas use).
/// </summary>
private bool HandleMtSend(string[] parts, string fullCommand)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+<letter>|msg <text>"); return true; }
string arg = parts[2].ToLowerInvariant();
if (parts[2].StartsWith('/'))
{
if (Host.HasInvokeChatParser) Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2));
return true;
}
if (!GameInput.Available) { ChatLine("[RynthAi] /mt send: the game window wasn't found."); return true; }
switch (arg)
{
case "enter": GameInput.SendEnter(); return true;
case "pause": GameInput.SendPause(); return true;
case "del": GameInput.SendDel(); return true;
case "space": GameInput.SendSpace(); return true;
case "f4": GameInput.SendF4(); return true;
case "f12": GameInput.SendF12(); return true;
case "msg":
int at = fullCommand.IndexOf(" msg ", StringComparison.OrdinalIgnoreCase);
if (at < 0 || at + 5 >= fullCommand.Length) { ChatLine("[RynthAi] Usage: /mt send msg <text>"); return true; }
GameInput.SendMsg(fullCommand[(at + 5)..]);
return true;
}
if (arg.StartsWith("cntrl+", StringComparison.Ordinal) && arg.Length >= 7)
{
GameInput.SendCntrl(arg[6]);
return true;
}
ChatLine("[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+<letter>|msg <text>");
return true;
}
// ── jump ─────────────────────────────────────────────────────────────────────
/// <summary>/mt jump[w|z|x|c] [ms] and /mt sjump... (shift): RynthAi's jumper (the engine's own
/// jump), else the keys as Mag-Tools.</summary>
private bool HandleMtJump(string cmd, string[] parts)
{
bool shift = cmd.StartsWith("sjump", StringComparison.Ordinal);
string suffix = cmd[(shift ? 5 : 4)..];
bool w = suffix.Contains('w'), z = suffix.Contains('z'), x = suffix.Contains('x'), c = suffix.Contains('c');
int ms = 0;
if (parts.Length >= 3) int.TryParse(parts[2], out ms);
ms = Math.Clamp(ms, 0, 1000);
string letters = (w ? "w" : "") + (x ? "x" : "") + (z ? "z" : "") + (c ? "c" : "") + (shift ? "s" : "");
if (_jumper != null && _jumper.Start(letters, null, ms)) return true;
if (_jumper?.IsBusy == true) return true; // it said so in chat
if (!GameInput.Available) { ChatLine("[RynthAi] /mt jump: no jump hook and no game window."); return true; }
GameInput.SendSpace(ms, shift, w, z, x, c);
return true;
}
// ── trade ────────────────────────────────────────────────────────────────────
/// <summary>/mt trade add|addp &lt;item&gt; | accept | decline | reset | end.</summary>
private bool HandleMtTrade(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt trade add|addp <item> | accept | decline | reset | end"); return true; }
if (!Host.HasTrade) { ChatLine("[RynthAi] Trading needs a newer RynthCore engine."); return true; }
string sub = parts[2].ToLowerInvariant();
switch (sub)
{
case "add":
case "addp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt trade {sub} <item>"); return true; }
string name = string.Join(" ", parts, 3, parts.Length - 3);
var item = FindObject(name, inv: true, land: false, partial: sub == "addp");
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
ChatLine(Host.TradeAdd(unchecked((uint)item.Id))
? $"[RynthAi] Added {item.Name} to the trade." : "[RynthAi] Could not add it to the trade.");
return true;
}
case "accept": Host.TradeAccept(); return true;
case "decline": Host.TradeDecline(); return true;
case "reset": Host.TradeReset(); return true;
case "end": Host.TradeClose(); return true;
default:
ChatLine("[RynthAi] Usage: /mt trade add|addp <item> | accept | decline | reset | end");
return true;
}
}
// ── vendor ───────────────────────────────────────────────────────────────────
/// <summary>
/// /mt vendor addbuy|addbuyp &lt;item&gt; [count] | addsell|addsellp &lt;item&gt; | buy | clearbuy | sell |
/// clearsell, with a vendor open: lists kept here, sent in one transaction by buy / sell.
/// </summary>
private bool HandleMtVendor(string[] parts)
{
const string usage = "[RynthAi] Usage: /mt vendor addbuy|addbuyp <item> [count] | addsell|addsellp <item> | buy | clearbuy | sell | clearsell";
if (parts.Length < 3) { ChatLine(usage); return true; }
if (!Host.HasVendorTrade) { ChatLine("[RynthAi] Vendor trading needs a newer RynthCore engine."); return true; }
if (!Host.TryGetVendorInfo(out VendorInfo info) || info.VendorId == 0)
{
ChatLine("[RynthAi] No vendor is open.");
return true;
}
string sub = parts[2].ToLowerInvariant();
switch (sub)
{
case "addbuy":
case "addbuyp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt vendor {sub} <item> [count]"); return true; }
var words = parts.Skip(3).ToList();
int count = 1;
if (words.Count > 1 && int.TryParse(words[^1], out int n) && n > 0) { count = n; words.RemoveAt(words.Count - 1); }
string name = string.Join(" ", words);
bool partial = sub == "addbuyp";
VendorItem? item = Host.GetVendorItems().FirstOrDefault(v => partial
? v.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: string.Equals(v.Name, name, StringComparison.OrdinalIgnoreCase));
if (item == null) { ChatLine($"[RynthAi] {info.Name} doesn't sell '{name}'."); return true; }
_mtBuyList.Add((item.ObjectId, item.Name, count));
ChatLine($"[RynthAi] Buy list: {count} x {item.Name} ({_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")}).");
return true;
}
case "addsell":
case "addsellp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt vendor {sub} <item>"); return true; }
string name = string.Join(" ", parts, 3, parts.Length - 3);
var item = FindObject(name, inv: true, land: false, partial: sub == "addsellp");
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
uint id = unchecked((uint)item.Id);
if (!_mtSellList.Any(s => s.Id == id)) _mtSellList.Add((id, item.Name));
ChatLine($"[RynthAi] Sell list: {item.Name} ({_mtSellList.Count} item(s)).");
return true;
}
case "buy":
{
if (_mtBuyList.Count == 0) { ChatLine("[RynthAi] The buy list is empty (/mt vendor addbuy <item> [count])."); return true; }
var entries = _mtBuyList.Select(b => new VendorTradeEntryNative(b.Id, b.Amount)).ToList();
uint sent = Host.VendorBuy(info.VendorId, entries);
ChatLine(sent != 0 ? $"[RynthAi] Buying {_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")} from {info.Name}."
: "[RynthAi] The buy could not be sent.");
if (sent != 0) _mtBuyList.Clear();
return true;
}
case "clearbuy":
_mtBuyList.Clear();
ChatLine("[RynthAi] Buy list cleared.");
return true;
case "sell":
{
if (_mtSellList.Count == 0) { ChatLine("[RynthAi] The sell list is empty (/mt vendor addsell <item>)."); return true; }
uint sent = Host.VendorSell(info.VendorId, _mtSellList.Select(s => s.Id).ToList());
ChatLine(sent != 0 ? $"[RynthAi] Selling {_mtSellList.Count} item(s) to {info.Name}." : "[RynthAi] The sell could not be sent.");
if (sent != 0) _mtSellList.Clear();
return true;
}
case "clearsell":
_mtSellList.Clear();
ChatLine("[RynthAi] Sell list cleared.");
return true;
default:
ChatLine(usage);
return true;
}
}
/// <summary>The vendor closed: its buy / sell lists no longer mean anything.</summary>
private void ClearMtVendorLists()
{
_mtBuyList.Clear();
_mtSellList.Clear();
}
// ── dumpspells ───────────────────────────────────────────────────────────────
/// <summary>/mt dumpspells: the spell table to RynthAi's folder (spelldump.txt: id, name, family, difficulty).</summary>
private bool HandleMtDumpSpells()
{
try
{
Dictionary<string, int> byName = SpellDatabase.BuildNameToIdMap();
var rows = byName.Select(kv => (Id: kv.Value, Name: kv.Key)).Distinct().OrderBy(r => r.Id).ToList();
string path = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "spelldump.txt");
using (var w = new StreamWriter(path, false, new System.Text.UTF8Encoding(false)))
{
w.WriteLine("Id\tName\tFamily\tDifficulty");
foreach (var (id, name) in rows)
{
SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty);
w.WriteLine($"{id}\t{name}\t{family}\t{difficulty}");
}
}
ChatLine($"[RynthAi] {rows.Count} spells written to {path}");
}
catch (Exception ex) { ChatLine($"[RynthAi] /mt dumpspells failed: {ex.Message}"); }
return true;
}
// ── /ra equipfor (VTank /vt equipitemsfor) ───────────────────────────────────
/// <summary>
/// /ra equipfor &lt;monster&gt; (VTank's /vt equipitemsfor): wield the weapon and off hand set on that
/// monster's rule (the rule named exactly, else one whose name the monster's contains, else
/// Default). Items already wielded are left; a rule with no set weapon says so (combat picks
/// one itself when it fights).
/// </summary>
private void HandleEquipForCommand(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /ra equipfor <monster name>"); return; }
var rules = _dashboard?.Settings?.MonsterRules;
if (rules == null || rules.Count == 0) { ChatLine("[RynthAi] No monster rules loaded."); return; }
string monster = string.Join(" ", parts, 2, parts.Length - 2).Trim();
var rule = rules.FirstOrDefault(r => string.Equals(r.Name, monster, StringComparison.OrdinalIgnoreCase))
?? rules.Where(r => !string.Equals(r.Name, "Default", StringComparison.OrdinalIgnoreCase)
&& r.Name.Length > 0 && monster.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0)
.OrderByDescending(r => r.Name.Length).FirstOrDefault()
?? rules.FirstOrDefault(r => string.Equals(r.Name, "Default", StringComparison.OrdinalIgnoreCase));
if (rule == null) { ChatLine($"[RynthAi] No monster rule for '{monster}'."); return; }
var ids = new List<int>();
if (rule.WeaponId != 0) ids.Add(rule.WeaponId);
if (rule.OffhandId != 0) ids.Add(rule.OffhandId);
if (ids.Count == 0)
{
ChatLine($"[RynthAi] '{rule.Name}' has no set weapon (combat picks one when it fights '{monster}').");
return;
}
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return; }
int sent = 0;
foreach (int id in ids)
{
var wo = _objectCache?[id];
if (wo == null) { ChatLine($"[RynthAi] '{rule.Name}': item 0x{(uint)id:X8} isn't carried."); continue; }
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) continue; // already wielded
Host.UseFor(unchecked((uint)id), "Command", "/ra equipfor", UseKind.Asked);
sent++;
}
ChatLine(sent > 0 ? $"[RynthAi] Equipping for '{monster}' ({rule.Name}): {sent} item(s)."
: $"[RynthAi] '{rule.Name}' gear for '{monster}' is already wielded.");
}
// ── click, cursor, movement, strafe, client ─────────────────────────────────
/// <summary>/mt click ok|yes|no|&lt;x&gt; &lt;y&gt;: a click in the game window (window coordinates).</summary>
private bool HandleMtClick(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt click ok|yes|no|<x> <y>"); return true; }
if (!GameInput.Available) { ChatLine("[RynthAi] /mt click: the game window wasn't found."); return true; }
switch (parts[2].ToLowerInvariant())
{
case "ok": GameInput.ClickOK(); return true;
case "yes": GameInput.ClickYes(); return true;
case "no": GameInput.ClickNo(); return true;
}
if (parts.Length >= 4 && int.TryParse(parts[2], out int x) && int.TryParse(parts[3], out int y))
{
GameInput.SendMouseClick(x, y);
return true;
}
ChatLine("[RynthAi] Usage: /mt click ok|yes|no|<x> <y>");
return true;
}
/// <summary>/mt get xy (and ub-IT's /mt cursor): the cursor relative to the game window.</summary>
private bool HandleMtCursor()
{
ChatLine(GameInput.TryCursorInWindow(out int x, out int y)
? $"[RynthAi] Current cursor position: {x},{y}"
: "[RynthAi] The cursor position couldn't be read.");
return true;
}
/// <summary>/mt movement &lt;key&gt; &lt;ms&gt;: hold a movement key (AC's keymap letter) for ms.</summary>
private bool HandleMtMovement(string[] parts)
{
if (parts.Length != 4 || parts[2].Length != 1 || !int.TryParse(parts[3], out int ms) || ms < 0)
{
ChatLine("[RynthAi] Usage: /mt movement <key> <ms> (e.g. /mt movement w 1500)");
return true;
}
if (!GameInput.Available) { ChatLine("[RynthAi] /mt movement: the game window wasn't found."); return true; }
GameInput.SendMovement(parts[2][0], ms);
return true;
}
/// <summary>ub-IT's /mt strafe left|l|right|r &lt;ms&gt;: hold the side-step key (Z / C) for ms.</summary>
private bool HandleMtStrafe(string[] parts)
{
if (parts.Length != 4 || !int.TryParse(parts[3], out int ms) || ms < 0)
{
ChatLine("[RynthAi] Usage: /mt strafe left|l|right|r <ms>");
return true;
}
char key = parts[2].ToLowerInvariant() switch { "left" or "l" => 'z', "right" or "r" => 'c', _ => '\0' };
if (key == '\0') { ChatLine("[RynthAi] /mt strafe: left, l, right or r."); return true; }
if (!GameInput.Available) { ChatLine("[RynthAi] /mt strafe: the game window wasn't found."); return true; }
GameInput.SendMovement(key, ms);
return true;
}
/// <summary>/mt client minimize|restore (ub-IT's frame apply|restore points to Settings > Display).</summary>
private bool HandleMtClient(string[] parts)
{
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
switch (sub)
{
case "minimize": GameInput.Minimize(); return true;
case "restore": GameInput.Restore(); return true;
case "frame":
ChatLine("[RynthAi] The window frame is RynthCore's: Settings > Display (Borderless Windowed, Reset Window Borders) or /rc window reset.");
return true;
default:
ChatLine("[RynthAi] Usage: /mt client minimize | restore");
return true;
}
}
}

View file

@ -92,14 +92,14 @@ public sealed partial class RynthAiPlugin
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit");
return true;
// ── Send a chat line / slash command (VTank /mt send) ────────────
// ── Keys in the game window (Mag-Tools /mt send); a "/" line is still sent as a command ──
case "send":
if (parts.Length >= 3 && Host.HasInvokeChatParser)
Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2));
return true;
return HandleMtSend(parts, fullCommand);
default:
return false;
// jump, trade, vendor, autopack, dumpspells, click, get xy, movement, client, config,
// strafe, test (MagToolsCommands.Extra.cs).
return TryHandleMtExtra(cmd, parts, fullCommand);
}
}
@ -302,11 +302,45 @@ public sealed partial class RynthAiPlugin
private bool HandleMtFace(string[] parts)
{
// /mt face <degrees>
if (parts.Length < 3 || !float.TryParse(parts[2], out float degrees)) return false;
if (!Host.HasTurnToHeading) { ChatLine("[RynthAi] TurnToHeading not available."); return true; }
// /mt face <degrees> (Mag-Tools) and /ub face <degrees> (ub-IT, translated here). The heading
// may have decimals (getheadingto[] gives them), read the same on every PC; or a coordinate
// ("42.1N, 33.6E") to face that spot.
if (parts.Length < 3) return false;
string arg = string.Join(" ", parts, 2, parts.Length - 2).Trim();
double heading;
if (double.TryParse(arg, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double deg))
heading = deg;
else if (!TryHeadingToCoords(arg, out heading))
return false;
Host.TurnToHeadingBy("Command", degrees);
// The jumper holds navigation while it turns (nav would turn the character back) and turns
// again until it faces the heading, as ub-IT does; without it, one plain turn.
if (_jumper != null) _jumper.Face(heading);
else if (Host.HasTurnToHeading) Host.TurnToHeadingBy("Command", (float)(((heading % 360) + 360) % 360));
else ChatLine("[RynthAi] TurnToHeading not available.");
return true;
}
private static readonly System.Text.RegularExpressions.Regex FaceCoordsRx = new(
@"^\s*(?<ns>\d+(?:\.\d+)?)\s*(?<nsc>[NnSs])[\s,]*(?<ew>\d+(?:\.\d+)?)\s*(?<ewc>[EeWw])\s*$",
System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>
/// The heading from the character to a "42.1N, 33.6E" coordinate (AC's: 0 north, 90 east, the
/// same as getheadingto[]). False when the text isn't a coordinate or our position is unknown.
/// </summary>
private bool TryHeadingToCoords(string text, out double heading)
{
heading = 0;
var m = FaceCoordsRx.Match(text);
if (!m.Success || !NavCoordinateHelper.TryGetNavCoords(Host, out double myNs, out double myEw)) return false;
var inv = System.Globalization.CultureInfo.InvariantCulture;
double ns = double.Parse(m.Groups["ns"].Value, inv) * (char.ToUpperInvariant(m.Groups["nsc"].Value[0]) == 'S' ? -1 : 1);
double ew = double.Parse(m.Groups["ew"].Value, inv) * (char.ToUpperInvariant(m.Groups["ewc"].Value[0]) == 'W' ? -1 : 1);
double dNs = ns - myNs, dEw = ew - myEw;
if (Math.Abs(dNs) < 1e-6 && Math.Abs(dEw) < 1e-6) return false;
heading = Math.Atan2(dEw, dNs) * (180.0 / Math.PI);
if (heading < 0) heading += 360.0;
return true;
}

View file

@ -0,0 +1,373 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.Meta;
/// <summary>
/// ub-IT expression functions that were missing (2026-10-18 meta-compatibility pass), with
/// ub-IT's names, arguments and return values. Where RynthAi has no matching data (character
/// select, Decal views, ub-IT's own HUDs) the function still answers, with the value ub-IT gives
/// when there is nothing to report, so an expression that calls it keeps working.
/// </summary>
internal sealed partial class ExpressionEngine
{
/// <summary>Corpses this character has opened (the plugin's loot bookkeeping), for
/// hascorpsebeenopenedbyme[] and getcorpsesunopenedbyme[]. Null: none known.</summary>
internal Func<int, bool>? CorpseOpenedByMe { get; set; }
/// <summary>The meta manager's '/vt opt set' (VTank names, distances in landblock units, the
/// special options), for vtsetsetting[]; null: the plain settings map (an engine without one).</summary>
internal Func<string, string, bool>? VtOptionSetter { get; set; }
/// <summary>The meta manager's '/vt opt get' (values read back in VTank's units), for vtgetsetting[].</summary>
internal Func<string, string?>? VtOptionGetter { get; set; }
// getcooldownexpiration: shared cooldowns are enchantments whose spell id has this bit.
private const uint CooldownSpellFlag = 0x8000;
// ub-IT's QuestRefreshCooldownSeconds default (canrefreshquests[]).
private const double QuestRefreshCooldownSeconds = 60;
// Character property ids (PropertyInt64): total experience, available luminance.
private const uint QuadTotalExperience = 1;
private const uint QuadAvailableLuminance = 6;
// PropertyInt StackSize.
private const uint IntStackSize = 12;
// XP meter (xpreset/xpmeter/xpduration/xptotal/lumtotal/xpavg/lumavg). Starts on the
// first call after login or a reset; luminance counts gains only (spending isn't earning).
private long _xpStartMs = -1;
private long _xpBase, _lumLast, _lumGained;
// Functions with no RynthAi data already logged (one line each per session).
private readonly HashSet<string> _ubNoDataLogged = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// The functions above. Returns false for any other name, so the caller's unknown-function
/// fallback still logs real typos.
/// </summary>
private bool TryEvalUbCompat(string funcName, List<string> rawArgs, Func<int, string> A, out string value)
{
value = funcName switch
{
// ── Inventory actions (1 = attempted, 0 = busy or not possible) ──────
"actiontrymove" => EvalActionTryMove(A(0), A(1), rawArgs.Count > 2 ? A(2) : "0", rawArgs.Count > 3 ? A(3) : "1"),
"actiontrysplit" => EvalActionTrySplit(A(0), A(1), rawArgs.Count > 2 ? A(2) : "", rawArgs.Count > 3 ? A(3) : "0"),
"actiontrydrop" => NoData("actiontrydrop", "0"),
// ── Vitals of an object (current values; the selected target or yourself) ──
"wobjectgethealthvalue" => EvalWobjectVital(A(0), 0),
"wobjectgetstaminavalue" => EvalWobjectVital(A(0), 1),
"wobjectgetmanavalue" => EvalWobjectVital(A(0), 2),
// ── Corpses ──────────────────────────────────────────────────────────
"hascorpsebeenopenedbyme" => EvalCorpseOpenedByMe(A(0)),
"getcorpsesunopenedbyme" => EvalCorpsesUnopenedByMe(),
// ── Casting, cooldowns, spell data ───────────────────────────────────
"iscasting" => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0 ? "1" : "0",
"getcooldownexpiration" => EvalCooldownExpiration(A(0)),
"spelldata" => EvalSpellData(A(0)),
// ── Macro state and delayed expressions ──────────────────────────────
"vtmacroenabled" => _settings?.IsMacroRunning == true ? "1" : "0",
"clearexec" => EvalClearExec(A(0)),
// ── Quests (myquests throttle; ACECustom quest bonus lives in RynthILT) ──
"canrefreshquests" => EvalCanRefreshQuests(),
"testquestbonus" => NoData("testquestbonus", "0"),
"isrefreshingquestbonuses" => "0",
"enlightenmentmaterials" => EvalEnlightenmentTokens(A(0), A(1)),
// ── XP meter ─────────────────────────────────────────────────────────
"xpreset" => EvalXpReset(),
"xpduration" => FormatNumber(XpSeconds()),
"xptotal" => FormatNumber(XpTotal()),
"lumtotal" => FormatNumber(LumTotal()),
"xpavg" => FormatNumber(PerHour(XpTotal())),
"lumavg" => FormatNumber(PerHour(LumTotal())),
"xpmeter" => EvalXpMeterText(),
// ── No RynthAi equivalent: ub-IT's "nothing here" values ─────────────
"getcharacterindex" => NoData("getcharacterindex", "-1"),
"setnextlogin" => NoData("setnextlogin", "0"),
"clearnextlogin" => NoData("clearnextlogin", "1"),
"netclients" => NoData("netclients", "[]"),
"statushud" => NoData("statushud", "1"),
"statushudcolored" => NoData("statushudcolored", "1"),
// Decal views: none exist here, so no view is found or shown.
"uiviewexists" => NoData("uiviewexists", "0"),
"uiviewvisible" => NoData("uiviewvisible", "0"),
"uisetvisible" => NoData("uisetvisible", "0"),
"uisetlabel" => NoData("uisetlabel", "0"),
"uigetcontrol" => NoData("uigetcontrol", "0"),
_ => null!,
};
return value != null;
}
/// <summary>The fixed answer of a function RynthAi has no data for; logged once per session.</summary>
private string NoData(string funcName, string result)
{
if (_ubNoDataLogged.Add(funcName))
_host.Log($"[RynthAi] Expression {funcName}[]: ub-IT feature with no RynthAi equivalent; returns {result}.");
return result;
}
// ── Inventory actions ────────────────────────────────────────────────────
private bool IsBusy() => _host.HasGetBusyState && _host.GetBusyState() > 0;
private int StackSizeOf(uint id)
{
if (_worldObjectCache != null)
{
int n = _worldObjectCache.GetIntProperty(unchecked((int)id), IntStackSize, 0);
if (n > 0) return n;
}
return 1;
}
/// <summary>actiontrymove[obj, container, slot=0, addToStack=1]: into a stack of the same
/// name in that container when there is one (and addToStack), else into the slot.</summary>
private string EvalActionTryMove(string objArg, string destArg, string slotArg, string stackArg)
{
if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0";
if (!TryParseWobjectHandle(destArg, out uint dest, out _) || dest == 0) return "0";
if (IsBusy()) return "0";
if (ToBool(stackArg) && _worldObjectCache != null && _host.HasMergeStackInternal)
{
string name = _worldObjectCache[unchecked((int)id)]?.Name ?? "";
foreach (var wo in _worldObjectCache.GetContainedItems(unchecked((int)dest)))
{
if (unchecked((uint)wo.Id) == id || !string.Equals(wo.Name, name, StringComparison.Ordinal)) continue;
if (StackSizeOf(unchecked((uint)wo.Id)) <= 1 && StackSizeOf(id) <= 1) continue;
return _host.MergeStackInternal(id, unchecked((uint)wo.Id)) ? "1" : "0";
}
}
if (!_host.HasMoveItemInternal) return "0";
int slot = (int)Math.Max(0, ToDouble(slotArg));
return _host.MoveItemInternal(id, dest, slot, StackSizeOf(id)) ? "1" : "0";
}
/// <summary>actiontrysplit[obj, newStackSize, container=player, slot=0]: splits newStackSize off the stack.</summary>
private string EvalActionTrySplit(string objArg, string countArg, string destArg, string slotArg)
{
if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0";
int count = (int)ToDouble(countArg);
if (count < 1 || count >= StackSizeOf(id)) return "0";
uint dest = TryParseWobjectHandle(destArg, out uint d, out _) && d != 0 ? d : _playerId;
if (dest == 0 || IsBusy() || !_host.HasSplitStackInternal) return "0";
int slot = (int)Math.Max(0, ToDouble(slotArg));
return _host.SplitStackInternal(id, dest, slot, count) ? "1" : "0";
}
// ── Vitals ───────────────────────────────────────────────────────────────
/// <summary>Current health (0), stamina (1) or mana (2) of the object; -1 when unknown. The
/// game reports these for yourself and for the target you've selected (as ub-IT notes).</summary>
private string EvalWobjectVital(string objArg, int which)
{
if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "-1";
uint hp, st, mp;
if (id == _playerId)
{
if (!_host.TryGetPlayerVitals(out hp, out _, out st, out _, out mp, out _)) return "-1";
}
else if (!_host.TryGetTargetVitals(id, out hp, out _, out st, out _, out mp, out _))
{
return "-1";
}
uint v = which switch { 0 => hp, 1 => st, _ => mp };
return v.ToString(CultureInfo.InvariantCulture);
}
// ── Corpses ──────────────────────────────────────────────────────────────
private string EvalCorpseOpenedByMe(string objArg)
{
if (!TryParseWobjectHandle(objArg, out uint id, out _) || id == 0) return "0";
return CorpseOpenedByMe?.Invoke(unchecked((int)id)) == true ? "1" : "0";
}
/// <summary>Corpses in view this character hasn't opened, as a list of objects.</summary>
private string EvalCorpsesUnopenedByMe()
{
if (_worldObjectCache == null) return "[]";
var items = new List<string>();
var seen = new HashSet<int>();
foreach (var wo in _worldObjectCache.GetLandscape())
{
if (wo.ObjectClass != AcObjectClass.Corpse || !seen.Add(wo.Id)) continue;
if (CorpseOpenedByMe?.Invoke(wo.Id) == true) continue;
items.Add(MakeWobjectHandle(unchecked((uint)wo.Id), wo.Name));
}
return NewList(items);
}
// ── Casting, cooldowns, spell data ───────────────────────────────────────
/// <summary>Seconds until shared cooldown <paramref name="idArg"/> ends; 0 when it isn't running.</summary>
private string EvalCooldownExpiration(string idArg)
{
int want = (int)ToDouble(idArg);
if (want <= 0 || !_host.HasReadPlayerEnchantments || !_host.HasGetServerTime) return "0";
double now = _host.GetServerTime();
if (now <= 0) return "0";
const int Max = 512;
uint[] ids = new uint[Max];
double[] expiry = new double[Max];
int count = _host.ReadPlayerEnchantments(ids, expiry, Max);
for (int i = 0; i < count; i++)
{
if ((ids[i] & CooldownSpellFlag) == 0 || (ids[i] & 0xFFF) != want) continue;
double left = expiry[i] - now;
return left > 0 ? ((int)Math.Ceiling(left)).ToString(CultureInfo.InvariantCulture) : "0";
}
return "0";
}
/// <summary>spelldata[id]: a dictionary of what RynthAi's spell table knows (Id, Name, Family,
/// Difficulty, Category, Power, Level). Empty for an unknown spell, as in ub-IT.</summary>
private string EvalSpellData(string idArg)
{
int id = (int)ToDouble(idArg);
var d = new Dictionary<string, string>(StringComparer.Ordinal);
if (id > 0 && SpellDatabase.HasSpell(id))
{
d["Id"] = id.ToString(CultureInfo.InvariantCulture);
d["Name"] = SpellDatabase.GetSpellName(id);
if (SpellDatabase.TryGetSpellMeta(id, out int family, out int difficulty))
{
d["Family"] = family.ToString(CultureInfo.InvariantCulture);
d["Difficulty"] = difficulty.ToString(CultureInfo.InvariantCulture);
}
if (SpellDatabase.TryGetCategoryAndPower(id, out int category, out int power))
{
d["Category"] = category.ToString(CultureInfo.InvariantCulture);
d["Power"] = power.ToString(CultureInfo.InvariantCulture);
d["Level"] = SpellDatabase.LevelFromPower(power).ToString(CultureInfo.InvariantCulture);
}
}
return NewDict(d);
}
// ── Delayed expressions ──────────────────────────────────────────────────
/// <summary>clearexec[id]: cancels the delayexec that returned that id. 1 if one was pending.</summary>
private string EvalClearExec(string idArg)
{
long id = (long)ToDouble(idArg);
int removed = _delayedExecs.RemoveAll(e => e.Id == id);
return removed > 0 ? "1" : "0";
}
// ── Quests ───────────────────────────────────────────────────────────────
private string EvalCanRefreshQuests()
{
if (_questTracker == null) return "1";
if (_questTracker.IsRefreshing) return "0";
return (DateTime.UtcNow - _questTracker.LastRefreshUtc).TotalSeconds >= QuestRefreshCooldownSeconds ? "1" : "0";
}
/// <summary>enlightenmentmaterials[current, target]: ub-IT's token count. Levels 6-150 cost
/// (level - 5) tokens each; levels 1-5 cost none and later levels cost other items.</summary>
private static string EvalEnlightenmentTokens(string curArg, string tgtArg)
{
int cur = (int)ToDouble(curArg), tgt = (int)ToDouble(tgtArg);
long tokens = 0;
for (int level = Math.Max(cur + 1, 6); level <= Math.Min(tgt, 150); level++)
tokens += level - 5;
return tokens.ToString(CultureInfo.InvariantCulture);
}
// ── XP meter ─────────────────────────────────────────────────────────────
private long ReadQuad(uint stype)
=> _playerId != 0 && _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(_playerId, stype, out long v) ? v : 0;
/// <summary>Starts the meter on first use and folds in luminance gained since the last look.</summary>
private void SampleXpMeter()
{
long lum = ReadQuad(QuadAvailableLuminance);
if (_xpStartMs < 0)
{
_xpStartMs = TickMs();
_xpBase = ReadQuad(QuadTotalExperience);
_lumLast = lum;
_lumGained = 0;
return;
}
if (lum > _lumLast) _lumGained += lum - _lumLast;
_lumLast = lum;
}
/// <summary>Forgets the meter when the character changes (called from SetPlayerId).</summary>
private void ResetXpMeter() => _xpStartMs = -1;
private string EvalXpReset()
{
ResetXpMeter();
SampleXpMeter();
return "1";
}
private double XpSeconds()
{
SampleXpMeter();
return Math.Max(0, (TickMs() - _xpStartMs) / 1000.0);
}
private double XpTotal()
{
SampleXpMeter();
return Math.Max(0, ReadQuad(QuadTotalExperience) - _xpBase);
}
private double LumTotal()
{
SampleXpMeter();
return _lumGained;
}
private double PerHour(double amount)
{
double s = XpSeconds();
return s <= 0 ? 0 : amount / s * 3600;
}
/// <summary>ub-IT's meter text: "500m XP and 2k LUM, 51s, 35.39b XP/hr and 140k LUM/hr".</summary>
private string EvalXpMeterText()
{
double xp = XpTotal(), lum = LumTotal(), s = XpSeconds();
string head = lum > 0 ? $"{ShortNumber(xp)} XP and {ShortNumber(lum)} LUM" : $"{ShortNumber(xp)} XP";
string rate = lum > 0 ? $"{ShortNumber(PerHour(xp))} XP/hr and {ShortNumber(PerHour(lum))} LUM/hr" : $"{ShortNumber(PerHour(xp))} XP/hr";
return $"{head}, {ShortDuration(s)}, {rate}";
}
private static string FormatNumber(double v) => Math.Round(v, 2).ToString("0.##", CultureInfo.InvariantCulture);
/// <summary>1234 -> 1.23k, 5.6e8 -> 560m, as ub-IT's formatExperience.</summary>
private static string ShortNumber(double v)
{
string[] units = { "", "k", "m", "b", "t", "q" };
int u = 0;
while (Math.Abs(v) >= 1000 && u < units.Length - 1) { v /= 1000; u++; }
return (u == 0 ? Math.Round(v).ToString("0", CultureInfo.InvariantCulture)
: v.ToString("0.##", CultureInfo.InvariantCulture)) + units[u];
}
private static string ShortDuration(double seconds)
{
var t = TimeSpan.FromSeconds(Math.Max(0, seconds));
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes}m";
if (t.TotalMinutes >= 1) return $"{t.Minutes}m {t.Seconds}s";
return $"{t.Seconds}s";
}
}

View file

@ -33,7 +33,7 @@ namespace RynthCore.Plugin.RynthAi.Meta;
/// Lists are text ("[a,b]"); the list functions that change a list write it back to the
/// variable it came from. Dictionaries and stopwatches are handles ("D:0", "SW:0").
/// </summary>
internal sealed class ExpressionEngine
internal sealed partial class ExpressionEngine
{
private readonly RynthCoreHost _host;
private WorldObjectCache? _worldObjectCache;
@ -71,7 +71,7 @@ internal sealed class ExpressionEngine
if (_pvars != null) foreach (string v in _pvars.Values) Scan(v);
if (_gvars != null) foreach (string v in _gvars.Values) Scan(v);
foreach (string v in _options.Values) Scan(v);
foreach (var (_, expr) in _delayedExecs) Scan(expr);
foreach (var (_, _, expr) in _delayedExecs) Scan(expr);
while (todo.Count > 0)
foreach (var (k, v) in _dicts[todo.Dequeue()]) { Scan(k); Scan(v); }
@ -133,7 +133,8 @@ internal sealed class ExpressionEngine
// hot-reload to fire into a freed engine). Instance-scoped so a hot-reload
// discards pending execs. Single-threaded access (Evaluate and the pump
// both run on the plugin-tick thread) → no lock needed.
private readonly List<(long DueMs, string Expr)> _delayedExecs = new();
private readonly List<(long Id, long DueMs, string Expr)> _delayedExecs = new();
private long _nextDelayedExecId;
private uint _playerId;
private LegacyUiSettings? _settings;
@ -187,6 +188,7 @@ internal sealed class ExpressionEngine
FlushVars(force: true); // persist the old char's pending pvars first
_pvars = null;
_pvarPathCached = null;
ResetXpMeter();
}
_playerId = id;
}
@ -557,8 +559,12 @@ internal sealed class ExpressionEngine
// UB vtgetmeta[]: the loaded meta's name (file name without extension).
"vtgetmeta" or "ragetmeta" => string.IsNullOrEmpty(_settings?.CurrentMetaPath)
? "" : Path.GetFileNameWithoutExtension(_settings!.CurrentMetaPath),
"rasetsetting" or "vtsetsetting" => EvalVtSetSetting(Text(0), A(1)),
"ragetsetting" or "vtgetsetting" or "vtankgetsetting" => EvalVtGetSetting(Text(0)),
// vt*: VTank option names and units (landblock distances), the same as '/vt opt set|get';
// ra*: RynthAi's own setting names, as they are.
"vtsetsetting" => VtOptionSetter != null && Text(0).Length > 0 ? (VtOptionSetter(Text(0), A(1)) ? "1" : "0") : EvalVtSetSetting(Text(0), A(1)),
"vtgetsetting" or "vtankgetsetting" => VtOptionGetter != null && Text(0).Length > 0 ? VtOptionGetter(Text(0)) ?? "" : EvalVtGetSetting(Text(0)),
"rasetsetting" => EvalVtSetSetting(Text(0), A(1)),
"ragetsetting" => EvalVtGetSetting(Text(0)),
// ── Dynamic evaluation ────────────────────────────────────────────
"exec" => Evaluate(A(0)),
@ -583,7 +589,8 @@ internal sealed class ExpressionEngine
// "Strings support slices like arrays. ie test[1:]": a word that isn't a function,
// followed by [start:stop].
_ when TopLevelColon(argsStr) >= 0 => SliceBy(expr.Substring(0, lb).Trim(), argsStr),
_ => EvalUnknownFunction(funcName)
// ub-IT's remaining functions (ExpressionEngine.UbCompat.cs), then a real unknown.
_ => TryEvalUbCompat(funcName, rawArgs, A, out string ubValue) ? ubValue : EvalUnknownFunction(funcName)
};
}
@ -3049,7 +3056,7 @@ internal sealed class ExpressionEngine
DateTime mtime = File.GetLastWriteTime(profilePath);
// Each pulse: fire MoveItemExternal for the first matching item still in inventory.
// Each pulse: give (whole object) the first matching item still in inventory.
// We retry the same item until it vanishes from the cache (server confirmed).
// Once gone, the next iteration naturally picks up the next item.
// Returns 1 while matching items remain, 0 when inventory is clear.
@ -3629,6 +3636,17 @@ internal sealed class ExpressionEngine
["CastDispelSelf"] = (() => B(s.CastDispelSelf), v => s.CastDispelSelf = ToDouble(v) != 0),
["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0),
["UseRecklessness"] = (() => B(s.UseRecklessness), v => s.UseRecklessness = ToDouble(v) != 0),
// The range a monster rule's Variable attack power picks from (percent of the bar).
["VariablePowerMin"] = (() => I(s.VariablePowerMin), v => { if (int.TryParse(v, out int i)) s.VariablePowerMin = Math.Clamp(i, 0, 100); }),
["VariablePowerMax"] = (() => I(s.VariablePowerMax), v => { if (int.TryParse(v, out int i)) s.VariablePowerMax = Math.Clamp(i, 0, 100); }),
// Environment hits: 0 Off, 1 Move closer, 2 New target, 3 Move closer then new target.
["MissileEnvironmentResponse"] = (() => I(s.MissileEnvironmentResponse), v => { if (int.TryParse(v, out int i)) s.MissileEnvironmentResponse = Math.Clamp(i, 0, 3); }),
["MagicEnvironmentResponse"] = (() => I(s.MagicEnvironmentResponse), v => { if (int.TryParse(v, out int i)) s.MagicEnvironmentResponse = Math.Clamp(i, 0, 3); }),
["EnvironmentImpactLimit"] = (() => I(s.EnvironmentImpactLimit), v => { if (int.TryParse(v, out int i)) s.EnvironmentImpactLimit = Math.Clamp(i, 1, 10); }),
["EnvironmentImpactWindowSec"] = (() => I(s.EnvironmentImpactWindowSec), v => { if (int.TryParse(v, out int i)) s.EnvironmentImpactWindowSec = Math.Clamp(i, 5, 120); }),
["EnvironmentApproachMeters"] = (() => I(s.EnvironmentApproachMeters), v => { if (int.TryParse(v, out int i)) s.EnvironmentApproachMeters = Math.Clamp(i, 1, 30); }),
["EnvironmentMinDistance"] = (() => I(s.EnvironmentMinDistance), v => { if (int.TryParse(v, out int i)) s.EnvironmentMinDistance = Math.Clamp(i, 1, 30); }),
["EnvironmentSkipSec"] = (() => I(s.EnvironmentSkipSec), v => { if (int.TryParse(v, out int i)) s.EnvironmentSkipSec = Math.Clamp(i, 5, 300); }),
["WeaponSwapSettleMs"] = (() => I(s.WeaponSwapSettleMs), v => { if (int.TryParse(v, out int i)) s.WeaponSwapSettleMs = Math.Clamp(i, 0, 3000); }),
["WeaponSwapMinHealthPct"] = (() => I(s.WeaponSwapMinHealthPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinHealthPct = Math.Clamp(i, 0, 100); }),
["WeaponSwapMinGainPct"] = (() => I(s.WeaponSwapMinGainPct), v => { if (int.TryParse(v, out int i)) s.WeaponSwapMinGainPct = Math.Clamp(i, 0, 200); }),
@ -3665,6 +3683,7 @@ internal sealed class ExpressionEngine
["CorpseApproachRangeMin"] = (() => D(s.CorpseApproachRangeMin), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.CorpseApproachRangeMin = d; }),
["ManaStoneKeepCount"] = (() => I(s.ManaStoneKeepCount), v => { if (int.TryParse(v, out int i)) s.ManaStoneKeepCount = i; }),
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
["BlacklistTimeoutSec"] = (() => I(s.BlacklistTimeoutSec), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && d >= 0) s.BlacklistTimeoutSec = (int)Math.Round(d); }),
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
@ -3722,8 +3741,10 @@ internal sealed class ExpressionEngine
CultureInfo.InvariantCulture, out double delayMs))
delayMs = 0;
long ms = (long)Math.Max(0, delayMs);
_delayedExecs.Add((TickMs() + ms, exprArg));
return "1";
// ub-IT returns the job's id (for clearexec); ids start at 1 so the result stays true.
long id = ++_nextDelayedExecId;
_delayedExecs.Add((id, TickMs() + ms, exprArg));
return id.ToString(CultureInfo.InvariantCulture);
}
/// <summary>

View file

@ -1608,7 +1608,9 @@ ITEM GIVING
actiontrygiveprofile[lootprofile, target]
Gives all inventory items matching Keep rules in the specified loot profile to a
nearby player or NPC named target.
nearby NPC or vendor named target, with AC's give action. Never to a player: a
shared meta must not be able to hand your inventory to someone's character.
To give to a player, type /ra ig <profile> to <player>.
Supports both VTank .utl profiles and native RynthAi .json profiles.
Profile files are loaded from:
@ -1620,10 +1622,13 @@ actiontrygiveprofile[lootprofile, target]
the target was not found in the nearby world, no items matched, or the profile
could not be loaded.
Param #0: lootprofile — filename (or full path) of the loot profile (.utl or .json).
Param #0: lootprofile — filename of the loot profile (.utl or .json), inside ItemGiver\
(a subfolder of it is fine). Full paths, drive letters, ':' and anything
that climbs out with ..\ are refused (logged once, returns "0").
Bare names without extension resolve as .utl from ItemGiver\.
Regex-escaped dots in UB examples (e.g. salvage\.utl) are just literal dots.
Param #1: target — exact name (case-insensitive) of the player or NPC to give to.
Param #1: target — exact name (case-insensitive) of the NPC or vendor to give to.
A player with that name is skipped.
Known limitations (TODO):
- Currently gives one item per meta pulse. Full rapid-fire batch transfer not yet
@ -1632,10 +1637,10 @@ actiontrygiveprofile[lootprofile, target]
all item types correctly (e.g. salvage ObjectClass known issue).
- Only .utl and .json profiles are supported; no fallback between profile directories.
Test in chat: /ra mexec actiontrygiveprofile[salvage.utl,My Salvage Mule]
Example: actiontrygiveprofile[salvage.utl,My Salvage Mule]
Test in chat: /ra mexec actiontrygiveprofile[salvage.utl,Town Crier]
Example: actiontrygiveprofile[salvage.utl,Town Crier]
→ "1" if items were given (VTank profile)
Example: actiontrygiveprofile[mysalvage.json,My Salvage Mule]
Example: actiontrygiveprofile[mysalvage.json,Town Crier]
→ "1" if items were given (native JSON profile)

View file

@ -179,6 +179,15 @@ internal sealed class MetaManager
_expressions?.SetKillClock(clock);
}
// Corpses this character opened (the plugin's loot bookkeeping), for ub-IT's
// hascorpsebeenopenedbyme[] / getcorpsesunopenedbyme[].
private Func<int, bool>? _corpseOpenedByMe;
public void SetCorpseOpenedCheck(Func<int, bool>? check)
{
_corpseOpenedByMe = check;
if (_expressions != null) _expressions.CorpseOpenedByMe = check;
}
public void SetPlayerId(uint id)
{
_playerId = id;
@ -231,6 +240,10 @@ internal sealed class MetaManager
engine.SetSettings(_settings);
engine.SetCreatureStore(_creatureStore);
engine.SetKillClock(_killClock);
engine.CorpseOpenedByMe = _corpseOpenedByMe;
// vtsetsetting[] / vtgetsetting[] take VTank names and units, as '/vt opt set|get' does.
engine.VtOptionSetter = TrySetVtOption;
engine.VtOptionGetter = GetVtOption;
return engine;
}
@ -1171,6 +1184,39 @@ internal sealed class MetaManager
return true;
}
// /vt e — VTank's macro toggle (ub-IT sends it to switch VTank on or off).
if (sub == "e")
{
_raCommandHandler?.Invoke(_settings.IsMacroRunning ? "/ra stop" : "/ra start");
return true;
}
// /vt jump [heading] [shift true|false] [holdms] — VTank's jump (universalremote.met, ub-IT):
// RynthAi's jumper through /ra jump[s] [heading] [holdtime].
if (sub == "jump")
{
string heading = parts.Length >= 3 ? parts[2] : "";
bool shift = parts.Length >= 4 && (parts[3].Equals("true", StringComparison.OrdinalIgnoreCase) || parts[3] == "1");
string hold = parts.Length >= 5 ? parts[4] : "";
_raCommandHandler?.Invoke(("/ra jump" + (shift ? "s" : "") + " " + heading + " " + hold).Trim());
return true;
}
// /vt tapjump — a quick jump with no charge.
if (sub == "tapjump")
{
if (!(_host.HasTapJump && _host.TapJump()))
_host.WriteToChat("[RynthAi] /vt tapjump: the engine's jump isn't available.", 1);
return true;
}
// /vt equipitemsfor <monster> — wield what that monster's rule names (weapon, off hand).
if (sub == "equipitemsfor" && parts.Length >= 3)
{
_raCommandHandler?.Invoke("/ra equipfor " + string.Join(" ", parts, 2, parts.Length - 2));
return true;
}
// /vt meta load <name> — the same load as /ra meta load (LegacyDashboardRenderer.LoadMetaByName):
// a meta in MetaFiles, or, when there is none by that name, a new blank one (2026-10-13).
if (sub == "meta" && parts.Length >= 4 &&
@ -1193,8 +1239,8 @@ internal sealed class MetaManager
return true;
}
// /vt loot load <name> — load a loot profile
if ((sub == "loot" || sub == "lootprofile") && parts.Length >= 4 &&
// /vt loot load <name> — load a loot profile ("looting load" too: FoundryIzexi.met, Meta_Society.met)
if ((sub == "loot" || sub == "lootprofile" || sub == "looting") && parts.Length >= 4 &&
parts[2].Equals("load", StringComparison.OrdinalIgnoreCase))
{
string name = string.Join(" ", parts, 3, parts.Length - 3).Trim().Trim('"');
@ -1231,8 +1277,20 @@ internal sealed class MetaManager
return true;
}
// /vt settings load / loadchar — ignore silently
if (sub == "settings") return true;
// /vt settings loadchar|savechar <name> — RynthAi's settings profiles (/ra settings ...);
// universalremote.met switches profiles this way. Any other /vt settings verb is ignored.
if (sub == "settings")
{
if (parts.Length >= 4 && (parts[2].Equals("loadchar", StringComparison.OrdinalIgnoreCase)
|| parts[2].Equals("savechar", StringComparison.OrdinalIgnoreCase)))
_raCommandHandler?.Invoke($"/ra settings {parts[2].ToLowerInvariant()} {string.Join(" ", parts, 3, parts.Length - 3)}");
return true;
}
// /vt <option> <value> — an option written as a verb (DerethExploration: "/vt navclosestoprange
// 0.005"): the same as /vt opt set, for the VTank options RynthAi maps.
if (parts.Length == 3 && (VtOptionMap.ContainsKey(sub) || IsSpecialVtOption(sub)))
return TrySetVtOption(sub, parts[2]);
// /vt <verb> aliases → existing /ra handlers (Phase 1.3 VTank-meta migration).
// Re-dispatch through the /ra path (_raCommandHandler → HandleRaCommand).
@ -1249,10 +1307,23 @@ internal sealed class MetaManager
System.Globalization.CultureInfo.InvariantCulture, out double bar))
{
int pct = Math.Clamp((int)Math.Round(bar * 100), 0, 100);
_lastAttackBarPct = pct;
_raCommandHandler?.Invoke("/ra power " + pct.ToString(System.Globalization.CultureInfo.InvariantCulture));
return true;
}
// /vt deletemonster (S_Colo, leaving the arena): no RynthAi equivalent is known. Accepted so
// it doesn't go on to AC's chat parser as an unknown command; logged once.
if (sub == "deletemonster")
{
if (!_deleteMonsterLogged)
{
_deleteMonsterLogged = true;
RynthLog.Write(LogCat.Meta, "[Meta] /vt deletemonster accepted and ignored (no RynthAi equivalent).");
}
return true;
}
// /vt reverseroute — reverse the active nav route in place (shared settings;
// the engine re-reads CurrentRoute each tick, so the flip takes effect next tick).
if (sub == "reverseroute")
@ -1351,15 +1422,143 @@ internal sealed class MetaManager
// converts it into FollowNavMin, the nav point reach (see ExpressionEngine).
["navclosestoprange"] = "NavCloseStopRange",
["follownavmin"] = "FollowNavMin", // RynthAi's own name, yards
// 2026-10-17: options the metas in MetaFiles / MetaProfiles set that had no mapping.
["navclosetoprange"] = "NavCloseStopRange", // the same option, misspelt in some metas
["attackrange"] = "MonsterRange",
["ringdistance"] = "RingRange",
["minimumringtargets"] = "MinRingTargets",
["corpseapproachrange"] = "CorpseApproachRangeMax",
["corpseapproachrange-max"] = "CorpseApproachRangeMax",
["corpseapproachrange-min"] = "CorpseApproachRangeMin",
// 2026-10-18: the sample metas (S_*, Colo) set these and nothing read them.
["rebufftimeremainingseconds"] = "RebuffSecondsRemaining", // VTank's spelling (the one above is a typo)
["petcustomrange"] = "CustomPetRange", // landblock units -> whole yards
["blacklistmonstertimeoutseconds"] = "BlacklistTimeoutSec",
};
/// <summary>VTank options given in landblock units (x240 = yards) whose RynthAi setting is yards.
/// NavCloseStopRange converts itself (the settings map takes landblock units).</summary>
private static readonly HashSet<string> VtDistanceOptions = new(StringComparer.OrdinalIgnoreCase)
{
"attackdistance", "attackrange", "approachdistance", "dooropenrange", "opendoorrange", "ringdistance",
"corpseapproachrange", "corpseapproachrange-max", "corpseapproachrange-min", "petcustomrange",
};
/// <summary>RynthAi distance settings kept in whole yards (their setter refuses a decimal).</summary>
private static readonly HashSet<string> IntYardSettings = new(StringComparer.Ordinal)
{
"MonsterRange", "ApproachRange", "RingRange", "CustomPetRange",
};
/// <summary>A RynthAi yards value as VTank's landblock units (yards / 240), for reading a distance back.</summary>
internal static string YardsToVtDistance(string yards)
{
if (!double.TryParse(yards, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double v))
return yards;
return (v / 240.0).ToString("0.######", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>
/// A VTank distance as RynthAi yards: a value up to 1 is landblock units (x240; VTank's own
/// unit), a larger one is taken as yards already (typed by hand). Invariant culture.
/// </summary>
internal static string VtDistanceToYards(string value, bool wholeYards)
{
if (!double.TryParse(value, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double v))
return value; // not a number (an unexpanded expression): left for the setter to refuse
double yards = v > 0 && v <= 1.0 ? v * 240.0 : v;
return wholeYards
? Math.Max(0, (int)Math.Round(yards)).ToString(System.Globalization.CultureInfo.InvariantCulture)
: yards.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>VTank options handled by <see cref="TrySetSpecialVtOption"/> (no 1:1 RynthAi setting).</summary>
private static bool IsSpecialVtOption(string vtName) => vtName.ToLowerInvariant() is
"defaultmeleeattackheight" or "lootfellowcorpses" or "lootallcorpses" or "usearcs" or "minimumhealkitsuccesschance"
or "autoattackpower";
// The last /vt setattackbar power (percent), for AutoAttackPower false after it was on (-1 = none yet).
private int _lastAttackBarPct = -1;
private bool _deleteMonsterLogged;
/// <summary>
/// The VTank options whose value means something else in RynthAi:
/// DefaultMeleeAttackHeight 1-3 (low/medium/high) is RynthAi's 0-2; LootFellowCorpses /
/// LootAllCorpses pick the loot-ownership mode (my kills / fellowship / all); UseArcs is a VTank
/// mode number (2, 3 in the metas) for RynthAi's on/off; MinimumHealKitSuccessChance is a
/// percent (a fraction up to 1 is scaled). False when <paramref name="vtName"/> isn't one of them.
/// </summary>
private bool TrySetSpecialVtOption(string vtName, string value)
{
var inv = System.Globalization.CultureInfo.InvariantCulture;
bool num = double.TryParse(value, System.Globalization.NumberStyles.Float, inv, out double n);
switch (vtName.ToLowerInvariant())
{
case "defaultmeleeattackheight":
if (!num) return true;
_settings.MeleeAttackHeight = Math.Clamp((int)Math.Round(n) - 1, 0, 2);
return true;
case "lootfellowcorpses":
if (!num) return true;
if (n != 0 && _settings.LootOwnership < 1) _settings.LootOwnership = 1;
else if (n == 0 && _settings.LootOwnership == 1) _settings.LootOwnership = 0;
return true;
case "lootallcorpses":
if (!num) return true;
if (n != 0) _settings.LootOwnership = 2;
else if (_settings.LootOwnership == 2) _settings.LootOwnership = 0;
return true;
case "usearcs":
if (!num) return true;
_settings.UseArcs = n != 0;
return true;
case "minimumhealkitsuccesschance":
if (!num) return true;
_settings.KitMinSuccessPct = Math.Clamp((int)Math.Round(n > 0 && n <= 1 ? n * 100 : n), 0, 100);
return true;
case "autoattackpower":
// On: RynthAi picks the power itself (-1, its "auto"). Off: the attack bar's value,
// the last /vt setattackbar (a power already set by hand stays as it is).
if (!num) return true;
if (n != 0)
{
_settings.MeleeAttackPower = _settings.MissileAttackPower = -1;
}
else if (_settings.MeleeAttackPower < 0 || _settings.MissileAttackPower < 0)
{
if (_lastAttackBarPct >= 0)
_settings.MeleeAttackPower = _settings.MissileAttackPower = _lastAttackBarPct;
else
RynthLog.Write(LogCat.Meta, "[Meta] AutoAttackPower off with no /vt setattackbar value yet: attack power stays automatic.");
}
return true;
default:
return false;
}
}
/// <summary>The special options as VTank reads them back (height 1-3, ownership as two flags).</summary>
private string? GetSpecialVtOption(string vtName) => vtName.ToLowerInvariant() switch
{
"defaultmeleeattackheight" => (_settings.MeleeAttackHeight + 1).ToString(System.Globalization.CultureInfo.InvariantCulture),
"lootfellowcorpses" => _settings.LootOwnership >= 1 ? "true" : "false",
"lootallcorpses" => _settings.LootOwnership == 2 ? "true" : "false",
"usearcs" => _settings.UseArcs ? "true" : "false",
"minimumhealkitsuccesschance" => _settings.KitMinSuccessPct.ToString(System.Globalization.CultureInfo.InvariantCulture),
"autoattackpower" => _settings.MeleeAttackPower < 0 ? "true" : "false",
_ => null,
};
/// <summary>A VTank option's current value (mapped setting, else a stored generic option).</summary>
private string? GetVtOption(string vtName)
{
if (GetSpecialVtOption(vtName) is string special) return special;
var map = Expressions.BuildSettingsMapPublic();
if (VtOptionMap.TryGetValue(vtName, out string? raName))
{
if (map.TryGetValue(raName, out var entry)) return entry.Get();
// Distances read back in VTank's landblock units, as they were set (6 yd reads 0.025).
if (map.TryGetValue(raName, out var entry))
return VtDistanceOptions.Contains(vtName) ? YardsToVtDistance(entry.Get()) : entry.Get();
}
// A RynthAi setting named directly (EnableCombat, OpenDoors, NavCloseStopRange...).
if (map.TryGetValue(vtName, out var direct)) return direct.Get();
@ -1372,6 +1571,15 @@ internal sealed class MetaManager
// Translate VTank bool strings to numeric
string value = NormalizeVtValue(vtValue);
// Options whose value means something else in RynthAi (a scale, an offset, a mode).
if (TrySetSpecialVtOption(vtName, value)) return true;
// VTank distances are in landblock units (1 = 240 yd: AttackDistance .01666 is 4 yd); RynthAi's
// are yards. Converted here, rounded where RynthAi keeps whole yards (an int setting refused
// "0.01666" outright, so every meta's attack / approach distance was dropped).
if (VtDistanceOptions.Contains(vtName) && VtOptionMap.TryGetValue(vtName, out string? distName))
value = VtDistanceToYards(value, IntYardSettings.Contains(distName));
var map = Expressions.BuildSettingsMapPublic();
if (VtOptionMap.TryGetValue(vtName, out string? raName))
{

View file

@ -0,0 +1,126 @@
// RingChain.cs - Infinite Leaftide's ring inscription chain (Crafting > Rings), from UB-IT's
// ImbueSpellCraftDefinitions / SpellcraftInventoryPolicy.
//
// Step 1: Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction
// Step 2: Enlightened Quill used on Ink of Partition -> partition quill
// Step 3: partition quill used on a Glyph -> "Inscription of ..." scroll
// Then each scroll is used on a ring / jewelry / weapon.
//
// Pure: ingredient matching (case-insensitive substrings with alternates and one exclude), the
// craft queue order and the scroll-to-target pairing. RingChainRunner does the using.
using System;
using System.Collections.Generic;
using System.Linq;
namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
/// <summary>One ingredient: the first of <see cref="Names"/> found in an item's name, unless it also has <see cref="Exclude"/>.</summary>
internal sealed record RingIngredient(string Label, string[] Names, string Exclude = "");
/// <summary>One combine: <see cref="Tool"/> is used on <see cref="Target"/>.</summary>
/// <param name="Tier">1 quill + trophy, 2 + ink, 3 + glyph: the queue runs every tier-1 run first.</param>
/// <param name="ScrollMarkers">Step 3: the words the resulting inscription scroll's name carries.</param>
internal sealed record RingRecipe(string Id, int Tier, string Name, string Notes,
RingIngredient Tool, RingIngredient Target, string[] ScrollMarkers);
internal static class RingChain
{
/// <summary>Every inscription scroll's name has this.</summary>
public const string InscriptionMarker = "Inscription of";
/// <summary>Most runs of one recipe the tab queues.</summary>
public const int MaxRuns = 99;
private static readonly RingIngredient PartitionQuill = new("Enlightened Infliction Quill of Partition",
new[] { "Enlightened Infliction Quill of Partition", "Enlightened Quill of Infliction of Partition" });
private static RingRecipe Glyph(string id, string element, string scroll) => new(
id, 3, $"Step 3: {element} glyph - {scroll}",
$"Partition quill used on Glyph of {element} -> Inscription of {scroll} scroll.",
PartitionQuill,
// The full glyph name: a short one can match the wrong stack.
new RingIngredient($"Glyph of {element}", new[] { $"Glyph of {element}" }),
new[] { scroll, element });
/// <summary>The chain, in UB-IT's order.</summary>
public static readonly RingRecipe[] Recipes =
{
new("ring2_step1_quill_trophy", 1, "Step 1: Quill of Infliction + Trophy",
"Quill of Infliction used on a Trophy -> Enlightened Quill of Infliction.",
new RingIngredient("Quill of Infliction", new[] { "Quill of Infliction", "Infliction Quill" }, Exclude: "Enlightened"),
// Not plain "Trophy": scrolls and kits carry that word too.
new RingIngredient("Trophy", new[] { "Royal Summons", "Empyrean Trophy", "Summoning Gem" }),
Array.Empty<string>()),
new("ring2_step2_ink", 2, "Step 2: Enlightened Quill + Ink of Partition",
"Enlightened Quill of Infliction (from Step 1) used on Ink of Partition -> partition quill.",
new RingIngredient("Enlightened Quill of Infliction",
new[] { "Enlightened Quill of Infliction", "Enlightened Infliction Quill", "Enlightened Infliction Quill of" }, Exclude: "Partition"),
new RingIngredient("Ink of Partition", new[] { "Ink of Partition", "Partition Ink" }),
Array.Empty<string>()),
Glyph("ring2_glyph_bludgeoning", "Bludgeoning", "Tectonic Rifts"),
Glyph("ring2_glyph_lightning", "Lightning", "Eye of the Storm"),
Glyph("ring2_glyph_piercing", "Piercing", "Nuhmudira's Spines"),
Glyph("ring2_glyph_nether", "Nether", "Clouded Soul"),
Glyph("ring2_glyph_corrosion", "Corrosion", "Searing Disc"),
Glyph("ring2_glyph_frost", "Frost", "Halo of Frost"),
Glyph("ring2_glyph_slashing", "Slashing", "Horizon's Blades"),
Glyph("ring2_glyph_flame", "Flame", "Cassius' Ring of Fire"),
};
/// <summary>True when an item's name is this ingredient.</summary>
public static bool Matches(string? name, RingIngredient ing)
{
if (string.IsNullOrEmpty(name)) return false;
if (ing.Exclude.Length > 0 && name.IndexOf(ing.Exclude, StringComparison.OrdinalIgnoreCase) >= 0) return false;
foreach (string n in ing.Names)
if (n.Length > 0 && name.IndexOf(n, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
/// <summary>
/// The craft queue: every Step 1 run, then every Step 2 run, then the glyphs, each tier in
/// definition order (a later tier's ingredients come out of the earlier one).
/// </summary>
public static List<RingRecipe> Expand(Func<string, int> runs)
{
var queue = new List<RingRecipe>();
foreach (var r in Recipes.OrderBy(r => r.Tier))
{
int n = Math.Clamp(runs(r.Id), 0, MaxRuns);
for (int i = 0; i < n; i++) queue.Add(r);
}
return queue;
}
/// <summary>The glyph recipe a scroll came from (null when its name has no known marker).</summary>
public static RingRecipe? GlyphOf(string? scrollName)
{
if (string.IsNullOrEmpty(scrollName)) return null;
foreach (var r in Recipes)
foreach (string m in r.ScrollMarkers)
if (scrollName.IndexOf(m, StringComparison.OrdinalIgnoreCase) >= 0) return r;
return null;
}
public static bool IsInscriptionScroll(string? name)
=> !string.IsNullOrEmpty(name) && name.IndexOf(InscriptionMarker, StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>
/// Pairs scrolls with targets the way UB-IT does: scrolls by glyph recipe id (unknown ones
/// last, by name), targets by object id, one scroll per target.
/// </summary>
public static List<(int Scroll, int Target)> PairScrolls(IEnumerable<(int Id, string Name)> scrolls, IEnumerable<int> targets)
{
var ordered = scrolls
.OrderBy(s => GlyphOf(s.Name)?.Id ?? "zzz_" + s.Name, StringComparer.Ordinal)
.ThenBy(s => s.Id)
.ToList();
var pairs = new List<(int, int)>();
int i = 0;
foreach (int t in targets.Distinct().OrderBy(x => x))
{
if (i >= ordered.Count) break;
pairs.Add((ordered[i++].Id, t));
}
return pairs;
}
}

View file

@ -0,0 +1,387 @@
// RingChainRunner.cs - Crafts Infinite Leaftide's ring inscription chain and applies the scrolls
// (Crafting > Rings).
//
// Pump thread only (the tab's Render reads the volatile snapshots and posts the commands).
// Crafting: the queue from RingChain.Expand, one combine at a time:
// 1. gates: peace mode (unless the server allows combat crafting), not busy, ActionPacer;
// 2. find the tool and the target by name; a later step's ingredients come out of the earlier
// combine, so a missing one is looked for again for a while (inventory lag) before giving up;
// 3. arm the engine's confirmation answer (Yes: the player queued it) and use tool on target;
// 4. the combine is done when the tool or the target stack shrinks or the output shows up.
// No sign of it stops the job instead of retrying, so nothing is crafted twice.
// Scrolls: each "Inscription of ..." scroll is used on its target (the item selected in AC, or
// the last Jewelry / weapon scan's items paired the UB-IT way) and is done when it leaves the pack.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RynthCore.Loot;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.MiniRemote.Crafting;
/// <summary>One line of the Rings scan: a recipe header (Found null) or an ingredient.</summary>
/// <param name="State">0 found, 1 comes from an earlier step, 2 missing.</param>
internal sealed record RingScanLine(string Text, string? Found, int State);
internal sealed class RingChainRunner
{
private const uint ErrorYoureTooBusy = 0x1D;
private const long StepTimeoutMs = 15_000;
/// <summary>The player answers AC's own dialog: give them time.</summary>
private const long ManualTimeoutMs = 60_000;
private const long StepGapMs = 700;
private const long RetryDelayMs = 1_500;
private const int MaxBusyRetries = 3;
/// <summary>A missing ingredient is looked for this often and this many times (~10 s).</summary>
private const long LookAgainMs = 250;
private const int LookTries = 40;
private static readonly Regex CannotUse = new(@"^The .+ cannot be used on the .+\.$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private enum Mode { Idle, Craft, Apply }
private readonly MiniRemoteContext _ctx;
/// <summary>True while another crafting job (the tinker runner) owns the pack.</summary>
private readonly Func<bool> _blocked;
// Job (pump thread)
private Mode _mode;
private List<RingRecipe> _queue = new();
private List<(int Scroll, int Target)> _pairs = new();
private int _index, _crafted, _lookTries, _busyRetries, _confSeq, _errSeq;
private bool _waiting, _manual;
private long _stepAt, _nextAt;
// Counts before the current combine (craft) / the scroll's stack (apply).
private long _toolBefore, _targetBefore, _outputBefore;
private int _scrollStackBefore;
// Render snapshots
private volatile string _status = "idle";
private volatile RingScanLine[] _scan = Array.Empty<RingScanLine>();
private volatile (int Id, string Name)[] _scrolls = Array.Empty<(int, string)>();
private volatile bool _running;
public RingChainRunner(MiniRemoteContext ctx, Func<bool> blocked)
{
_ctx = ctx;
_blocked = blocked;
}
public bool Running => _running;
public string Status => _status;
public RingScanLine[] ScanLines => _scan;
/// <summary>The inscription scrolls the last scan found.</summary>
public (int Id, string Name)[] Scrolls => _scrolls;
private RynthCoreHost Host => _ctx.Host;
private MiniRemoteInventory Inv => _ctx.Inventory;
private CraftingTabState C => _ctx.State.Crafting;
private int Runs(string id)
{
var map = C.RingRuns;
lock (map) return map.TryGetValue(id, out int n) ? n : 0;
}
// ── Inventory ───────────────────────────────────────────────────────────
private IEnumerable<WorldObject> Carried() => Inv.Items().Where(w => !Inv.IsEquipped(w));
private WorldObject? Find(RingIngredient ing) => Carried().FirstOrDefault(w => RingChain.Matches(w.Name, ing));
private long Count(RingIngredient ing) => Carried().Where(w => RingChain.Matches(w.Name, ing)).Sum(w => (long)Inv.StackSize(w));
private long ScrollCount() => Carried().Where(w => RingChain.IsInscriptionScroll(w.Name)).Sum(w => (long)Inv.StackSize(w));
/// <summary>What a recipe makes, counted: Step 1 the enlightened quill, Step 2 the partition quill, Step 3 a scroll.</summary>
private long OutputCount(RingRecipe r) => r.Tier switch
{
1 => Count(RingChain.Recipes[1].Tool),
2 => Count(RingChain.Recipes[2].Tool),
_ => ScrollCount(),
};
// ── Scan ────────────────────────────────────────────────────────────────
/// <summary>
/// Lists every queued recipe's ingredients, marking the ones a later step only gets from an
/// earlier combine (UB-IT's "(after Step 1)"), and the carried inscription scrolls.
/// </summary>
public void Scan()
{
var lines = new List<RingScanLine>();
bool Stocked(int tier) => RingChain.Recipes
.Where(r => r.Tier == tier && Runs(r.Id) > 0)
.All(r => Find(r.Tool) != null && Find(r.Target) != null);
bool tier1 = Stocked(1), tier2 = Stocked(2);
bool any = false, blocking = false;
foreach (var r in RingChain.Recipes)
{
int runs = Runs(r.Id);
if (runs <= 0) continue;
any = true;
lines.Add(new RingScanLine($"{r.Name} x{runs}", null, 0));
foreach (var ing in new[] { r.Tool, r.Target })
{
var found = Find(ing);
if (found != null) { lines.Add(new RingScanLine(ing.Label, $"{found.Name} ({Count(ing)})", 0)); continue; }
string? later = r.Tier == 2 && !tier1 ? "(after Step 1)"
: r.Tier == 3 && !tier1 ? "(after Step 1)"
: r.Tier == 3 && !tier2 ? "(after Step 2)"
: null;
if (later == null) blocking = true;
lines.Add(new RingScanLine(ing.Label, later ?? "(not found)", later == null ? 2 : 1));
}
}
_scan = lines.ToArray();
RefreshScrolls();
_status = !any ? "set how many times to craft at least one recipe"
: blocking ? "missing ingredients are marked (not found)"
: "ready: Create runs every Step 1, then Step 2, then Step 3";
}
private void RefreshScrolls()
=> _scrolls = Carried().Where(w => RingChain.IsInscriptionScroll(w.Name))
.Select(w => (w.Id, w.Name ?? string.Empty))
.OrderBy(s => RingChain.GlyphOf(s.Item2)?.Id ?? "zzz_" + s.Item2, StringComparer.Ordinal)
.ToArray();
// ── Job control ─────────────────────────────────────────────────────────
/// <summary>Crafts the queued recipes (pump thread, after the tab's confirm).</summary>
public void Create()
{
if (_running) return;
if (_blocked()) { _status = "a tinkering job is running"; return; }
var queue = RingChain.Expand(Runs);
if (queue.Count == 0) { _status = "set how many times to craft at least one recipe"; return; }
Begin(Mode.Craft);
_queue = queue;
_status = $"crafting {queue.Count} combine(s)";
RynthLog.Write(LogCat.Crafting, $"[Crafting] Rings: create, {queue.Count} combine(s)");
}
/// <summary>Uses one scroll on the item selected in AC.</summary>
public void ApplyToSelected(int scrollId)
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) { _status = "select the ring or item in AC first"; return; }
if (unchecked((int)sel) == scrollId) { _status = "the scroll itself is selected: select the ring or item"; return; }
ApplyPairs(new List<(int, int)> { (scrollId, unchecked((int)sel)) });
}
/// <summary>Pairs the carried scrolls with these items (the last Jewelry / weapon scan) and uses them.</summary>
public void ApplyToItems(IReadOnlyList<int> targetIds)
{
RefreshScrolls();
if (_scrolls.Length == 0) { _status = "no inscription scroll in the pack (name has \"Inscription of\")"; return; }
if (targetIds.Count == 0) { _status = "scan the Jewelry or a Weapons tab first: its items are the targets"; return; }
ApplyPairs(RingChain.PairScrolls(_scrolls, targetIds));
}
private void ApplyPairs(List<(int Scroll, int Target)> pairs)
{
if (_running) return;
if (_blocked()) { _status = "a tinkering job is running"; return; }
if (pairs.Count == 0) { _status = "nothing to apply"; return; }
Begin(Mode.Apply);
_pairs = pairs;
_status = $"applying {pairs.Count} inscription(s)";
RynthLog.Write(LogCat.Crafting, $"[Crafting] Rings: apply {pairs.Count} inscription(s)");
}
private void Begin(Mode mode)
{
_mode = mode;
_index = 0;
_crafted = 0;
_lookTries = 0;
_busyRetries = 0;
_waiting = false;
_nextAt = 0;
_running = true;
}
public void Stop(string why)
{
if (_waiting && Host.HasConfirmationAnswers) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
_mode = Mode.Idle;
_waiting = false;
_running = false;
_queue = new List<RingRecipe>();
_pairs = new List<(int, int)>();
_status = why;
}
public void OnLogout()
{
Stop("idle");
_scan = Array.Empty<RingScanLine>();
_scrolls = Array.Empty<(int, string)>();
}
// ── Tick (pump thread) ──────────────────────────────────────────────────
public void Tick(long nowMs)
{
if (_mode == Mode.Idle) return;
if (_waiting) { Wait(nowMs); return; }
if (nowMs < _nextAt) return;
if (!C.AllowInCombat && !Inv.InPeaceMode) { _status = "waiting for peace mode"; return; }
if (Inv.IsBusy) return;
if (!ActionPacer.MayStart(Host, "Crafting", HealNeed.None, out string why)) { _status = "waiting: " + why; return; }
if (_mode == Mode.Craft) NextCombine(nowMs);
else NextScroll(nowMs);
}
private void NextCombine(long nowMs)
{
if (_index >= _queue.Count)
{
Stop($"done - {_crafted} combine(s)");
RefreshScrolls();
RynthLog.Write(LogCat.Crafting, $"[Crafting] Rings: done, {_crafted} combine(s)");
return;
}
var r = _queue[_index];
var tool = Find(r.Tool);
var target = Find(r.Target);
if (tool == null || target == null)
{
string label = tool == null ? r.Tool.Label : r.Target.Label;
if (++_lookTries <= LookTries)
{
_nextAt = nowMs + LookAgainMs;
_status = $"{r.Name}: looking for {label}";
return;
}
Stop($"{r.Name}: no {label} in the pack");
return;
}
_lookTries = 0;
_toolBefore = Count(r.Tool);
_targetBefore = Count(r.Target);
_outputBefore = OutputCount(r);
if (!Use(tool, target, $"Rings: {r.Name} ({_index + 1}/{_queue.Count})"))
{
Stop($"{r.Name}: the use request didn't go out");
return;
}
string ask = _manual ? " - click Yes in AC's craft dialog" : "";
_status = $"{r.Name} ({_index + 1}/{_queue.Count}): {tool.Name} on {target.Name}{ask}";
}
private void NextScroll(long nowMs)
{
if (_index >= _pairs.Count)
{
Stop($"done - {_crafted} inscription(s) applied");
RefreshScrolls();
return;
}
var (scrollId, targetId) = _pairs[_index];
var scroll = Inv.Cache?[scrollId];
var target = Inv.Cache?[targetId];
if (scroll == null || target == null)
{
// UB-IT moves on past a pair whose scroll or item is gone.
_status = $"inscription {_index + 1}: the scroll or the item is gone - skipped";
_index++;
_nextAt = nowMs + StepGapMs;
return;
}
if (Inv.IsEquipped(target)) { Stop($"{target.Name} is equipped: take it off to inscribe it"); return; }
_scrollStackBefore = Inv.StackSize(scroll);
if (!Use(scroll, target, $"Rings: {scroll.Name} on {target.Name}"))
{
Stop("the use request didn't go out");
return;
}
string ask = _manual ? " - click Yes in AC's dialog" : "";
_status = $"inscription {_index + 1}/{_pairs.Count}: {scroll.Name} on {target.Name}{ask}";
}
/// <summary>Arms the dialog answer (Yes: the player asked for this) and uses source on target.</summary>
private bool Use(WorldObject source, WorldObject target, string why)
{
_manual = !(C.AnswerCraftDialog && Host.HasConfirmationAnswers
&& Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, (int)StepTimeoutMs) == 1);
_confSeq = Host.TryGetLastConfirmation(out int cs, out _, out _, out _, out _) ? cs : 0;
_errSeq = Host.TryGetLastWeenieError(out int es, out _, out _, out _) ? es : 0;
if (!Host.UseOnFor(unchecked((uint)source.Id), unchecked((uint)target.Id), "Crafting", why, UseKind.Asked))
{
if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
return false;
}
_waiting = true;
_stepAt = Environment.TickCount64;
return true;
}
private void Wait(long nowMs)
{
if (Host.TryGetLastConfirmation(out int seq, out uint type, out int pct, out int outcome, out _)
&& seq != _confSeq && type == RynthCoreHost.ConfirmationKind.CraftInteraction)
{
_confSeq = seq;
if (outcome == RynthCoreHost.ConfirmationOutcome.Declined) { Stop("the craft dialog was answered No"); return; }
if (outcome is RynthCoreHost.ConfirmationOutcome.Shown or RynthCoreHost.ConfirmationOutcome.SendFailed)
{
_manual = true;
_status = $"click Yes in AC's craft dialog ({(pct >= 0 ? pct + "%" : "chance not shown")})";
}
}
if (Host.TryGetLastWeenieError(out int es, out uint error, out _, out _) && es != _errSeq)
{
_errSeq = es;
// Busy: the server did nothing, so the same combine can go again.
if (error == ErrorYoureTooBusy && ++_busyRetries <= MaxBusyRetries)
{
_waiting = false;
_nextAt = nowMs + RetryDelayMs;
_status = $"server says busy - trying again ({_busyRetries}/{MaxBusyRetries})";
return;
}
Stop($"the server refused it (error 0x{error:X})");
return;
}
if (Done()) { Next(nowMs); return; }
if (nowMs - _stepAt > (_manual ? ManualTimeoutMs : StepTimeoutMs))
Stop(_manual ? "no answer to AC's dialog - stopped" : "no result seen - stopped (check the pack before going on)");
}
/// <summary>The current combine or inscription went through.</summary>
private bool Done()
{
if (_mode == Mode.Craft)
{
var r = _queue[_index];
return Count(r.Tool) < _toolBefore || Count(r.Target) < _targetBefore || OutputCount(r) > _outputBefore;
}
var scroll = Inv.Cache?[_pairs[_index].Scroll];
return scroll == null || Inv.StackSize(scroll) < _scrollStackBefore;
}
private void Next(long nowMs)
{
_waiting = false;
_busyRetries = 0;
_crafted++;
_index++;
_nextAt = nowMs + StepGapMs;
}
/// <summary>"cannot be used on" ends the job: the names didn't match what the server expects.</summary>
public void OnChat(string text)
{
if (!_waiting || string.IsNullOrEmpty(text)) return;
if (CannotUse.IsMatch(text)) Stop(text);
}
}

View file

@ -5,11 +5,12 @@
// mana / retain. Every retail tinker (imbues too) uses one of the item's 10 tinker slots and the
// success chance follows RecipeManager.GetTinkerChance (TinkerMath).
//
// Server: the connected server's own recipes come from the plugin that owns it (its
// "RynthServer.Profile" JSON's "salvage" list, read by FromServerPlugin): a server plugin, or
// RynthILT for Infinite Leaftide. Nothing server-specific lives here. Their chances are the
// server's: the Crafting runner relies on the confirmation's percent.
// The player adds their own rows per world (CraftingTabState.CustomByWorld).
// Server: Infinite Leaftide / ACECustom extras, taken from UB-IT (LeaftideImbueHelper): jewelry
// rating salvages (Copper, Silver, Green Jade, Tourmaline, Serpentine, Steel), the weapon crit
// lines (Yellow Garnet, Turquoise, White Quartz, Abyssal-Touched gems, Tourmaline, Wool), Tiger
// Eye on missile weapons and Leather as the post-cap tink. ILT's recipes live in its database,
// so their chances are the server's: the Crafting runner relies on the confirmation's percent.
// Other custom shards add their own rows per world (CraftingTabState.CustomByWorld).
using System;
using System.Collections.Generic;
using RynthCore.Loot;
@ -25,7 +26,7 @@ internal enum TinkerBench
Caster,
Jewelry,
Items,
/// <summary>Trinkets (compass, goggles, scarab...): server salvage, often tier-prepared.</summary>
/// <summary>Infinite Leaftide trinkets (compass, goggles, scarab...): tier-prepared salvage.</summary>
Trinkets,
}
@ -34,9 +35,14 @@ internal enum TinkerOrigin
{
/// <summary>Stock ACE (retail) tinkering.</summary>
Retail,
/// <summary>Infinite Leaftide / ACECustom recipe.</summary>
Server,
/// <summary>A row the player added for this server.</summary>
Custom,
/// <summary>A row the server's own plugin defines (its profile's "salvage" list, ServerPackInfo.Salvage).</summary>
/// <summary>
/// A row the server's own plugin defines (its profile's "salvage" list, ServerPackInfo.Salvage).
/// Kept apart from <see cref="Server"/> so the Leaftide-only planner rules never apply to it.
/// </summary>
Plugin,
}
@ -47,24 +53,20 @@ internal enum TinkerKind
Tink,
/// <summary>One imbue per item (ImbuedEffect): a second imbue of any kind is refused.</summary>
Imbue,
/// <summary>One application (retain, heritage, a server's flag recipes...).</summary>
/// <summary>One application, tracked by its own flag (ILT jewelry ratings, retain...).</summary>
Once,
}
/// <summary>One salvage a tab can apply.</summary>
/// <param name="Id">MaterialType (131); <see cref="TinkerCatalog.RendId"/> = the weapon's damage-type rend.</param>
/// <param name="UsesTinkSlot">Counts toward the 10-tink cap.</param>
/// <param name="AppliedInt">An int property of the item: the material is on it when it reads 2 (0 = none).</param>
/// <param name="NameMatch">The bag must have this in its name (server bags that share a material id).</param>
/// <param name="AppliedInt">ILT flag int: the material is on the item when it reads 2 (0 = none).</param>
/// <param name="NameMatch">The bag must have this in its name (ILT bags that share a material id).</param>
/// <param name="Order">Apply order (lower first).</param>
/// <param name="Prepared">The bag must first be prepared on tier Ammunition: its name then carries the tier.</param>
/// <param name="AfterCap">Goes on last, and only once the item's tink slots are full.</param>
/// <param name="StackGroup">Rows with the same group share <paramref name="StackCap"/> per item ("" = none).</param>
/// <param name="StackCap">The group's combined cap per item.</param>
/// <param name="Prepared">The bag must first be prepared on tier Ammunition (ILT trinkets): its name then carries the tier.</param>
internal sealed record TinkerMaterial(
int Id, string Name, TinkerOrigin Origin, TinkerKind Kind, string Effect, int Order,
bool UsesTinkSlot = true, int AppliedInt = 0, string NameMatch = "", int Skill = 0, bool Prepared = false,
bool AfterCap = false, string StackGroup = "", int StackCap = 0);
bool UsesTinkSlot = true, int AppliedInt = 0, string NameMatch = "", int Skill = 0, bool Prepared = false);
internal static class TinkerCatalog
{
@ -91,9 +93,19 @@ internal static class TinkerCatalog
public const int Diamond = 20, Ruby = 38, GromnieHide = 54, Pyreal = 62;
/// <summary>Prepared salvage tiers: the word in the Ammunition's and the prepared bag's name.</summary>
// ILT jewelry flag ints (applied = 2).
public const int IntJewelCopper = 370, IntJewelGreenJade = 371, IntJewelSerpentine = 372,
IntJewelSilver = 374, IntJewelTourmaline = 375, IntJewelSteel = 376;
// ILT trinket flag ints (applied = 2).
public const int IntTrinketDiamond = 384, IntTrinketRuby = 385, IntTrinketGromnie = 386, IntTrinketPyreal = 387;
/// <summary>Trinket salvage tiers: the word in the Ammunition's and the prepared bag's name.</summary>
public static readonly string[] TrinketTiers = { "Minor", "Moderate", "Major" };
/// <summary>Steel and Serpentine stack on ILT jewelry, at most this many combined.</summary>
public const int JewelryStackCap = 10;
/// <summary>The ordinary tinker slots on an item.</summary>
public const int MaxTinks = 10;
@ -180,14 +192,66 @@ internal static class TinkerCatalog
[TinkerBench.Trinkets] = Array.Empty<TinkerMaterial>(),
};
private static readonly Dictionary<TinkerBench, TinkerMaterial[]> Server = new()
{
[TinkerBench.Armor] = Array.Empty<TinkerMaterial>(),
[TinkerBench.Melee] = new TinkerMaterial[]
{
new(YellowGarnet, "Yellow Garnet", TinkerOrigin.Server, TinkerKind.Once, "Biting Strike (no tink slot)", 70, UsesTinkSlot: false),
new(Turquoise, "Turquoise", TinkerOrigin.Server, TinkerKind.Once, "Crushing Blow (no tink slot)", 80, UsesTinkSlot: false),
new(WhiteQuartz, "White Quartz", TinkerOrigin.Server, TinkerKind.Once, "Cleaving (no tink slot)", 90, UsesTinkSlot: false),
new(BlackGarnet, "Abyssal-Touched Gems", TinkerOrigin.Server, TinkerKind.Once, "Crit line (bag of Abyssal-Touched Gems)", 100, NameMatch: "Abyssal"),
new(Tourmaline, "Tourmaline", TinkerOrigin.Server, TinkerKind.Once, "Crit line (no tink slot)", 104, UsesTinkSlot: false),
new(Wool, "Wool", TinkerOrigin.Server, TinkerKind.Once, "Biting Strike (no tink slot)", 108, UsesTinkSlot: false),
new(Leather, "Leather", TinkerOrigin.Server, TinkerKind.Once, "100% tink once the 10 ordinary tinks are on", 995, UsesTinkSlot: false),
},
[TinkerBench.Missile] = new TinkerMaterial[]
{
new(YellowGarnet, "Yellow Garnet", TinkerOrigin.Server, TinkerKind.Once, "Biting Strike (no tink slot)", 70, UsesTinkSlot: false),
new(Turquoise, "Turquoise", TinkerOrigin.Server, TinkerKind.Once, "Crushing Blow (no tink slot)", 80, UsesTinkSlot: false),
new(BlackGarnet, "Abyssal-Touched Gems", TinkerOrigin.Server, TinkerKind.Once, "Crit line (bag of Abyssal-Touched Gems)", 100, NameMatch: "Abyssal"),
new(Tourmaline, "Tourmaline", TinkerOrigin.Server, TinkerKind.Once, "Crit line (no tink slot)", 104, UsesTinkSlot: false),
new(Wool, "Wool", TinkerOrigin.Server, TinkerKind.Once, "Biting Strike (no tink slot)", 108, UsesTinkSlot: false),
new(TigerEye, "Tiger Eye", TinkerOrigin.Server, TinkerKind.Tink, "+missile defense bonus", 230),
new(Leather, "Leather", TinkerOrigin.Server, TinkerKind.Once, "100% tink once the 10 ordinary tinks are on", 995, UsesTinkSlot: false),
},
[TinkerBench.Caster] = new TinkerMaterial[]
{
new(YellowGarnet, "Yellow Garnet", TinkerOrigin.Server, TinkerKind.Once, "Biting Strike (no tink slot)", 70, UsesTinkSlot: false),
new(Turquoise, "Turquoise", TinkerOrigin.Server, TinkerKind.Once, "Crushing Blow (no tink slot)", 80, UsesTinkSlot: false),
new(Leather, "Leather", TinkerOrigin.Server, TinkerKind.Once, "100% tink once the 10 ordinary tinks are on", 995, UsesTinkSlot: false),
},
[TinkerBench.Jewelry] = new TinkerMaterial[]
{
// ILT keeps these in their own ints (370-376) with their own cap, not the 10 tinker slots.
new(Silver, "Silver", TinkerOrigin.Server, TinkerKind.Once, "+1 critical damage rating", 10, UsesTinkSlot: false, AppliedInt: IntJewelSilver),
new(Copper, "Copper", TinkerOrigin.Server, TinkerKind.Once, "+1 damage rating", 20, UsesTinkSlot: false, AppliedInt: IntJewelCopper),
new(GreenJade, "Green Jade", TinkerOrigin.Server, TinkerKind.Once, "+1 damage resist rating", 30, UsesTinkSlot: false, AppliedInt: IntJewelGreenJade),
new(Tourmaline, "Tourmaline", TinkerOrigin.Server, TinkerKind.Once, "+1 critical damage resist rating", 40, UsesTinkSlot: false, AppliedInt: IntJewelTourmaline),
new(Serpentine, "Serpentine", TinkerOrigin.Server, TinkerKind.Tink, "+1 critical rating (stacks with Steel, 10 max)", 50, UsesTinkSlot: false),
new(Steel, "Steel", TinkerOrigin.Server, TinkerKind.Tink, "Steel stack tier (stacks with Serpentine, 10 max)", 60, UsesTinkSlot: false),
},
[TinkerBench.Items] = Array.Empty<TinkerMaterial>(),
// UB-IT LeaftideImbueHelper trinket imbues: Diamond, Ruby, Gromnie Hide, Pyreal, in that order.
[TinkerBench.Trinkets] = new TinkerMaterial[]
{
new(Diamond, "Diamond", TinkerOrigin.Server, TinkerKind.Once, "Trinket tier: Diamond", 10, UsesTinkSlot: false, AppliedInt: IntTrinketDiamond, Prepared: true),
new(Ruby, "Ruby", TinkerOrigin.Server, TinkerKind.Once, "Trinket tier: Ruby", 20, UsesTinkSlot: false, AppliedInt: IntTrinketRuby, Prepared: true),
new(GromnieHide, "Gromnie Hide", TinkerOrigin.Server, TinkerKind.Once, "Trinket tier: Gromnie Hide", 30, UsesTinkSlot: false, AppliedInt: IntTrinketGromnie, Prepared: true),
new(Pyreal, "Pyreal", TinkerOrigin.Server, TinkerKind.Once, "Trinket tier: Pyreal", 40, UsesTinkSlot: false, AppliedInt: IntTrinketPyreal, Prepared: true),
},
};
/// <summary>The retail rows of a tab.</summary>
public static IReadOnlyList<TinkerMaterial> RetailFor(TinkerBench bench) => Retail[bench];
/// <summary>The Infinite Leaftide / ACECustom rows of a tab.</summary>
public static IReadOnlyList<TinkerMaterial> ServerFor(TinkerBench bench) => Server[bench];
/// <summary>
/// A server plugin's salvage rows for one tab (its profile's "salvage" list). Rows for other
/// tabs, unknown tab names and unknown kinds are left out. A row's own "order" decides where it
/// runs; without one, imbues run before tinks and one-application rows after them, each in the
/// plugin's list order.
/// tabs, unknown tab names and unknown kinds are left out; imbues run before tinks, and
/// one-application rows after them, each in the plugin's own order.
/// </summary>
public static List<TinkerMaterial> FromServerPlugin(TinkerBench bench, IEnumerable<RynthCore.Plugin.Shared.ServerSalvageView>? salvage)
{
@ -212,23 +276,18 @@ internal static class TinkerCatalog
TinkerKind.Once => 600,
_ => 400,
} + i++;
if (s.Order != 0) order = s.Order;
string group = s.StackCap > 0 ? (s.StackGroup ?? string.Empty).Trim() : string.Empty;
rows.Add(new TinkerMaterial(s.Material, MaterialName(s.Material), TinkerOrigin.Plugin, kind.Value,
string.IsNullOrWhiteSpace(s.Effect) ? "server recipe" : s.Effect.Trim(), order,
UsesTinkSlot: s.UsesTinkSlot, AppliedInt: s.AppliedInt, NameMatch: s.NameMatch ?? string.Empty,
Prepared: s.Prepared, AfterCap: s.AfterCap, StackGroup: group, StackCap: group.Length > 0 ? s.StackCap : 0));
UsesTinkSlot: s.UsesTinkSlot, NameMatch: s.NameMatch ?? string.Empty));
}
return rows;
}
/// <summary>
/// Settings key for a row: retail and server rows of one tab share ids (Wool, Steel...). Keys
/// with the old "s" prefix (RynthAi's own Leaftide rows before they moved to RynthILT) match no row.
/// </summary>
/// <summary>Settings key for a row: retail and server rows of one tab share ids (Wool, Steel...).</summary>
public static string Key(TinkerMaterial m) => m.Origin switch
{
TinkerOrigin.Retail => "r" + m.Id,
TinkerOrigin.Server => "s" + m.Id,
TinkerOrigin.Plugin => "p" + m.Id,
_ => "c" + m.Id,
};
@ -247,8 +306,8 @@ internal static class TinkerCatalog
};
/// <summary>
/// Trinkets (compass, goggles, scarab, watch, puzzle box, tops) are jewelry the Jewelry tab
/// leaves alone: they take the Trinkets tab's recipes instead (UB-IT IsLeaftideTrinketJewelry).
/// ILT trinkets (compass, goggles, scarab, watch, puzzle box, tops) are jewelry the Jewelry
/// tab leaves alone: they take the trinket recipes instead (UB-IT IsLeaftideTrinketJewelry).
/// </summary>
public static bool IsTrinket(string name)
{
@ -301,7 +360,7 @@ internal static class TinkerCatalog
};
}
/// <summary>The rend gem a Foolproof bag's name advertises (server bags may not set Material), else 0.</summary>
/// <summary>The rend gem a Foolproof bag's name advertises (ILT bags may not set Material), else 0.</summary>
public static int RendFromFoolproofName(string name)
{
if (string.IsNullOrEmpty(name) || name.IndexOf("Foolproof", StringComparison.OrdinalIgnoreCase) < 0) return 0;

View file

@ -2,17 +2,17 @@
//
// Pure: the scan reads the item into TinkerItemFacts and the runner re-plans from fresh facts,
// so these rules are the only place the apply order and caps live (and the host tests drive
// them directly). Server rows say which rules apply to them (TinkerMaterial, from the server
// plugin's profile); nothing here knows a server:
// * rows run in TinkerMaterial.Order (imbues and server crit lines before stat tinks; with
// them directly):
// * rows run in TinkerMaterial.Order (imbues and ILT crit lines before stat tinks; with
// "rend last" the rend moves to the end, the way UB-IT's foolproof-rend option does);
// * a tink-slot row is cut to the free slots (10 minus the item's tinks); no-slot rows aren't;
// * a tink-slot row is cut to the free slots (10 minus the item's tinks); ILT's no-slot
// salvages aren't;
// * one imbue per item (the item's own, or the first planned one);
// * a row with an applied int is skipped once that int reads 2 on the item;
// * rows of one stack group stop at the group's cap combined;
// * an after-cap row goes on last, once, and only when the tink slots are full;
// * a prepared row needs a bag prepared at the chosen tier (its name says Minor, Moderate or
// Major); a raw bag becomes one on that tier's Ammunition.
// * an ILT flag row (jewelry Copper...) is skipped once its flag reads 2;
// * ILT jewelry Steel + Serpentine stop at 10 combined;
// * ILT Leather on a weapon goes on once, after the 10 ordinary tinks are on;
// * an ILT trinket salvage needs a bag prepared at the chosen tier (its name says Minor,
// Moderate or Major); a raw bag becomes one on that tier's Ammunition.
using System;
using System.Collections.Generic;
using System.Linq;
@ -39,7 +39,7 @@ internal sealed class TinkerItemFacts
/// <summary>ItemMaxMana (108).</summary>
public int MaxMana;
public bool Equipped;
/// <summary>Reads an int property of the item (a row's applied int: 2 = that salvage is on).</summary>
/// <summary>Reads an ILT flag int (370-376); 2 = that salvage is on.</summary>
public Func<int, int> FlagInt = _ => 0;
}
@ -51,9 +51,16 @@ internal readonly record struct TinkerBagChoice(int Id, double Workmanship, doub
internal static class TinkerPlanner
{
/// <summary>
/// The rows a tab offers on this world: retail, the server's (ILT-like worlds) and the
/// player's custom rows for this world.
/// </summary>
public static List<TinkerMaterial> Rows(TinkerBench bench, bool iltWorld, IEnumerable<CustomTinker>? custom)
=> Rows(bench, iltWorld ? TinkerCatalog.ServerFor(bench) : null, custom);
/// <summary>
/// The rows a tab offers: retail, then <paramref name="server"/> (the connected server's own
/// salvage, from the plugin that owns it), then the player's custom rows.
/// salvage: RynthAi's Leaftide rows on ILT, or the server plugin's), then the player's custom rows.
/// </summary>
public static List<TinkerMaterial> Rows(TinkerBench bench, IEnumerable<TinkerMaterial>? server, IEnumerable<CustomTinker>? custom)
{
@ -91,8 +98,8 @@ internal static class TinkerPlanner
/// <summary>
/// The ordered steps for one item (empty when nothing ticked applies).
/// <paramref name="attempted"/> is how many times this run already tried a row key on the
/// item: the item's tinks count failures too, but no-slot server rows and the ticked counts
/// don't show on it, so a re-plan would otherwise repeat them.
/// item: the item's tinks count failures too, but ILT rows and the ticked counts don't show
/// on it, so a re-plan would otherwise repeat them.
/// </summary>
public static List<TinkerStep> Plan(TinkerBench bench, TinkerItemFacts item, TinkerBenchSettings s,
IReadOnlyList<TinkerMaterial> rows, Func<string, int>? attempted = null)
@ -100,8 +107,9 @@ internal static class TinkerPlanner
var steps = new List<TinkerStep>();
int free = Math.Max(0, TinkerCatalog.MaxTinks - item.Tinks);
bool imbueTaken = item.Imbued;
Dictionary<string, int>? stacked = null;
List<TinkerStep>? afterCap = null;
int jewelryStack = 0;
TinkerStep? leatherLast = null;
bool weapon = bench is TinkerBench.Melee or TinkerBench.Missile or TinkerBench.Caster;
foreach (var row in rows.OrderBy(r => OrderOf(r, s)))
{
@ -121,16 +129,15 @@ internal static class TinkerPlanner
imbueTaken = true;
}
if (row.AppliedInt != 0 && item.FlagInt(row.AppliedInt) == 2) continue;
if (row.StackGroup.Length > 0 && row.StackCap > 0)
if (bench == TinkerBench.Jewelry && row.Origin == TinkerOrigin.Server
&& material is TinkerCatalog.Steel or TinkerCatalog.Serpentine)
{
stacked ??= new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
int used = stacked.TryGetValue(row.StackGroup, out int u) ? u : 0;
n = Math.Min(n, row.StackCap - used);
stacked[row.StackGroup] = used + Math.Max(0, n);
n = Math.Min(n, TinkerCatalog.JewelryStackCap - jewelryStack);
jewelryStack += Math.Max(0, n);
}
if (row.AfterCap)
if (weapon && row.Origin == TinkerOrigin.Server && material == TinkerCatalog.Leather)
{
(afterCap ??= new List<TinkerStep>()).Add(new TinkerStep(row, material));
leatherLast = new TinkerStep(row, material);
continue;
}
if (row.UsesTinkSlot)
@ -140,7 +147,7 @@ internal static class TinkerPlanner
}
for (int i = 0; i < n; i++) steps.Add(new TinkerStep(row, material));
}
if (afterCap != null && free == 0) steps.AddRange(afterCap);
if (leatherLast is TinkerStep leather && free == 0) steps.Add(leather);
return steps;
}
@ -158,7 +165,7 @@ internal static class TinkerPlanner
}
/// <summary>
/// Whether a salvage bag can serve a step: a full bag (100 units) of the material, server bags
/// Whether a salvage bag can serve a step: a full bag (100 units) of the material, ILT bags
/// matched by name (Abyssal-Touched Gems share Black Garnet's id, Foolproof rend bags may not
/// carry a material at all).
/// </summary>
@ -176,7 +183,7 @@ internal static class TinkerPlanner
return step.Row.Id == TinkerCatalog.RendId && TinkerCatalog.RendFromFoolproofName(bagName) == step.Material;
}
/// <summary>The prepared tier a name carries (0 Minor, 1 Moderate, 2 Major), else -1.</summary>
/// <summary>The trinket tier a name carries (0 Minor, 1 Moderate, 2 Major), else -1.</summary>
public static int TierOf(string name)
{
name ??= string.Empty;
@ -185,11 +192,11 @@ internal static class TinkerPlanner
return -1;
}
/// <summary>A full, not yet prepared bag of a prepared row's salvage (no tier in its name).</summary>
/// <summary>A full, not yet prepared bag of a trinket salvage (no tier in its name).</summary>
public static bool IsRawTrinketBag(int material, string bagName, int bagMaterial, int bagUses)
=> bagUses >= 100 && bagMaterial == material && TierOf(bagName) < 0;
/// <summary>The Ammunition that prepares a raw bag into a tier bag.</summary>
/// <summary>The Ammunition that prepares a raw trinket bag into a tier bag.</summary>
public static bool IsTierAmmunition(string name, int tier)
=> (name ?? string.Empty).IndexOf("Ammunition", StringComparison.OrdinalIgnoreCase) >= 0
&& TierOf(name!) == Math.Clamp(tier, 0, TinkerCatalog.TrinketTiers.Length - 1);

View file

@ -11,11 +11,10 @@
// confirmation, "cannot be used on", or a WeenieError (YoureTooBusy retries).
// Without the v81 engine (or with dialog answering off) AC shows its own dialog and the player
// clicks it; the runner waits longer for that.
// Prepared rows (a server's trinket salvage): with no bag prepared at the chosen tier, a raw bag
// is first used on that tier's Ammunition (UB-IT's "prep salvage") and the step runs once the
// prepared bag shows up.
// Items a run finished are left out of later scans this session, so server rows that don't show
// on the item aren't applied twice and "auto next batch" moves on to the next items.
// Trinkets: with no bag prepared at the chosen tier, a raw bag is first used on that tier's
// Ammunition (UB-IT's "prep salvage") and the step runs once the prepared bag shows up.
// Items a run finished are left out of later scans this session, so ILT rows that don't show on
// the item aren't applied twice and "auto next batch" moves on to the next items.
using System;
using System.Collections.Generic;
using System.Linq;
@ -56,7 +55,7 @@ internal sealed class TinkerRunner
private const int MaxRetries = 3;
/// <summary>Appraisal requests one scan may send (the Items tab sees the whole pack).</summary>
private const int MaxAppraisalsPerScan = 25;
/// <summary>UB-IT polls up to ~30 s for the prepared bag.</summary>
/// <summary>UB-IT polls up to ~30 s for the prepared trinket bag.</summary>
private const long PrepTimeoutMs = 30_000;
/// <summary>Auto next batch: re-scan while items are still being appraised, this often and this many times.</summary>
private const long AutoRescanDelayMs = 3_000;
@ -89,7 +88,7 @@ internal sealed class TinkerRunner
private bool _manual;
private long _stepAt, _nextAt;
private Dictionary<int, TinkerRow> _byId = new();
/// <summary>The wait is for a bag being prepared, not a tinker.</summary>
/// <summary>The wait is for a trinket bag being prepared, not a tinker.</summary>
private bool _prep;
private int _prepsThisItem;
/// <summary>Bags this batch used up (auto next batch stops after a batch that used none).</summary>
@ -117,6 +116,8 @@ internal sealed class TinkerRunner
/// <summary>A job is on (set by Start, cleared by Stop: the queue empties before the batch-done step runs).</summary>
public bool Running => _active;
private volatile bool _active;
/// <summary>True while another crafting job (the Rings chain) owns the pack.</summary>
public Func<bool> Blocked { get; set; } = () => false;
public TinkerBench Bench => _bench;
public string Status => _status;
/// <summary>The last scan's rows (for <see cref="ScannedBench"/>).</summary>
@ -238,6 +239,7 @@ internal sealed class TinkerRunner
public void Start(TinkerBench bench)
{
if (Running) return;
if (Blocked()) { _status = "the Rings chain is running"; return; }
if (_scannedBench != (int)bench || _scan.Length == 0) { _status = "scan first"; return; }
_bench = bench;
_queue.Clear();
@ -434,7 +436,7 @@ internal sealed class TinkerRunner
_status = $"{facts.Name}: applying {_bagName}{pctText}{ask}";
}
/// <summary>The full bags that can serve a step (prepared rows: prepared at the chosen tier).</summary>
/// <summary>The full bags that can serve a step (trinket steps: prepared at the chosen tier).</summary>
private List<WorldObject> BagsFor(TinkerStep step)
=> Inv.Items()
.Where(b => b.ObjectClass == AcObjectClass.Salvage
@ -442,7 +444,7 @@ internal sealed class TinkerRunner
.ToList();
/// <summary>
/// No prepared bag: use a raw one on the tier's Ammunition (UB-IT's prep). The wait
/// No prepared trinket bag: use a raw one on the tier's Ammunition (UB-IT's prep). The wait
/// ends when a prepared bag shows up; the next tick then applies it.
/// </summary>
private void Prepare(long nowMs, TinkerStep step, string key, string matName)
@ -464,7 +466,7 @@ internal sealed class TinkerRunner
_step = step;
_prep = true;
if (!Host.UseOnFor(unchecked((uint)raw.Id), unchecked((uint)ammo.Id), "Crafting",
$"{TinkerCatalog.Label(_bench)}: prepare {matName} on {ammo.Name}", UseKind.Asked))
$"Trinkets: prepare {matName} on {ammo.Name}", UseKind.Asked))
{
if (!_manual) Host.ArmConfirmation(RynthCoreHost.ConfirmationKind.CraftInteraction, 0, 0);
Retry(nowMs, "the prepare request didn't go out");

View file

@ -1,15 +1,15 @@
// CraftingTab.cs - The Mini Remote's universal "Crafting" tab (every world, like Quests and Pets).
//
// UB-IT's crafting benches, one sub-tab each: Armor, Weapons (Melee / Missile / Caster),
// Jewelry, Trinkets and Items tinkering. (Infinite Leaftide's own crafting - chunking / clap,
// split arrows, the Rings inscription chain - belongs in RynthILT.) Every tinker tab has two
// sections:
// Jewelry, Trinkets and Items tinkering, and the Rings inscription chain. (Infinite Leaftide's
// chunking / clap and split-arrow tools stay on RynthILT's Gear tab.) Every tinker tab has
// two sections:
// * Retail tinkering - stock ACE salvage (TinkerCatalog.Retail), chance from TinkerMath;
// * Server tinkering - the connected server's own salvage, from the plugin that owns it (its
// "RynthServer.Profile" JSON's "salvage" list, MiniRemoteContext.ServerSalvage; RynthILT's on
// Infinite Leaftide), then the player's own rows for this world (CraftingTabState.CustomByWorld).
// With none defined it says so.
// One TinkerRunner works one tab's scan at a time.
// * Server tinkering - the connected server's own salvage: RynthAi's built-in rows on
// Infinite Leaftide, otherwise the active server plugin's (its profile's "salvage" list,
// MiniRemoteContext.ServerSalvage), then the player's own rows for this world
// (CraftingTabState.CustomByWorld). With none defined it says so.
// One TinkerRunner works one tab's scan at a time; the RingChainRunner and it never run together.
using System;
using System.Collections.Generic;
using System.Linq;
@ -25,6 +25,7 @@ internal sealed class CraftingTab
private readonly MiniRemoteContext _ctx;
public TinkerRunner Runner { get; }
public RingChainRunner Rings { get; }
// Custom-row editor (render thread only)
private int _newMaterial = TinkerCatalog.Steel;
@ -39,6 +40,8 @@ internal sealed class CraftingTab
{
_ctx = ctx;
Runner = new TinkerRunner(ctx, RowsFor, SettingsFor);
Rings = new RingChainRunner(ctx, () => Runner.Running);
Runner.Blocked = () => Rings.Running;
}
private CraftingTabState C => _ctx.State.Crafting;
@ -69,20 +72,35 @@ internal sealed class CraftingTab
private IReadOnlyList<TinkerMaterial> RowsFor(TinkerBench bench)
=> TinkerPlanner.Rows(bench, ServerRowsFor(bench), CustomRows());
/// <summary>The connected server's own salvage for a bench: what its plugin's profile defines.</summary>
/// <summary>
/// The connected server's own salvage for a bench: RynthAi's built-in rows on Infinite Leaftide
/// (RynthILT says so), otherwise what the active server plugin's profile defines.
/// </summary>
private IReadOnlyList<TinkerMaterial> ServerRowsFor(TinkerBench bench)
=> TinkerCatalog.FromServerPlugin(bench, _ctx.ServerSalvage);
=> _ctx.Ilt.IsIltWorld ? TinkerCatalog.ServerFor(bench) : TinkerCatalog.FromServerPlugin(bench, _ctx.ServerSalvage);
/// <summary>The connected server defines salvage for at least one bench.</summary>
private bool ServerHasSalvage => _ctx.ServerSalvage.Count > 0;
private bool ServerHasSalvage => _ctx.Ilt.IsIltWorld || _ctx.ServerSalvage.Count > 0;
// ── Lifecycle (MiniRemoteController) ─────────────────────────────────────────────────────────
public void Tick(long nowMs) => Runner.Tick(nowMs);
public void Tick(long nowMs)
{
Runner.Tick(nowMs);
Rings.Tick(nowMs);
}
public void OnChat(string text) => Runner.OnChat(text);
public void OnChat(string text)
{
Runner.OnChat(text);
Rings.OnChat(text);
}
public void OnLogout() => Runner.OnLogout();
public void OnLogout()
{
Runner.OnLogout();
Rings.OnLogout();
}
// ── UI (render thread) ──────────────────────────────────────────────────
@ -103,13 +121,26 @@ internal sealed class CraftingTab
}
if (ImGui.BeginTabItem("Jewelry")) { RenderBench(TinkerBench.Jewelry); ImGui.EndTabItem(); }
if (ImGui.BeginTabItem("Trinkets")) { RenderBench(TinkerBench.Trinkets); ImGui.EndTabItem(); }
if (ImGui.BeginTabItem("Rings"))
{
IltOnlyNote();
RenderRings();
ImGui.EndTabItem();
}
if (ImGui.BeginTabItem("Items")) { RenderBench(TinkerBench.Items); ImGui.EndTabItem(); }
ImGui.EndTabBar();
}
private void IltOnlyNote()
{
if (!_ctx.Ilt.IsIltWorld)
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "Infinite Leaftide recipes: this server may not have them.");
}
private void RenderBench(TinkerBench bench)
{
var s = SettingsFor(bench);
bool ilt = _ctx.Ilt.IsIltWorld;
string world = _ctx.WorldName;
bool weapon = bench is TinkerBench.Melee or TinkerBench.Missile or TinkerBench.Caster;
ImGui.PushID((int)bench);
@ -133,8 +164,8 @@ internal sealed class CraftingTab
if (serverRows.Count > 0)
{
RenderRows(s, serverRows, "server");
if (serverRows.Any(r => !r.UsesTinkSlot && r.AppliedInt == 0))
ImGui.TextDisabled("Rows without a tink slot don't show on the item: a run applies each once, and items\n"
if (ilt && weapon)
SafeImGui.TextDisabled("These weapon lines don't show on the item: a run applies each once, and items\n"
+ "finished this session are left out of later scans (Forget brings them back).");
}
else if (ServerHasSalvage)
@ -178,7 +209,7 @@ internal sealed class CraftingTab
}
}
/// <summary>Trinkets: the prepared salvage tier and whether to prepare raw bags on the tier's Ammunition.</summary>
/// <summary>Trinkets: the salvage tier and whether to prepare raw bags on the tier's Ammunition.</summary>
private void RenderTrinketOptions()
{
int tier = Math.Clamp(C.TrinketTier, 0, TinkerCatalog.TrinketTiers.Length - 1);
@ -253,7 +284,7 @@ internal sealed class CraftingTab
if (world.Length == 0) { ImGui.TextDisabled("Log in to add rows for this server."); return; }
var mine = CustomRows().Where(c => c.Bench == (int)bench).ToList();
var rows = TinkerPlanner.Rows(bench, null, mine).Where(r => r.Origin == TinkerOrigin.Custom).ToList();
var rows = TinkerPlanner.Rows(bench, false, mine).Where(r => r.Origin == TinkerOrigin.Custom).ToList();
if (rows.Count == 0) ImGui.TextDisabled("None yet.");
for (int i = 0; i < rows.Count; i++)
{
@ -370,7 +401,7 @@ internal sealed class CraftingTab
if (ImGui.SmallButton("Forget")) _ctx.Post(() => Runner.ForgetDone(bench));
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
ImGui.SetTooltip("Let finished items show in scans again (server rows that don't show on the item could go on twice).");
ImGui.SetTooltip("Let finished items show in scans again (Leaftide lines that don't show on the item could go on twice).");
}
bool running = Runner.Running;
@ -378,7 +409,7 @@ internal sealed class CraftingTab
ImGui.BeginDisabled(running);
if (ImGui.Button("Scan")) _ctx.Post(() => Runner.Scan(bench));
ImGui.SameLine();
ImGui.BeginDisabled(!mine || Runner.Rows.Length == 0);
ImGui.BeginDisabled(!mine || Runner.Rows.Length == 0 || Rings.Running);
if (ImGui.Button("Start"))
{
int n = Runner.Rows.Length;
@ -398,6 +429,8 @@ internal sealed class CraftingTab
ImGui.SameLine();
if (running && Runner.Bench != bench)
SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, $"{TinkerCatalog.Label(Runner.Bench)} is running");
else if (Rings.Running)
ImGui.TextColored(LegacyDashboardRenderer.ColAmber, "the Rings chain is running");
else
SafeImGui.TextDisabled(Runner.Status);
@ -431,4 +464,125 @@ internal sealed class CraftingTab
}
ImGui.EndTable();
}
// ── Rings ───────────────────────────────────────────────────────────────
/// <summary>The ring inscription chain: runs per recipe, Scan / Create / Stop, then the scrolls.</summary>
private void RenderRings()
{
ImGui.TextDisabled("Quill of Infliction -> Enlightened Quill -> partition quill -> glyph -> Inscription scroll -> ring.");
if (ImGui.BeginTable("##ringrecipes", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Runs", ImGuiTableColumnFlags.WidthFixed, 100);
ImGui.TableSetupColumn("Recipe");
var runs = C.RingRuns;
foreach (var r in RingChain.Recipes)
{
ImGui.PushID(r.Id);
ImGui.TableNextRow();
ImGui.TableNextColumn();
int n;
lock (runs) n = runs.TryGetValue(r.Id, out int v) ? v : 0;
ImGui.SetNextItemWidth(90);
if (ImGui.InputInt("##runs", ref n, 1))
{
n = Math.Clamp(n, 0, RingChain.MaxRuns);
lock (runs)
{
if (n == 0) runs.Remove(r.Id);
else runs[r.Id] = n;
}
}
ImGui.TableNextColumn();
ImGui.TextUnformatted(r.Name);
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(r.Notes);
ImGui.PopID();
}
ImGui.EndTable();
}
bool running = Rings.Running;
bool tinkering = Runner.Running;
ImGui.BeginDisabled(running);
if (ImGui.Button("Scan##rings")) _ctx.Post(() => Rings.Scan());
ImGui.SameLine();
ImGui.BeginDisabled(tinkering);
if (ImGui.Button("Create"))
{
int total = RingChain.Expand(id => { lock (C.RingRuns) return C.RingRuns.TryGetValue(id, out int v) ? v : 0; }).Count;
_ctx.Confirm("Rings chain", $"Craft {total} combine(s)?\n\nEvery Step 1 run goes first, then Step 2, then Step 3.\nThe ingredients are used up.",
() => Rings.Create(), "Create");
}
ImGui.EndDisabled();
ImGui.EndDisabled();
ImGui.SameLine();
ImGui.BeginDisabled(!running);
if (ImGui.Button("Stop##rings")) _ctx.Post(() => Rings.Stop("stopped by player"));
ImGui.EndDisabled();
ImGui.SameLine();
if (tinkering) SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, $"{TinkerCatalog.Label(Runner.Bench)} tinkering is running");
else SafeImGui.TextDisabled(Rings.Status);
var lines = Rings.ScanLines;
if (lines.Length > 0 && ImGui.BeginTable("##ringscan", 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.Borders | ImGuiTableFlags.SizingStretchProp))
{
foreach (var l in lines)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
if (l.Found == null) { SafeImGui.TextColored(LegacyDashboardRenderer.ColTeal, l.Text); continue; }
ImGui.TextUnformatted(" " + l.Text);
ImGui.TableNextColumn();
if (l.State == 0) ImGui.TextUnformatted(l.Found);
else if (l.State == 1) SafeImGui.TextDisabled(l.Found);
else SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, l.Found);
}
ImGui.EndTable();
}
ImGui.Separator();
RenderScrolls(running || tinkering);
}
/// <summary>The carried inscription scrolls: one to the selected item, or all to the last scan's items.</summary>
private void RenderScrolls(bool busy)
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Inscription scrolls");
var scrolls = Rings.Scrolls;
if (scrolls.Length == 0) { ImGui.TextDisabled("None carried (Scan to look again)."); return; }
ImGui.BeginDisabled(busy);
foreach (var (id, name) in scrolls)
{
ImGui.PushID(id);
if (ImGui.SmallButton("Apply to selected"))
{
int scrollId = id;
string scrollName = name;
_ctx.Confirm("Ring inscription", $"Use {scrollName} on the item selected in AC?",
() => Rings.ApplyToSelected(scrollId), "Apply");
}
ImGui.SameLine();
ImGui.TextUnformatted(name);
ImGui.PopID();
}
// UB-IT pairs the scrolls with the last Jewelry or weapon scan's items.
int scanned = Runner.ScannedBench;
bool usable = scanned is (int)TinkerBench.Jewelry or (int)TinkerBench.Melee or (int)TinkerBench.Missile or (int)TinkerBench.Caster;
var targets = usable ? Runner.Rows.Select(r => r.Id).ToList() : new List<int>();
string from = usable ? TinkerCatalog.Label((TinkerBench)scanned) : "Jewelry / Weapons";
ImGui.BeginDisabled(targets.Count == 0);
if (ImGui.Button($"Apply all to the last {from} scan ({targets.Count})"))
{
int pairs = Math.Min(targets.Count, scrolls.Length);
_ctx.Confirm("Ring inscriptions", $"Use {pairs} inscription scroll(s) on the items of the last {from} scan, one each?",
() => Rings.ApplyToItems(targets), "Apply");
}
ImGui.EndDisabled();
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
SafeImGui.SetTooltip("Scrolls in glyph order go on the scanned items in id order (UB-IT's pairing).\n"
+ "Scan the Jewelry or a Weapons tab first.");
ImGui.EndDisabled();
}
}

View file

@ -35,7 +35,7 @@ internal sealed class MiniRemoteController
/// <summary>Where the quest UI went (chat reply for the retired "/ra quests" verbs and tab names).</summary>
public const string QuestsMovedText =
"[Mini Remote] Quests moved to RynthOracle: /ro (Quests tab: timers, tracking, rewards), /ro timers (Quest Timers window).";
"[Mini Remote] Quests moved to RynthOracle: /ro (Quests tab: timers, tracking, rewards, /qb), /ro timers (Quest Timers window).";
private readonly MiniRemoteContext _ctx;
private readonly Func<QuestTracker?> _quests;
@ -45,7 +45,7 @@ internal sealed class MiniRemoteController
private bool _confirmOpened;
public PetsTab Pets { get; }
/// <summary>The Crafting tab (tinker benches and server salvage; any world). SilentKelpie's.</summary>
/// <summary>The Crafting tab (tinker benches and the Rings chain; any world).</summary>
public CraftingTab Crafting { get; }
public VTankUsdImporter Usd { get; }
@ -113,13 +113,14 @@ internal sealed class MiniRemoteController
}
}
/// <summary>Pump-thread chat line (the heal pet's heal). Never eats.</summary>
/// <summary>Pump-thread chat line (the heal pet's heal, a tinker run's results). Never eats.</summary>
public void OnChat(string text)
{
if (string.IsNullOrEmpty(text)) return;
try { Pets.OnChat(text.TrimEnd('\r', '\n')); }
string line = text.TrimEnd('\r', '\n');
try { Pets.OnChat(line); }
catch (Exception ex) { RynthLog.Exception(LogCat.Pets, ex, "PetsTab.OnChat"); }
try { Crafting.OnChat(text.TrimEnd('\r', '\n')); }
try { Crafting.OnChat(line); }
catch (Exception ex) { RynthLog.Exception(LogCat.Crafting, ex, "CraftingTab.OnChat"); }
}
@ -220,11 +221,10 @@ internal sealed class MiniRemoteController
// ── Commands ────────────────────────────────────────────────────────────
/// <summary>
/// "/ra hub [show|hide|toggle|open pets|crafting [show|hide|toggle]|open breeding|tab pets|crafting|breeding|remote]",
/// "/ra hub [show|hide|toggle|open pets|breeding|crafting [show|hide|toggle]|tab pets|breeding|crafting|remote]",
/// "/ra quests [refresh]", "/ra pets [show|hide|toggle]"; every other "/ra hub ..." verb,
/// "/ra guardian ..." and "/ra bounty|bounties|bountys ..." go to RynthILT. The retired quest
/// verbs and tab names ("/ra quests window", "/ra hub open quests", ...) say where quests went,
/// and "/ra hub open|tab character" opens RynthOracle's Character tab (Huds/MovedTabs.cs).
/// verbs and tab names ("/ra quests window", "/ra hub open quests", ...) say where quests went.
/// Returns false if not handled.
/// </summary>
public bool HandleCommand(string verb, string[] args)
@ -254,14 +254,22 @@ internal sealed class MiniRemoteController
_ctx.Chat(QuestsMovedText);
return true;
}
// "/ra hub open|tab character": the Character tab left the Mini Remote (2026-10-13);
// HudController.HandleTabCommand opens RynthOracle's Character tab.
// "/ra hub open|tab character|charms|banking": those left the Mini Remote (2026-10-13);
// HudController.HandleTabCommand opens RynthOracle's Character tab or Global Inventory > Banking.
if (cmd is "open" or "tab" && args.Length > 1 && Huds.MovedTabs.CommandFor(args[1]) != null)
{
string? reply = MiniRemoteTabCommand?.Invoke(args[1].Trim().ToLowerInvariant(), "show");
if (cmd == "open" && reply != null) _ctx.Chat("[Mini Remote] " + reply);
return true;
}
// "/ra hub open|tab breeding": the Pets tab on its Breeding sub-tab (RynthOracle's Pet Breeding tab links here).
if (cmd is "open" or "tab" && args.Length > 1 && args[1].Trim().ToLowerInvariant() is "breeding" or "breed")
{
Pets.SelectBreeding();
if (cmd == "open") OpenTab(MiniRemoteTabs.Pets, "show");
else MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Pets, "select");
return true;
}
switch (cmd)
{
case "show":
@ -270,9 +278,6 @@ internal sealed class MiniRemoteController
// The Mini Remote is the Hub's main window.
_ctx.Chat(MiniRemoteCommand != null ? MiniRemoteCommand(cmd) : "[Mini Remote] The Mini Remote is not available yet.");
return true;
case "open" or "tab" when args.Length > 1 && IsBreedingTabName(args[1]):
OpenBreeding(cmd);
return true;
case "open" when args.Length > 1 && MiniRemoteTabs.Parse(args[1]) is { } openTab:
OpenTab(openTab, args.Length > 2 ? args[2] : "toggle");
return true;
@ -299,37 +304,10 @@ internal sealed class MiniRemoteController
private void PrintHelp()
{
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote) /ra hub open pets|crafting [show|hide|toggle] /ra hub open breeding (ILT)");
_ctx.Chat("[Mini Remote] /ra hub [show|hide|toggle] (Mini Remote) /ra hub open pets|crafting [show|hide|toggle]");
_ctx.Chat("[Mini Remote] /ra quests refresh (quiet /myquests) /ra pets [show|hide] Quest list, timers and rewards: RynthOracle (/ro).");
_ctx.Chat("[Mini Remote] Banking, gear, charms, games, the Guardian, bounties, /ra hub attr ...: Infinite Leaftide, the RynthILT plugin.");
_ctx.Chat("[Mini Remote] Character overview and session: RynthOracle (/ro character). Force a server: /rc diagnostics.");
}
/// <summary>"breeding" / "breed": the Pets tab's Breeding sub-tab (RynthILT's tracker, Infinite Leaftide).</summary>
private static bool IsBreedingTabName(string text) => text.Trim().ToLowerInvariant() is "breeding" or "breed";
/// <summary>
/// "/ra hub open|tab breeding": the Pets tab on its Breeding sub-tab when RynthILT offers it. "open"
/// shows the Mini Remote and says why when there is no Breeding sub-tab; "tab" (the engine's
/// dashboard) only switches tabs, to the Pets roster when there is none.
/// </summary>
private void OpenBreeding(string cmd)
{
bool offered = Pets.BreedingOffered;
if (offered) Pets.SelectBreeding();
if (cmd == "tab")
{
MiniRemoteTabCommand?.Invoke(MiniRemoteTabs.Pets, "select");
return;
}
if (!offered)
{
_ctx.Chat("[Mini Remote] " + (!_ctx.Ilt.Loaded ? IltClient.NotLoaded
: !_ctx.Ilt.IsIltWorld ? "Pet breeding is an Infinite Leaftide feature; this world isn't Infinite Leaftide."
: "This server reports pet breeding off."));
return;
}
OpenTab(MiniRemoteTabs.Pets, "show");
_ctx.Chat("[Mini Remote] Gear, games, the Guardian, bounties, /ra hub attr ...: Infinite Leaftide, the RynthILT plugin.");
_ctx.Chat("[Mini Remote] Character and charms: RynthOracle (/ro character). Banking: Global Inventory (/ginv bank). Force a server: /rc diagnostics.");
}
private static bool IsRemoteTabName(string text)

View file

@ -21,7 +21,7 @@ public sealed class MiniRemoteState
public int SchemaVersion = 1;
public PetTabState Pet = new();
public QuestsTabState Quests = new();
/// <summary>The Crafting tab (tinker benches); the ILT Hub's Crafting before.</summary>
/// <summary>The Crafting tab (tinker benches, Rings chain); the ILT Hub's Crafting before.</summary>
public CraftingTabState Crafting = new();
/// <summary>Last VTank .usd file the importer read (the ILT Hub's Gear.LastUsdPath before).</summary>
public string LastUsdPath = string.Empty;
@ -44,17 +44,18 @@ public sealed class CraftingTabState
public bool AutoNextBatch;
/// <summary>...and start it without asking again.</summary>
public bool AutoStartNextBatch;
/// <summary>Prepared salvage tier: 0 Minor, 1 Moderate, 2 Major (TinkerCatalog.TrinketTiers).</summary>
/// <summary>Trinket salvage tier: 0 Minor, 1 Moderate, 2 Major (TinkerCatalog.TrinketTiers).</summary>
public int TrinketTier;
/// <summary>Prepare a raw bag on the tier's Ammunition when no prepared bag is carried.</summary>
/// <summary>Prepare a raw trinket bag on the tier's Ammunition when no prepared bag is carried.</summary>
public bool TrinketPrep;
// "RingRuns" (the Rings chain, now left to RynthILT) may still be in older files: it is ignored.
/// <summary>Rings chain: recipe id (RingChain) to how many times to craft it.</summary>
public Dictionary<string, int> RingRuns = new();
}
/// <summary>One tinker bench's choices.</summary>
public sealed class TinkerBenchSettings
{
/// <summary>Row key (TinkerCatalog.Key: r/p/c + material id) to how many times (imbues and flags: 0 or 1).</summary>
/// <summary>Row key (TinkerCatalog.Key: r/s/c + material id) to how many times (imbues and flags: 0 or 1).</summary>
public Dictionary<string, int> Counts = new();
/// <summary>Skip a step whose chance is under this percent (0 = any chance).</summary>
public int MinChancePercent;
@ -123,7 +124,7 @@ public sealed class PetTabState
// Auto siphon-lens capture (ACECustom MonsterCapture; Mini Remote > Pets).
/// <summary>When on, use the selected siphon lens on a nearby creature once it is weak enough.</summary>
public bool AutoCaptureEnabled;
/// <summary>Index into <see cref="PetCaptureRules.Lenses"/> (Flawed to Asheron).</summary>
/// <summary>Index into <see cref="PetCaptureRules.Lenses"/> (Flawed…Asheron's).</summary>
public int CaptureLensIndex;
}
@ -264,6 +265,7 @@ internal sealed class MiniRemoteStore
s.Crafting ??= new CraftingTabState();
s.Crafting.Benches ??= new();
s.Crafting.CustomByWorld ??= new();
s.Crafting.RingRuns ??= new();
s.Crafting.BatchSize = Math.Clamp(s.Crafting.BatchSize, 1, 200);
s.Crafting.TrinketTier = Math.Clamp(s.Crafting.TrinketTier, 0, 2);
s.LastUsdPath ??= string.Empty;

View file

@ -0,0 +1,124 @@
// PetDamageTint.cs — damage-type colours and pet essence school picking, after UB-ILT.
//
// Palette: UB-ILT Lib\LeaftideDamageTypeVtColors.ForDamageTypeFlag (the Virindi Tank / Leaftide
// label colours its Items, Spell and Pets tabs share). The engine's Items panel uses the same
// values (RynthCore ImGui\Panels\DamageTypeColors.cs); keep the two tables in step.
// School picking: UB-ILT Lib\PetDamageTypeTintPolicy.PickFlag (v2.0.1119).
using System;
using System.Numerics;
namespace RynthCore.Plugin.RynthAi.MiniRemote;
/// <summary>ACE damage-type flags, colours per school, and the pet essence school pick.</summary>
internal static class PetDamageTint
{
public const uint Slash = 1, Pierce = 2, Bludgeon = 4, SlashPierce = 3, Cold = 8, Fire = 16,
Acid = 32, Lightning = 64, Nether = 1024;
/// <summary>Text colour when the school is unknown (white, as UB for an essence in the pack).</summary>
public static readonly Vector4 Unknown = new(0.95f, 0.95f, 0.95f, 1f);
// Combined masks are read in this order (UB DamageProbeOrder): elements before physical.
private static readonly uint[] ProbeOrder = { Nether, Lightning, Acid, Fire, Cold, Bludgeon, SlashPierce, Pierce, Slash };
/// <summary>Colour for a school name as RynthAi writes it (Slash, Pierce, Bludgeon, Fire, Cold, Lightning, Acid, Nether).</summary>
public static Vector4 ForName(string? school) => school switch
{
"Slash" or "Slashing" => Rgb(255, 180, 120),
"Pierce" or "Piercing" => Rgb(240, 200, 140),
"Bludgeon" or "Bludgeoning" => Rgb(220, 190, 140),
"Slash/Pierce" => Rgb(255, 160, 100),
"Cold" or "Frost" => Rgb(160, 210, 255),
"Fire" => Rgb(255, 130, 70),
"Acid" => Rgb(160, 255, 140),
"Lightning" or "Electric" or "Storm" => Rgb(255, 240, 120),
"Nether" => Rgb(200, 160, 255),
_ => Unknown,
};
/// <summary>School name for one flag (empty for 0 or an undefined value).</summary>
public static string Name(uint flag) => flag switch
{
Slash => "Slash",
Pierce => "Pierce",
Bludgeon => "Bludgeon",
SlashPierce => "Slash/Pierce",
Cold => "Cold",
Fire => "Fire",
Acid => "Acid",
Lightning => "Lightning",
Nether => "Nether",
_ => string.Empty,
};
/// <summary>
/// One school for a pet essence: the captured source's damage (ACE 9054), else the essence's
/// DamageType mask (45), else the name ("Fire Banshee Essence", "Incendiary Knight"). 0 = unknown.
/// ILT reuses 9054 as the min-summon-aug id on some builds, where 1/2/4 read as Slash/Pierce/
/// Bludgeon; an elemental name wins over such a physical-only property read.
/// </summary>
public static uint PickPetFlag(int capturedSourceDamageType, int damageTypeMask, string? displayName)
{
uint fromProps = PickFromProperties(capturedSourceDamageType, damageTypeMask);
uint fromName = InferFromName(displayName);
if (fromName != 0 && IsPhysicalOnly(fromProps)) return fromName;
return fromProps != 0 ? fromProps : fromName;
}
/// <summary>School from Mag-Tools essence names and ILT catalog adjectives (whole words only).</summary>
public static uint InferFromName(string? displayName)
{
if (string.IsNullOrWhiteSpace(displayName)) return 0;
string n = displayName.ToLowerInvariant();
if (HasAny(n, "nether")) return Nether;
if (HasAny(n, "lightning", "electric", "voltaic", "galvanic", "electrified", "shocked", "excited", "volt", "shock"))
return Lightning;
if (HasAny(n, "acid", "caustic", "corrosion", "blistered", "blistering", "corrosive")) return Acid;
if (HasAny(n, "fire", "flaming", "incendiary", "charred", "volcanic", "scorched", "pyre", "magma", "ember"))
return Fire;
if (HasAny(n, "frost", "glacial", "frozen", "frigid", "freezing", "arctic", "blizzard", "ice", "chill"))
return Cold;
if (HasAny(n, "bludgeon", "bludgeoning")) return Bludgeon;
if (HasAny(n, "slash", "slashing")) return Slash;
if (HasAny(n, "pierce", "piercing")) return Pierce;
return 0;
}
private static uint PickFromProperties(int captured, int mask)
{
if (IsDefined(captured)) return (uint)captured;
if (IsDefined(mask)) return (uint)mask;
if (mask <= 0) return 0;
uint m = unchecked((uint)mask);
foreach (uint v in ProbeOrder)
if ((m & v) == v) return v;
return 0;
}
private static bool IsDefined(int raw) => raw > 0 && Name(unchecked((uint)raw)).Length > 0;
private static bool IsPhysicalOnly(uint flag) => flag is Slash or Pierce or Bludgeon or SlashPierce;
private static bool HasAny(string haystack, params string[] tokens)
{
foreach (string t in tokens)
if (HasToken(haystack, t)) return true;
return false;
}
/// <summary>True when <paramref name="token"/> appears as a whole word ("ice" not in "Novice").</summary>
private static bool HasToken(string haystack, string token)
{
int i = 0;
while ((i = haystack.IndexOf(token, i, StringComparison.Ordinal)) >= 0)
{
int end = i + token.Length;
if ((i == 0 || !char.IsLetter(haystack[i - 1])) && (end >= haystack.Length || !char.IsLetter(haystack[end])))
return true;
i++;
}
return false;
}
private static Vector4 Rgb(int r, int g, int b) => new(r / 255f, g / 255f, b / 255f, 1f);
}

View file

@ -152,9 +152,9 @@ internal static class PetStatsReader
_ => string.Empty,
};
int dmg = inv.Int(wo, IntCapturedDamageType);
if (dmg <= 0) dmg = inv.Int(wo, IntDamageType);
s.DamageType = DamageTypeName(dmg);
// Most essences carry neither property; the name then gives the school (UB-ILT v2.0.1119).
s.DamageType = PetDamageTint.Name(PetDamageTint.PickPetFlag(
inv.Int(wo, IntCapturedDamageType), inv.Int(wo, IntDamageType), wo.Name));
// Gear ratings first (what Mag ItemInfo shows), else the base rating ids.
s.D = inv.Int(wo, IntGearDamage);
@ -290,20 +290,6 @@ internal static class PetStatsReader
return sb.Length > 0 ? "[" + sb + "]" : string.Empty;
}
/// <summary>Single AC DamageType flag → name (combined flags return empty).</summary>
private static string DamageTypeName(int flags) => flags switch
{
1 => "Slash",
2 => "Pierce",
4 => "Bludgeon",
8 => "Cold",
16 => "Fire",
32 => "Acid",
64 => "Lightning",
1024 => "Nether",
_ => string.Empty,
};
private static bool TryBool(RynthCoreHost host, uint id, uint stype, out bool v)
{
v = false;

View file

@ -24,7 +24,7 @@
// * Healing pet (UB HealingBuddy subset): summons a heal pet when HP drops, dismisses it
// after the heal lands, holds PetManager's combat summons while it is out.
// * Auto siphon capture (ACECustom MonsterCapture): when enabled, uses the chosen lens on the
// nearest attackable creature within 5 m once it is <=20% health or under 20 HP (Asheron's
// nearest attackable creature within 5 m once it is ≤20% health or under 20 HP (Asheron's
// Lens skips the health gate). Resonance still needs a prior failed capture on the server.
// * /pets and /shinies logs: RynthILT's (RynthILT.Hub section "pets-logs", ILT only).
// * Breeding sub-tab (Infinite Leaftide only): the tab becomes Roster | Breeding when RynthILT
@ -475,8 +475,6 @@ internal sealed class PetsTab
if (essence != null) _ctx.Inventory.Use(essence);
}
// ── Active pet ──────────────────────────────────────────────────────────
// ── Auto siphon capture (ACECustom MonsterCapture) ───────────────────────
/// <summary>
@ -611,6 +609,8 @@ internal sealed class PetsTab
return true;
}
// ── Active pet ──────────────────────────────────────────────────────────
/// <summary>The live "&lt;Me&gt;'s …" creature (server pet naming), or null.</summary>
private WorldObject? FindOwnPet()
{
@ -899,19 +899,23 @@ internal sealed class PetsTab
/// <summary>Shows the Breeding sub-tab on the next frame (any thread).</summary>
public void SelectBreeding() => _selectBreeding = true;
/// <summary>
/// RynthILT offers the Breeding sub-tab: it calls this world Infinite Leaftide and the server
/// hasn't reported pet breeding off. False without RynthILT. Any thread.
/// </summary>
public bool BreedingOffered => _ctx.Ilt.IsIltWorld && !_ctx.Ilt.IsOff(RynthIltHub.FeaturePetBreeding);
/// <summary>Whether auto siphon-lens capture is on (Mini Remote Capture toggle; settings on the roster).</summary>
/// <summary>Whether auto siphon-lens capture is on (Mini Remote Options / Pets roster).</summary>
public bool AutoCaptureEnabled
{
get => S.AutoCaptureEnabled;
set => S.AutoCaptureEnabled = value;
}
/// <summary>Selected siphon lens index (<see cref="PetCaptureRules.LensNames"/>).</summary>
public int CaptureLensIndex
{
get => S.CaptureLensIndex;
set => S.CaptureLensIndex = value;
}
/// <summary>Live auto-capture status line for the Mini Remote capture row.</summary>
public string CaptureStatus => _captureStatus;
/// <summary>
/// Mini Remote Pet toggle on: enable combat auto-summon and summon the Pets tab's active
/// combat essence now (first ticked priority, or the highlighted row). Pump thread.
@ -932,19 +936,14 @@ internal sealed class PetsTab
}
/// <summary>
/// The Pets tab: the universal roster, and on Infinite Leaftide the Roster | Breeding sub-tabs
/// (Breeding is drawn by RynthILT).
/// The Pets tab: the universal Roster, and Breeding (RynthILT's breeding tracker, section
/// "pets-breeding", the same tracker as RynthOracle's Pet Breeding tab).
/// </summary>
public void Render()
{
var settings = _ctx.Settings;
if (settings == null) { ImGui.TextDisabled("Not logged in."); return; }
if (!BreedingOffered)
{
RenderRoster(settings);
return;
}
if (!ImGui.BeginTabBar("##petsub")) return;
if (ImGui.BeginTabItem("Roster##petroster"))
{
@ -955,9 +954,7 @@ internal sealed class PetsTab
_selectBreeding = false;
if (BeginTab(BreedingTabLabel, breedFlags))
{
// RynthILT's tracker; an older RynthILT (before 0.3.1) has no such section and draws nothing.
if (!_ctx.Ilt.RenderSection(RynthIltHub.SectionPetBreeding))
ImGui.TextDisabled("This RynthILT has no pet breeding tracker; update RynthILT to 0.3.1 or later.");
RenderBreeding();
ImGui.EndTabItem();
}
ImGui.EndTabBar();
@ -965,16 +962,33 @@ internal sealed class PetsTab
private static readonly byte[] BreedingTabLabel = System.Text.Encoding.UTF8.GetBytes("Breeding##petbreeding\0");
/// <summary>
/// BeginTabItem with flags but no close button (ImGui.NET pairs the flags overload with p_open,
/// which draws an X on the tab).
/// </summary>
/// <summary>BeginTabItem with flags but no close button (ImGui.NET pairs the flags overload with p_open, which draws an X).</summary>
private static unsafe bool BeginTab(byte[] labelUtf8Z, ImGuiTabItemFlags flags)
{
fixed (byte* label = labelUtf8Z)
return ImGuiNative.igBeginTabItem(label, null, flags) != 0;
}
/// <summary>
/// Breeding is Infinite Leaftide's and RynthILT's: drawn by RynthILT, with a pointer when it
/// isn't loaded or this isn't an ILT world.
/// </summary>
private void RenderBreeding()
{
if (!_ctx.Ilt.Loaded)
{
ImGui.TextDisabled("Pet breeding is tracked by RynthILT (the Infinite Leaftide plugin), which isn't loaded.");
return;
}
if (!_ctx.Ilt.IsIltWorld)
{
ImGui.TextDisabled("Pet breeding is an Infinite Leaftide feature; this world isn't Infinite Leaftide.");
return;
}
if (!_ctx.Ilt.RenderSection(RynthIltHub.SectionPetBreeding))
ImGui.TextDisabled("This RynthILT has no breeding tracker yet; update RynthILT to 0.2.7 or later.");
}
/// <summary>The universal roster: types, summons, ILT charms, healing pets and RynthILT's /pets logs.</summary>
private void RenderRoster(LegacyUiSettings settings)
{
@ -1050,7 +1064,7 @@ internal sealed class PetsTab
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Dismiss the pet that is out.");
ImGui.SameLine();
if (ImGui.Button("Scan pack")) _ctx.Post(ScanPack);
if (ImGui.IsItemHovered()) ImGui.SetTooltip("Appraise every pet to refresh bond, potency and breeding, and check pet-named items\n(an \"... Essence\" name alone isn't enough — the item must be a summoning pet device).");
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip("Appraise every pet to refresh bond, potency and breeding, and check pet-named items\n(an \"... Essence\" name alone isn't enough — the item must be a summoning pet device).");
ImGui.SameLine();
if (ImGui.Button("Add sel.")) _ctx.Post(() => AddSelectedAs(summonKind));
if (ImGui.IsItemHovered()) SafeImGui.SetTooltip($"Make the item selected in your pack a {KindNames[(int)kind].ToLowerInvariant()} pet.");
@ -1148,7 +1162,7 @@ internal sealed class PetsTab
_highlightId = _highlightId == r.Id ? 0 : r.Id;
RenderRowContextMenu(r);
ImGui.SetCursorPos(start);
SafeImGui.TextColored(DamageColor(r.DamageType), r.Line1);
SafeImGui.TextColored(PetDamageTint.ForName(r.DamageType), r.Line1);
SafeImGui.TextColored(LegacyDashboardRenderer.ColAmber, " " + r.Line2);
if (r.UsesMax > 0 && r.UsesCur == 0) SafeImGui.TextColored(LegacyDashboardRenderer.ColHp, " " + r.Line3);
else SafeImGui.TextDisabled(" " + r.Line3);
@ -1183,17 +1197,6 @@ internal sealed class PetsTab
ImGui.EndPopup();
}
/// <summary>Line-1 colour by the pet's damage type (white when unknown / not appraised).</summary>
private static Vector4 DamageColor(string damageType) => damageType switch
{
"Fire" => new Vector4(1.00f, 0.55f, 0.30f, 1f),
"Cold" => new Vector4(0.55f, 0.80f, 1.00f, 1f),
"Acid" => new Vector4(0.55f, 0.95f, 0.45f, 1f),
"Lightning" => new Vector4(0.85f, 0.70f, 1.00f, 1f),
"Nether" => new Vector4(0.75f, 0.50f, 0.90f, 1f),
_ => new Vector4(0.95f, 0.95f, 0.95f, 1f),
};
private void RenderCharms()
{
ImGui.TextColored(LegacyDashboardRenderer.ColTeal, "Pet charms");

View file

@ -140,7 +140,10 @@ public static unsafe class PluginExports
{
if (surface == null) return 0;
ReadOnlySpan<byte> name = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(surface);
if (name.EndsWith(":popout"u8)) name = name[..^":popout"u8.Length];
// Engine tags popped-out embeds with ":popout" so the Mini Remote can show Dock
// and open expanded Options in the floating window.
bool popped = name.EndsWith(":popout"u8);
if (popped) name = name[..^":popout"u8.Length];
var plugin = Runtime.Plugin;
if (plugin == null) return 0;
System.Numerics.Vector2 want;
@ -161,7 +164,7 @@ public static unsafe class PluginExports
bool remote = name.SequenceEqual("miniremote-remote"u8);
bool window = remote || name.SequenceEqual("miniremote-window"u8);
if (!window && !name.SequenceEqual("miniremote"u8)) return 0;
if (!plugin.RenderEmbeddedMiniRemote(window, out want, tabs: !remote)) return 0;
if (!plugin.RenderEmbeddedMiniRemote(window, out want, tabs: !remote, popped: popped)) return 0;
}
if (wantWidth != null) *wantWidth = want.X;
if (wantHeight != null) *wantHeight = want.Y;

View file

@ -243,6 +243,7 @@ public static class VirindiTankProfileImporter
dst.OffhandId = src.OffhandId;
dst.PreferredAmmoItemId = src.PreferredAmmoItemId;
dst.PetDamage = src.PetDamage;
dst.AttackPower = src.AttackPower;
}
private static MonsterRule CloneMonsterRule(MonsterRule row) =>
@ -268,6 +269,7 @@ public static class VirindiTankProfileImporter
OffhandId = row.OffhandId,
PreferredAmmoItemId = row.PreferredAmmoItemId,
PetDamage = row.PetDamage,
AttackPower = row.AttackPower,
PreferredDamage = row.PreferredDamage,
};

View file

@ -1553,8 +1553,9 @@ public sealed partial class RynthAiPlugin
}
/// <summary>
/// What a loot rule can be built from: the item's name, class, stack, key properties and
/// T11 reading, from the object cache. <paramref name="like"/> adds its spells;
/// What a loot rule can be built from: the item's name, class, stack, every property the
/// attribute checklist offers (LootItemAttributes) and T11 reading, from the object cache.
/// <paramref name="like"/> adds its spells (the popup always asks: its checklist lists them);
/// <paramref name="t11"/> asks for an ID when a T11 item's text hasn't arrived.
/// </summary>
private RynthCore.Loot.Editing.LootItemFacts? BuildLootItemFacts(uint itemId, bool like, bool t11)
@ -1568,6 +1569,8 @@ public sealed partial class RynthAiPlugin
ObjectClass = (int)wo.ObjectClass,
StackSize = Math.Max(1, wo.Values(LongValueKey.StackCount, 1)),
MaxStackSize = Math.Max(1, wo.Values(LongValueKey.MaxStackSize, 1)),
// The Pets tab's test (WCID block, summoning-gem icon, Summoning use requirement): the essence group.
IsPetEssence = _miniRemote?.Pets.IsPetDevice(wo) == true,
};
foreach (int key in RynthCore.Loot.Editing.LootItemRules.IntKeys)
{

View file

@ -329,14 +329,16 @@ public sealed partial class RynthAiPlugin
return current != IntPtr.Zero ? current : Host.ImGuiContext;
}
/// <summary>
/// <summary>
/// RynthPluginRenderEmbed "miniremote" / "miniremote-window": the Mini Remote inside the
/// engine's RynthAi dashboard drawer, or (<paramref name="window"/>) inside the engine's Mini
/// Remote window, docked or popped out, drawn into the engine's current ImGui window (and
/// context, see <see cref="EmbedContext"/>). False (nothing drawn) until login and the HUDs
/// context, see <see cref="EmbedContext"/>). <paramref name="popped"/> is true when the
/// engine tagged the surface with ":popout". False (nothing drawn) until login and the HUDs
/// exist. Render thread.
/// </summary>
public bool RenderEmbeddedMiniRemote(bool window, out System.Numerics.Vector2 want, bool tabs = true)
public bool RenderEmbeddedMiniRemote(bool window, out System.Numerics.Vector2 want, bool tabs = true, bool popped = false)
{
want = default;
var huds = _huds;
@ -347,7 +349,7 @@ public sealed partial class RynthAiPlugin
ImGui.SetCurrentContext(EmbedContext());
try
{
want = huds.RenderEmbedded(window, tabs);
want = huds.RenderEmbedded(window, tabs, popped);
return true;
}
catch (Exception ex)

View file

@ -96,6 +96,8 @@ public sealed partial class RynthAiPlugin
{
Log("[RynthAi] Died — holding all actions until respawned and out of portal space.");
_combatManager?.ReleaseHeldTurn();
// A Handler-ring run-away holds autorun: never carry it through the death portal.
_combatManager?.StopRingEscape("died");
_navigationEngine?.Stop();
RynthCore.Plugin.Shared.ActionPacer.Forget("death"); // the server dropped whatever was open
_buffManager?.CancelPendingRecall("death"); // no /lifestone or macro restart after the respawn

View file

@ -731,7 +731,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_metaManager = new MetaManager(_dashboard.Settings, Host, _vitals);
_metaManager.SetPlayerId(_playerId);
_metaManager.SetMtCommandHandler(HandleMtCommand);
_metaManager.SetMtCommandHandler(HandleMetaChatCommand);
_metaManager.SetRaCommandHandler(HandleRaCommand);
if (_objectCache != null) _metaManager.SetObjectCache(_objectCache);
_metaManager.SetFellowshipTracker(_fellowshipTracker);
@ -739,6 +739,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (_buffManager != null) _metaManager.SetBuffManager(_buffManager);
_metaManager.SetCreatureStore(_creatureStore);
_metaManager.SetKillClock(_killClock);
_metaManager.SetCorpseOpenedCheck(id => _completedCorpses.ContainsKey(id));
if (_dashboard != null)
_dashboard.MetaSnapshotProvider = () => _metaManager?.GetStateSnapshot();
@ -1023,6 +1024,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
["MeleeAttackPower"] = (-1, 100), ["MissileAttackPower"] = (-1, 100),
["MeleeAttackHeight"] = (0, 2), ["MissileAttackHeight"] = (0, 2),
["VariablePowerMin"] = (0, 100), ["VariablePowerMax"] = (0, 100),
["MissileEnvironmentResponse"] = (0, 3), ["MagicEnvironmentResponse"] = (0, 3),
["EnvironmentImpactLimit"] = (1, 10), ["EnvironmentImpactWindowSec"] = (5, 120),
["EnvironmentApproachMeters"] = (1, 30), ["EnvironmentMinDistance"] = (1, 30), ["EnvironmentSkipSec"] = (5, 300),
["WeaponSwapSettleMs"] = (0, 3000), ["WeaponSwapMinHealthPct"] = (0, 100), ["WeaponSwapMinGainPct"] = (0, 200),
["PetMinMonsters"] = (1, 20),
["SpellCastIntervalMs"] = (100, 1500), ["StuckCastBreakMs"] = (0, 60000), ["RecoveryRetryMs"] = (200, 5000), ["AttackSpellIntervalMs"] = (0, 5000), ["MinRingTargets"] = (1, 20), ["MinBlastTargets"] = (1, 20), ["BlastRange"] = (0, 100), ["MinWallTargets"] = (1, 20), ["WallRange"] = (0, 100),
@ -2355,7 +2360,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
{
try { _combatManager?.OnObjectCreated(objectId); } catch { }
_sessionStats?.OnCreateObject(objectId);
try { _objectCache?.OnCreateObject(objectId); }
try
{
_objectCache?.OnCreateObject(objectId);
_combatManager?.OnEnvironmentObjectCreated(objectId); // spell projectiles for the environment-impact throttle
}
catch (Exception ex)
{
Host.Log($"[RynthAi] OnCreateObject EXCEPTION on id=0x{objectId:X8}: {ex.GetType().Name}: {ex.Message}");
@ -3623,6 +3632,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
break;
case "settings": HandleSettingsCommand(parts); break;
// /ra equipfor <monster>: VTank's /vt equipitemsfor (MagToolsCommands.Extra.cs)
case "equipfor": HandleEquipForCommand(parts); break;
case "autotrade": HandleAutoTradeRaCommand(parts); break;
case "trade": HandleTradeCommand(parts); break;
case "busyinfo": HandleBusyInfoCommand(); break;

View file

@ -41,8 +41,8 @@ public sealed partial class RynthAiPlugin
{
ServerProfileView? p = ServerProfileView.Parse(_serverState.ProfileJson);
ChatLine(p != null
? $"[RynthAi] {_serverState.ProfilePlugin} {RynthServerProfileApiV1.InterfaceName}: {p.Summary()}"
: $"[RynthAi] {st.ActivePlugin} sent no server settings ({RynthServerProfileApiV1.InterfaceName} not answered - an older plugin?).");
? $"[RynthAi] {_serverState.ProfilePlugin} {_serverState.ProfileInterface}: {p.Summary()}"
: $"[RynthAi] {st.ActivePlugin} sent no server settings ({ServerStateClient.InterfaceFor(st.ActivePlugin)} not answered - an older plugin?).");
}
bool iltTabs = _ilt != null && _ilt.Loaded;

View file

@ -44,7 +44,7 @@ public sealed partial class RynthAiPlugin
private static unsafe class PluginModule
{
/// <summary>RynthPluginVersion's hand-written string (it never changes between builds).</summary>
// Previous release: 0.5.0-legacy-ui (upstream standing).
// Upstream sk keeps the standing 0.5.0-legacy-ui (rynth's publish policy); local builds carry 0.5.88-legacy-ui.
public const string HandWrittenVersion = "0.5.0-legacy-ui";
private const uint FromAddress = 0x4, UnchangedRefCount = 0x2;

View file

@ -86,6 +86,14 @@ public sealed partial class RynthAiPlugin
string cmd = parts[1].ToLower();
// ub-Rythai's verbs: that plugin answers; handled here only in the sense of "not unknown".
if (IsUbRythaiCommand(cmd, SplitUbLine(fullCommand).Args))
return true;
// "/ub vtsetmetastate[State]" and the like: an expression, not a verb.
if (TryHandleUbExpression(fullCommand))
return true;
// /ub jump[swzxc] [heading] [holdtime] — see Jumper.cs
if (cmd.StartsWith("jump", StringComparison.Ordinal))
{
@ -176,6 +184,11 @@ public sealed partial class RynthAiPlugin
if (TryHandleUbExtra(cmd, fullCommand))
return true;
// The rest of ub-IT's verbs: aliases, features, and accepted no-ops (UtilityBeltCompatCommands.cs).
// Before the /mt translation, so "/ub fellow dismiss" doesn't land on /mt fellow's usage line.
if (TryHandleUbCompat(cmd, fullCommand))
return true;
// /ub closestportal: use the nearest portal (UtilityBelt's command).
if (cmd == "closestportal")
{

View file

@ -0,0 +1,355 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// The rest of ub-IT's /ub verbs (2026-10-18 meta-compatibility pass). Three kinds:
/// 1. Aliases and features with a RynthAi, RynthNav, RynthSort, engine or server equivalent
/// (wear, getxy, stfl/stfr, arrow, navgoto, frame limits, fellow dismiss/leader/status,
/// qblist, augs, window save, packsort*, miniremote, meta/combat/sloot on|off, debug, lps).
/// 2. ub-Rythai's verbs, which RynthAi leaves to that plugin without a reply.
/// 3. ub-IT features that mean nothing here (videopatch, chat max, playeroption, ...): accepted
/// without error, said once per session, so a meta that sends them keeps running.
/// </summary>
public sealed partial class RynthAiPlugin
{
/// <summary>Verbs the ub-Rythai plugin answers. Every plugin sees each /ub line, so RynthAi stays quiet for these.</summary>
private static readonly HashSet<string> UbRythaiVerbs = new(StringComparer.OrdinalIgnoreCase)
{
"autopercent", "autotradeaccept", "bank", "build", "guard", "guardian", "ilt", "leaftide",
"log", "loginq", "p2", "periodic", "xpmeter",
};
/// <summary>
/// ub-IT verbs with no RynthAi equivalent: diagnostics of ub-IT's own tools, Decal UI and
/// client patches, and features RynthCore does its own way. Accepted so metas keep running.
/// </summary>
private static readonly HashSet<string> UbNoEquivalentVerbs = new(StringComparer.OrdinalIgnoreCase)
{
"acobject", "autologin", "autoloot", "autosalvage", "autosalvagedebug", "autosalvagereload",
"bankparse", "breakallegiance", "bridge", "calcdamage", "chat", "chatfilter", "chunkaeth",
"chunkaetheria", "chunkdebug", "chunkreset", "chunkstatus", "clapstatus", "dispel", "dispeltool",
"egg", "element", "enlighten", "enlightenment", "getjob", "getui", "invcache", "joke", "keystore",
"login", "lsdclearcache", "lsdlb", "mtbridge", "nav", "navfollow", "navfollowarrival",
"onetouchheal", "pcap", "perf", "playeroption", "prepclick", "printcolors", "professor",
"questbonus", "queuestatus", "refreshqueues", "resolution", "revalidate", "setui", "shittalk",
"soak", "spell", "statushud", "storm", "surgingstrength", "swearallegiance", "testassessor",
"textures", "tinkcalc", "trace", "tracearmorbuffs", "ubhudrecover", "ucm", "unstack",
"vhudbridgestatus", "videopatch", "xp", "xpdebug",
};
// No-equivalent verbs already reported this session (one chat line each, not one per meta pulse).
private readonly HashSet<string> _ubNoEquivalentSaid = new(StringComparer.OrdinalIgnoreCase);
/// <summary>True when ub-Rythai owns this /ub verb. "/ub portal use|list" (portal gems) is
/// ub-Rythai's; "/ub portal &lt;name&gt;" (the nearest portal) is RynthAi's.</summary>
internal static bool IsUbRythaiCommand(string cmd, string args)
{
if (UbRythaiVerbs.Contains(cmd)) return true;
if (!cmd.Equals("portal", StringComparison.OrdinalIgnoreCase)) return false;
string first = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0] : "";
return first.Length == 0 || first.Equals("use", StringComparison.OrdinalIgnoreCase)
|| first.Equals("list", StringComparison.OrdinalIgnoreCase);
}
/// <summary>The verb and its arguments from a "/ub verb args" line.</summary>
private static (string Cmd, string Args) SplitUbLine(string fullCommand)
{
string rest = fullCommand.Length > 3 ? fullCommand.Substring(3).Trim() : "";
int sp = rest.IndexOf(' ');
return sp > 0 ? (rest.Substring(0, sp).ToLowerInvariant(), rest.Substring(sp + 1).Trim())
: (rest.ToLowerInvariant(), "");
}
/// <summary>
/// A meta's chat-command line. /ub lines go to the /ub dispatcher (ub-IT meaning: "/ub give" gives
/// every match, where "/mt give" gives one). ub-Rythai's verbs return false, so the meta hands the
/// line to the chat parser, which every plugin's chat handler sees. Anything else is /mt.
/// </summary>
internal bool HandleMetaChatCommand(string cmd)
{
if (cmd.StartsWith("/ub ", StringComparison.OrdinalIgnoreCase))
{
var (verb, args) = SplitUbLine(cmd);
return !IsUbRythaiCommand(verb, args) && HandleUbCommand(cmd);
}
return HandleMtCommand(cmd);
}
/// <summary>The verbs above. Returns false for anything else.</summary>
internal bool TryHandleUbCompat(string cmd, string fullCommand)
{
string args = SplitUbLine(fullCommand).Args;
string[] w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string sub = w.Length > 0 ? w[0].ToLowerInvariant() : "";
switch (cmd)
{
// ── Aliases of commands RynthAi already has ─────────────────────────
case "wear": UbWear(args, partial: false); return true;
case "wearp": UbWear(args, partial: true); return true;
case "getxy": return HandleMtCursor();
case "stfl": return HandleMtStrafe(new[] { "/mt", "strafe", "left", args });
case "stfr": return HandleMtStrafe(new[] { "/mt", "strafe", "right", args });
case "debug": HandleRaCommand(("/ra debug " + args).TrimEnd()); return true;
case "close": UbClose(sub); return true;
case "bgframelimit":
case "globalframelimit":
UbFrameLimit(background: cmd == "bgframelimit", args);
return true;
case "fellow" when sub is "dismiss" or "dismissp" or "leader" or "leaderp" or "status" or "recruitp":
UbFellow(sub, w.Length > 1 ? string.Join(" ", w, 1, w.Length - 1) : "");
return true;
// ── RynthNav: the arrow and travel to coordinates ───────────────────
case "arrow":
if (sub == "point" && args.Length > 6)
SendToPlugin("RynthNav", "rnav", "arrow " + args.Substring(6).Trim(), "/ub arrow needs the RynthNav plugin.");
else
UbNoEquivalent(cmd, "\"arrow face\" has no RynthNav equivalent");
return true;
case "navgoto":
UbNavGoto(w);
return true;
// ── RynthSort: pack sorting ─────────────────────────────────────────
case "packsort":
case "packsortscansort":
case "packsortscanforcesort":
SendToPlugin("RynthSort", "rsort", "now", "/ub packsort needs the RynthSort plugin.");
return true;
case "packsortshow":
case "packsortlist":
SendToPlugin("RynthSort", "rsort", "status", "/ub packsort needs the RynthSort plugin.");
return true;
case "packsortreload":
case "packsortscan":
case "packsortscanforce":
UbNoEquivalent(cmd, "RynthSort reads its rules itself");
return true;
// ── Server commands (ACECustom) ─────────────────────────────────────
case "qblist": InvokeServerCommand("/qb list"); return true;
case "augs": InvokeServerCommand("/aug"); return true;
// ── RynthCore's window placement ────────────────────────────────────
case "window":
if (sub == "save") InvokeServerCommand("/rc window save");
else UbNoEquivalent(cmd + " " + sub, "RynthCore restores the saved window at login (/rc window save|reset)");
return true;
// ── RynthAi's Mini Remote ───────────────────────────────────────────
case "miniremote":
if (sub is "show" or "hide" or "toggle") HandleHudCommand("miniremote", sub);
else UbNoEquivalent(cmd + " " + sub, "use /ub miniremote show|hide|toggle");
return true;
// ── Project Storm's switches onto RynthAi's macro features ──────────
case "meta": return UbStormSwitch(cmd, sub, "enablemeta", w);
case "combat": return UbStormSwitch(cmd, sub, "enablecombat", w);
case "sloot": return UbStormSwitch(cmd, sub, "enablelooting", w);
case "lps":
case "lootprofilestatus":
{
string path = _dashboard?.Settings?.CurrentLootPath ?? "";
ChatLine("[RynthAi] Loot profile: " + (path.Length > 0 ? Path.GetFileName(path) : "(none)"));
return true;
}
}
// ── ub-IT features with no RynthAi equivalent ───────────────────────────
if (UbNoEquivalentVerbs.Contains(cmd))
{
UbNoEquivalent(cmd, null);
return true;
}
return false;
}
/// <summary>
/// /ub close corpse|chest (ub-IT): closes the open container when it is that kind (a bare
/// "/ub close" closes whatever is open). Metas send it after looting a quest corpse.
/// </summary>
private void UbClose(string kind)
{
uint open = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0;
if (open == 0) { ChatLine("[RynthAi] No container is currently open."); return; }
WorldObject? wo = _objectCache?[unchecked((int)open)];
bool fits = kind switch
{
"corpse" => wo == null || wo.ObjectClass == AcObjectClass.Corpse,
"chest" => wo == null || wo.ObjectClass == AcObjectClass.Container,
_ => true,
};
if (!fits) return; // as ub-IT: the open container isn't that kind, nothing to do
bool closed = Host.HasCloseContainer ? Host.CloseContainer(open) : Host.UseFor(open, "Command", "/ub close", UseKind.Asked);
Log($"[RynthAi] /ub close {kind}: 0x{open:X8} {(closed ? "closed" : "close refused")}.");
}
/// <summary>
/// "/ub &lt;expression&gt;": a /ub line whose verb is an expression call (S_BulbOfMornings broadcasts
/// "/ub bc /ub vtsetmetastate[State]" so every client switches state). ub-IT has no such
/// command; RynthAi evaluates the expression, which is what the meta means. True when it was one.
/// </summary>
internal bool TryHandleUbExpression(string fullCommand)
{
string rest = fullCommand.Length > 3 ? fullCommand.Substring(3).Trim() : "";
int bracket = rest.IndexOf('[');
int space = rest.IndexOf(' ');
if (bracket <= 0 || (space >= 0 && space < bracket) || !rest.EndsWith("]", StringComparison.Ordinal)) return false;
string result = EvalExpr(rest);
Log($"[RynthAi] /ub {rest} evaluated as an expression -> '{result}'.");
return true;
}
/// <summary>Says once per session that a /ub verb is accepted and ignored; every use is logged.</summary>
private void UbNoEquivalent(string what, string? note)
{
Log($"[RynthAi] /ub {what}: no RynthAi equivalent; ignored.");
if (_ubNoEquivalentSaid.Add(what))
ChatLine($"[RynthAi] /ub {what} is a ub-IT feature with no RynthAi equivalent; it is accepted and ignored so metas keep running"
+ (note != null ? $" ({note})." : "."));
}
/// <summary>Sends a chat line to the chat parser (server commands, /rc).</summary>
private void InvokeServerCommand(string line)
{
if (Host.HasInvokeChatParser) Host.InvokeChatParser(line);
else ChatLine($"[RynthAi] Can't send {line}: the chat parser isn't available.");
}
/// <summary>A command for another plugin through the engine broker.</summary>
private void SendToPlugin(string plugin, string action, string value, string missing)
{
if (!(Host.HasSendPluginCommand && Host.SendPluginCommand(plugin, action, value)))
ChatLine("[RynthAi] " + missing);
}
/// <summary>/ub wear[p] &lt;name&gt;: wield a carried item by name, skipping copies already worn
/// (using a worn item would take it off).</summary>
private void UbWear(string name, bool partial)
{
if (string.IsNullOrWhiteSpace(name)) { ChatLine("[RynthAi] Usage: /ub wear <item name> (wearp: partial name)"); return; }
if (_objectCache == null || !Host.HasUseObject) { ChatLine("[RynthAi] /ub wear: not ready (log in first)."); return; }
bool sawWorn = false;
foreach (var wo in _objectCache.GetInventory())
{
bool match = partial
? wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: string.Equals(wo.Name, name, StringComparison.OrdinalIgnoreCase);
if (!match) continue;
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) { sawWorn = true; continue; }
Host.UseFor(unchecked((uint)wo.Id), "Command", "/ub wear", UseKind.Asked);
Log($"[RynthAi] /ub wear: {wo.Name} (0x{(uint)wo.Id:X8})");
return;
}
ChatLine(sawWorn ? $"[RynthAi] Already wearing '{name}'." : $"[RynthAi] Item not found: '{name}'");
}
/// <summary>/ub globalframelimit|bgframelimit &lt;fps&gt;: RynthAi's frame limit (Settings, Display).
/// 0 turns the limit off (global) or lifts the background cap to its maximum.</summary>
private void UbFrameLimit(bool background, string arg)
{
LegacyUiSettings? s = _dashboard?.Settings;
if (s == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; }
if (!int.TryParse(arg.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int fps) || fps < 0)
{
ChatLine($"[RynthAi] Usage: /ub {(background ? "bgframelimit" : "globalframelimit")} <frames per second>");
return;
}
if (background)
{
s.TargetFPSBackground = fps == 0 ? 60 : Math.Clamp(fps, 5, 60);
s.EnableFPSLimit = true;
ChatLine($"[RynthAi] Background frame limit: {s.TargetFPSBackground} fps.");
}
else if (fps == 0)
{
s.EnableFPSLimit = false;
ChatLine("[RynthAi] Frame limit off.");
}
else
{
s.TargetFPSFocused = Math.Clamp(fps, 10, 240);
s.EnableFPSLimit = true;
ChatLine($"[RynthAi] Frame limit: {s.TargetFPSFocused} fps.");
}
try { _dashboard?.SaveSettings(); } catch { }
}
/// <summary>/ub fellow dismiss[p]|leader[p] &lt;name&gt;, status, recruitp &lt;name&gt; (the p forms match part of a name).</summary>
private void UbFellow(string sub, string name)
{
if (sub == "status") { HandleFellowshipCommand(new[] { "/ra", "fellow", "status" }); return; }
if (name.Length == 0) { ChatLine($"[RynthAi] Usage: /ub fellow {sub} <name>"); return; }
bool partial = sub.EndsWith('p');
string resolved = name;
if (partial && sub != "recruitp" && _fellowshipTracker != null)
{
foreach (string member in _fellowshipTracker.GetMemberNames())
if (member.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0) { resolved = member; break; }
}
else if (sub == "recruitp" && FindObject(name, inv: false, land: true, partial: true) is { } wo)
{
resolved = wo.Name;
}
string verb = sub.TrimEnd('p');
InvokeServerCommand($"/fellowship {verb} {resolved}");
}
/// <summary>/ub navgoto &lt;ns&gt; &lt;ew&gt; [walk|run]: ub-IT's signed coordinates (south and west
/// negative) to RynthNav's "/rnav go 42.1N, 33.6E". RynthNav picks its own pace.</summary>
private void UbNavGoto(string[] w)
{
if (w.Length < 2
|| !double.TryParse(w[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double ns)
|| !double.TryParse(w[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double ew))
{
ChatLine("[RynthAi] Usage: /ub navgoto <ns> <ew> [walk|run] (south and west are negative)");
return;
}
string coords = FormattableString.Invariant($"{Math.Abs(ns):0.0#}{(ns < 0 ? 'S' : 'N')}, {Math.Abs(ew):0.0#}{(ew < 0 ? 'W' : 'E')}");
SendToPlugin("RynthNav", "rnav", "go " + coords, "/ub navgoto needs the RynthNav plugin.");
}
/// <summary>
/// Project Storm's /ub meta|combat|sloot: on/off switch the matching RynthAi macro feature
/// (enablemeta, enablecombat, enablelooting); "meta load &lt;name&gt;" and "meta state &lt;name&gt;"
/// are VTank's meta load and setmetastate. The other Storm verbs have no equivalent.
/// </summary>
private bool UbStormSwitch(string cmd, string sub, string vtOption, string[] w)
{
string rest = w.Length > 1 ? string.Join(" ", w, 1, w.Length - 1) : "";
if (_metaManager == null) { ChatLine("[RynthAi] Not ready (log in first)."); return true; }
switch (sub)
{
case "on" or "off":
_metaManager.TryHandleVtCommand($"/vt opt set {vtOption} {(sub == "on" ? "true" : "false")}");
return true;
case "status" or "":
_metaManager.TryHandleVtCommand($"/vt opt get {vtOption}");
return true;
case "load" when cmd == "meta" && rest.Length > 0:
_metaManager.TryHandleVtCommand("/vt meta load " + rest);
return true;
case "state" when cmd == "meta" && rest.Length > 0:
_metaManager.TryHandleVtCommand("/vt setmetastate " + rest);
return true;
}
UbNoEquivalent(cmd + " " + sub, "Project Storm's own engine; RynthAi is the macro here");
return true;
}
}