RynthSuite as of 2026-09-27 (internal 1816d05): AutoVendor (UtilityBelt port), missile/magic facing and arc line of sight, nav waypoint skipping, rebuff batch and item-enchant fixes, crafting fallback, Loot Editor AutoVendor folder and command-line open, release 2026.9.27.2
This commit is contained in:
parent
a19ee1904e
commit
d55ffda4ed
33 changed files with 4364 additions and 207 deletions
7
.github/workflows/release.yml
vendored
7
.github/workflows/release.yml
vendored
|
|
@ -85,6 +85,13 @@ jobs:
|
||||||
dotnet run --project "$env:GITHUB_WORKSPACE\Tools\RynthCore.LootSdkTests\RynthCore.LootSdkTests.csproj" -c Release
|
dotnet run --project "$env:GITHUB_WORKSPACE\Tools\RynthCore.LootSdkTests\RynthCore.LootSdkTests.csproj" -c Release
|
||||||
if ($LASTEXITCODE -ne 0) { throw "LootSdk golden tests FAILED" }
|
if ($LASTEXITCODE -ne 0) { throw "LootSdk golden tests FAILED" }
|
||||||
|
|
||||||
|
# AutoVendor pure-logic tests (rule judging, buy-up-to-N, batch planning, splits).
|
||||||
|
- name: Validation gate - AutoVendor tests
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
dotnet run --project "$env:GITHUB_WORKSPACE/Tools/RynthCore.AutoVendorTests/RynthCore.AutoVendorTests.csproj" -c Release
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "AutoVendor tests FAILED" }
|
||||||
|
|
||||||
# ── Build LootEditor ───────────────────────────────────────────────────────
|
# ── Build LootEditor ───────────────────────────────────────────────────────
|
||||||
- name: Build LootEditor
|
- name: Build LootEditor
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
|
|
|
||||||
10
BUILD.md
10
BUILD.md
|
|
@ -52,6 +52,16 @@ dotnet build -c Release
|
||||||
dotnet run -c Release
|
dotnet run -c Release
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd C:\Projects\RynthSuite\Tools\RynthCore.AutoVendorTests
|
||||||
|
dotnet run -c Release # RynthAi AutoVendor rule/planning tests
|
||||||
|
```
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd C:\Projects\RynthSuite\Tools\RynthCore.MissileArcTests
|
||||||
|
dotnet run -c Release # RynthAi missile arc (LoS ballistics) tests
|
||||||
|
```
|
||||||
|
|
||||||
These projects target `net10.0` (no `-windows` suffix) and use Avalonia 11.2.3, so they build and run identically on Windows, Linux, and macOS.
|
These projects target `net10.0` (no `-windows` suffix) and use Avalonia 11.2.3, so they build and run identically on Windows, Linux, and macOS.
|
||||||
|
|
||||||
## Deploy — Plugin
|
## Deploy — Plugin
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,7 @@ public enum DoubleValueKey
|
||||||
DamageVariance = 22,
|
DamageVariance = 22,
|
||||||
CurrentPowerMod = 23,
|
CurrentPowerMod = 23,
|
||||||
AccuracyMod = 24,
|
AccuracyMod = 24,
|
||||||
|
MaximumVelocity = 26, // missile launcher launch speed (m/s); known once appraised
|
||||||
WeaponDefense = 29,
|
WeaponDefense = 29,
|
||||||
UseRadius = 54,
|
UseRadius = 54,
|
||||||
WeaponOffense = 61,
|
WeaponOffense = 61,
|
||||||
|
|
@ -106,17 +107,59 @@ public class WorldObject
|
||||||
// Set by WorldObjectCache when it creates/updates this object
|
// Set by WorldObjectCache when it creates/updates this object
|
||||||
internal WorldObjectCache? Cache { get; set; }
|
internal WorldObjectCache? Cache { get; set; }
|
||||||
|
|
||||||
public int Values(LongValueKey key, int defaultValue)
|
/// <summary>
|
||||||
=> Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
|
/// Values that answer Values() before any live read (AutoVendor: a vendor-list item
|
||||||
|
/// built from the engine's vendor snapshot, or an item's known name). Null = live only.
|
||||||
|
/// </summary>
|
||||||
|
internal ItemPropertyOverlay? Overlay { get; set; }
|
||||||
|
|
||||||
|
public int Values(LongValueKey key, int defaultValue) => Values((int)key, defaultValue);
|
||||||
|
|
||||||
public int Values(int key, int defaultValue)
|
public int Values(int key, int defaultValue)
|
||||||
=> Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
|
{
|
||||||
|
var o = Overlay;
|
||||||
|
if (o != null)
|
||||||
|
{
|
||||||
|
if (o.Ints.TryGetValue(unchecked((uint)key), out int v)) return v;
|
||||||
|
if (!o.LiveFallback) return defaultValue;
|
||||||
|
}
|
||||||
|
return Cache?.GetIntProperty(Id, (uint)key, defaultValue) ?? defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
public string Values(StringValueKey key, string defaultValue)
|
public string Values(StringValueKey key, string defaultValue)
|
||||||
=> Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue;
|
{
|
||||||
|
var o = Overlay;
|
||||||
|
if (o != null)
|
||||||
|
{
|
||||||
|
if (o.Strings.TryGetValue((uint)key, out string? v)) return v;
|
||||||
|
if (!o.LiveFallback) return defaultValue;
|
||||||
|
}
|
||||||
|
return Cache?.GetStringProperty(Id, (uint)key, defaultValue) ?? defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
public double Values(DoubleValueKey key, double defaultValue)
|
public double Values(DoubleValueKey key, double defaultValue)
|
||||||
=> Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue;
|
{
|
||||||
|
var o = Overlay;
|
||||||
|
if (o != null)
|
||||||
|
{
|
||||||
|
if (o.Doubles.TryGetValue((uint)key, out double v)) return v;
|
||||||
|
if (!o.LiveFallback) return defaultValue;
|
||||||
|
}
|
||||||
|
return Cache?.GetDoubleProperty(Id, (uint)key, defaultValue) ?? defaultValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fixed property values for a <see cref="WorldObject"/>. With LiveFallback off, a key
|
||||||
|
/// that isn't here reads as the caller's default instead of the client object's value
|
||||||
|
/// (a vendor-list item carries only what the vendor snapshot holds).
|
||||||
|
/// </summary>
|
||||||
|
internal sealed class ItemPropertyOverlay
|
||||||
|
{
|
||||||
|
public Dictionary<uint, int> Ints { get; } = new();
|
||||||
|
public Dictionary<uint, string> Strings { get; } = new();
|
||||||
|
public Dictionary<uint, double> Doubles { get; } = new();
|
||||||
|
public bool LiveFallback { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── SpellInfo stub ────────────────────────────────────────────────────────
|
// ── SpellInfo stub ────────────────────────────────────────────────────────
|
||||||
|
|
|
||||||
|
|
@ -36,6 +36,10 @@ public class BuffManager : IDisposable
|
||||||
private DateTime _lastBuffStanceAttempt = DateTime.MinValue;
|
private DateTime _lastBuffStanceAttempt = DateTime.MinValue;
|
||||||
private int _buffStanceConsecutiveFails = 0;
|
private int _buffStanceConsecutiveFails = 0;
|
||||||
private bool _isForceRebuffing = false;
|
private bool _isForceRebuffing = false;
|
||||||
|
// Set with _isForceRebuffing when the pass is the automatic batch (one buff fell
|
||||||
|
// under RebuffSecondsRemaining), not the Force Rebuff button. The batch only tops
|
||||||
|
// off buffs under RebuffTopOffSecondsRemaining; Force Rebuff recasts everything.
|
||||||
|
private bool _isAutoBatchRebuff = false;
|
||||||
private int _pendingSpellId = 0;
|
private int _pendingSpellId = 0;
|
||||||
private Action<string>? _onCastResolved;
|
private Action<string>? _onCastResolved;
|
||||||
|
|
||||||
|
|
@ -475,6 +479,7 @@ public class BuffManager : IDisposable
|
||||||
public void ForceFullRebuff()
|
public void ForceFullRebuff()
|
||||||
{
|
{
|
||||||
_isForceRebuffing = true;
|
_isForceRebuffing = true;
|
||||||
|
_isAutoBatchRebuff = false;
|
||||||
_forceRebuffCastFamilies.Clear();
|
_forceRebuffCastFamilies.Clear();
|
||||||
_buffFailCooldownUntil.Clear(); // explicit recast-all must not be blocked by stale cooldowns
|
_buffFailCooldownUntil.Clear(); // explicit recast-all must not be blocked by stale cooldowns
|
||||||
_silentNoShowCounts.Clear(); // give parked families a fresh shot on FR too
|
_silentNoShowCounts.Clear(); // give parked families a fresh shot on FR too
|
||||||
|
|
@ -496,6 +501,7 @@ public class BuffManager : IDisposable
|
||||||
public void CancelBuffing()
|
public void CancelBuffing()
|
||||||
{
|
{
|
||||||
_isForceRebuffing = false;
|
_isForceRebuffing = false;
|
||||||
|
_isAutoBatchRebuff = false;
|
||||||
_isRechargingMana = false;
|
_isRechargingMana = false;
|
||||||
_isRechargingStamina = false;
|
_isRechargingStamina = false;
|
||||||
_isHealingSelf = false;
|
_isHealingSelf = false;
|
||||||
|
|
@ -810,15 +816,17 @@ public class BuffManager : IDisposable
|
||||||
|
|
||||||
if (_isForceRebuffing)
|
if (_isForceRebuffing)
|
||||||
{
|
{
|
||||||
|
bool wasAutoBatch = _isAutoBatchRebuff;
|
||||||
_isForceRebuffing = false;
|
_isForceRebuffing = false;
|
||||||
_host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families");
|
_isAutoBatchRebuff = false;
|
||||||
|
_host.Log($"[FR] complete — cast {_forceRebuffCastFamilies.Count} spell families{(wasAutoBatch ? " (auto batch)" : "")}");
|
||||||
// Order matters: the flag must already be false (IsBuffActive
|
// Order matters: the flag must already be false (IsBuffActive
|
||||||
// short-circuits on _forceRebuffCastFamilies while it is set, so
|
// short-circuits on _forceRebuffCastFamilies while it is set, so
|
||||||
// every family would read "active"), and the set must still be
|
// every family would read "active"), and the set must still be
|
||||||
// populated — it is what the audit iterates.
|
// populated — it is what the audit iterates.
|
||||||
AuditBatchSatisfied();
|
AuditBatchSatisfied();
|
||||||
_forceRebuffCastFamilies.Clear();
|
_forceRebuffCastFamilies.Clear();
|
||||||
_host.WriteToChat("[RynthAi] Force Rebuff Complete.", 1);
|
_host.WriteToChat(wasAutoBatch ? "[RynthAi] Rebuff complete." : "[RynthAi] Force Rebuff Complete.", 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1066,6 +1074,7 @@ public class BuffManager : IDisposable
|
||||||
// no-show → re-park → another auto-batch → loop. Hard-reject
|
// no-show → re-park → another auto-batch → loop. Hard-reject
|
||||||
// cooldowns are short-lived (120s) so they expire on their own.
|
// cooldowns are short-lived (120s) so they expire on their own.
|
||||||
_isForceRebuffing = true;
|
_isForceRebuffing = true;
|
||||||
|
_isAutoBatchRebuff = true;
|
||||||
_forceRebuffCastFamilies.Clear();
|
_forceRebuffCastFamilies.Clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1377,13 +1386,23 @@ public class BuffManager : IDisposable
|
||||||
// Force Rebuff: ignore live timers entirely — only spells we've already
|
// Force Rebuff: ignore live timers entirely — only spells we've already
|
||||||
// cast THIS rebuff cycle count as "active". The whole point of FR is to
|
// cast THIS rebuff cycle count as "active". The whole point of FR is to
|
||||||
// recast every spell so all timers align to the same start time.
|
// recast every spell so all timers align to the same start time.
|
||||||
|
// The automatic batch shares FR's bookkeeping but must NOT recast
|
||||||
|
// everything: one buff under the threshold used to refresh every buff,
|
||||||
|
// even ones with 30+ minutes left (2026-09-27). It tops off only buffs
|
||||||
|
// under RebuffTopOffSecondsRemaining (never less than RebuffSecondsRemaining,
|
||||||
|
// so the buff that started the batch is always in it) and leaves the rest
|
||||||
|
// to their own timers.
|
||||||
if (_isForceRebuffing)
|
if (_isForceRebuffing)
|
||||||
return _forceRebuffCastFamilies.Contains(targetSpell.Family);
|
{
|
||||||
|
if (_forceRebuffCastFamilies.Contains(targetSpell.Family)) return true;
|
||||||
|
if (!_isAutoBatchRebuff) return false;
|
||||||
|
rebufferSecOverride = Math.Max(_settings.RebuffTopOffSecondsRemaining, _settings.RebuffSecondsRemaining);
|
||||||
|
}
|
||||||
|
|
||||||
int targetLevel = GetSpellLevel(targetSpell);
|
int targetLevel = GetSpellLevel(targetSpell);
|
||||||
// Recast when remaining duration drops below this many seconds.
|
// Recast when remaining duration drops below this many seconds.
|
||||||
// User-configurable via Advanced Settings → Buffing; overridden during
|
// User-configurable via Advanced Settings → Buffing; overridden during
|
||||||
// batch-rebuff passes (CheckAndCastSelfBuffs) to 1200s (20 min).
|
// batch-rebuff passes (CheckAndCastSelfBuffs) by RebuffTopOffSecondsRemaining.
|
||||||
int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining);
|
int rebufferSec = Math.Max(0, rebufferSecOverride ?? _settings.RebuffSecondsRemaining);
|
||||||
|
|
||||||
// Tier-upgrade rule (applies to both item enchantments and player buffs):
|
// Tier-upgrade rule (applies to both item enchantments and player buffs):
|
||||||
|
|
@ -1664,9 +1683,15 @@ public class BuffManager : IDisposable
|
||||||
|
|
||||||
// Learn the real ceiling this family lands at (Incantations cap below
|
// Learn the real ceiling this family lands at (Incantations cap below
|
||||||
// their nominal tier) so IsBuffActive stops chasing an unreachable tier.
|
// their nominal tier) so IsBuffActive stops chasing an unreachable tier.
|
||||||
// Recorded for EVERY entry read, including one the merge above
|
// Recorded for every timed entry read, including one the merge above
|
||||||
// discarded — the ceiling is about what this character can land, not
|
// discarded — the ceiling is about what this character can land, not
|
||||||
// about which entry currently wins the family slot.
|
// about which entry currently wins the family slot. NOT for permanent
|
||||||
|
// entries: those are item-granted ("Willpower Other I" on gear), not
|
||||||
|
// something this character cast, and learning their tier as the
|
||||||
|
// ceiling made a permanent level-1 enchant satisfy the family forever
|
||||||
|
// (effective target 1, never expires): after a relog with the real
|
||||||
|
// buff gone, Lucy went 17 minutes without Willpower (2026-09-27).
|
||||||
|
if (!isPermanent)
|
||||||
RecordAchievedTier(spellInfo.Family, level);
|
RecordAchievedTier(spellInfo.Family, level);
|
||||||
|
|
||||||
if (isPermanent && _loggedPermanentFamilies.Add(spellInfo.Family))
|
if (isPermanent && _loggedPermanentFamilies.Add(spellInfo.Family))
|
||||||
|
|
|
||||||
|
|
@ -160,7 +160,7 @@ public class CombatManager : IDisposable
|
||||||
// a perfectly good target in ~3 ticks (~1.2s at SpellCastIntervalMs=400).
|
// a perfectly good target in ~3 ticks (~1.2s at SpellCastIntervalMs=400).
|
||||||
private bool _offensiveCastThisCycle;
|
private bool _offensiveCastThisCycle;
|
||||||
private DateTime _faceStartTime = DateTime.MinValue;
|
private DateTime _faceStartTime = DateTime.MinValue;
|
||||||
private const double FACE_TIMEOUT_MS = 1000.0; // give up waiting and fire anyway (MISSILE only)
|
private const double FACE_TIMEOUT_MS = 1000.0; // give up waiting and swing anyway (non-native MELEE only)
|
||||||
private const double FACE_TOLERANCE_DEG = 15.0; // heading error threshold to fire
|
private const double FACE_TOLERANCE_DEG = 15.0; // heading error threshold to fire
|
||||||
|
|
||||||
// ── Magic targeted-cast settle gate (root-cause fix 2026-06-19) ──────────
|
// ── Magic targeted-cast settle gate (root-cause fix 2026-06-19) ──────────
|
||||||
|
|
@ -168,11 +168,11 @@ public class CombatManager : IDisposable
|
||||||
// turn-to-face; a turn/stop MoveToState that lands during that deferred
|
// turn-to-face; a turn/stop MoveToState that lands during that deferred
|
||||||
// windup ORPHANS the cast (DoSpellWords/CreatePlayerSpell never runs) → the
|
// windup ORPHANS the cast (DoSpellWords/CreatePlayerSpell never runs) → the
|
||||||
// gesture animates but 0 damage / "You're too busy!" forever. Self-buffs are
|
// gesture animates but 0 damage / "You're too busy!" forever. Self-buffs are
|
||||||
// immune (untargeted → synchronous, no turn). Fix: for MAGIC, never cast
|
// immune (untargeted → synchronous, no turn). The 2026-06-19 fix turned the
|
||||||
// mid-turn — keep turning until actually within angle, then release the turn
|
// bot itself until within angle, then released and settled before the cast;
|
||||||
// motions and let the stop reach the server (settle tick) BEFORE the cast.
|
// since 2026-09-27 the bot doesn't turn for magic at all (the server's own
|
||||||
|
// Rotate does it), and this only settles after releasing a turn melee left held.
|
||||||
private DateTime _faceSettledAt = DateTime.MinValue;
|
private DateTime _faceSettledAt = DateTime.MinValue;
|
||||||
private const double FACE_MAX_WAIT_MS = 2500.0; // safety: heading never converges (jittery point-blank pose) → cast anyway rather than wedge
|
|
||||||
private const double FACE_SETTLE_MS = 140.0; // let the turn-stop reach the server (≥ one 30Hz tick) before the cast packet
|
private const double FACE_SETTLE_MS = 140.0; // let the turn-stop reach the server (≥ one 30Hz tick) before the cast packet
|
||||||
|
|
||||||
// ── Magic cast cadence guard ────────────────────────────────────────────
|
// ── Magic cast cadence guard ────────────────────────────────────────────
|
||||||
|
|
@ -665,7 +665,9 @@ public class CombatManager : IDisposable
|
||||||
double maxDist = _settings.MonsterRange;
|
double maxDist = _settings.MonsterRange;
|
||||||
TargetingFSM.AttackType attackType = TargetingFSM.AttackType.Linear;
|
TargetingFSM.AttackType attackType = TargetingFSM.AttackType.Linear;
|
||||||
if (RaycastInitialized && _raycastSystem?.TargetingFSM != null)
|
if (RaycastInitialized && _raycastSystem?.TargetingFSM != null)
|
||||||
attackType = _raycastSystem.GetAttackType(CurrentCombatMode, "");
|
attackType = DetermineAttackTypeForLOS();
|
||||||
|
bool losDebug = _settings.LosDebugLog;
|
||||||
|
if (losDebug) LogLosDebugWeapon();
|
||||||
|
|
||||||
foreach (var wo in _worldFilter.GetLandscape())
|
foreach (var wo in _worldFilter.GetLandscape())
|
||||||
{
|
{
|
||||||
|
|
@ -721,14 +723,12 @@ public class CombatManager : IDisposable
|
||||||
if (dist > (isEngaged ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue;
|
if (dist > (isEngaged ? Math.Max(maxDist, DisengageDistance) : maxDist)) continue;
|
||||||
|
|
||||||
bool losBlocked = false;
|
bool losBlocked = false;
|
||||||
if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem != null)
|
if (_settings.EnableRaycasting && RaycastInitialized && _raycastSystem?.TargetingFSM != null)
|
||||||
{
|
{
|
||||||
RaycastCheckCount++;
|
RaycastCheckCount++;
|
||||||
if (_raycastSystem.IsTargetBlocked(_host, (uint)wo.Id, attackType))
|
losBlocked = _raycastSystem.TargetingFSM.IsTargetBlocked(_host, (uint)wo.Id, attackType, out var losDetail);
|
||||||
{
|
if (losBlocked) RaycastBlockCount++;
|
||||||
RaycastBlockCount++;
|
if (losDebug) LogLosDebug(wo, losBlocked, losDetail);
|
||||||
losBlocked = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Don't blacklist from scan — just exclude from this result.
|
// Don't blacklist from scan — just exclude from this result.
|
||||||
|
|
@ -1337,9 +1337,12 @@ public class CombatManager : IDisposable
|
||||||
private void DropTarget(string reason)
|
private void DropTarget(string reason)
|
||||||
{
|
{
|
||||||
if (activeTargetId != 0)
|
if (activeTargetId != 0)
|
||||||
_host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason}");
|
_host.Log($"[RynthAi] DropTarget 0x{activeTargetId:X8}: {reason} [{DescribeTargetPos(activeTargetId)}]");
|
||||||
activeTargetId = 0;
|
activeTargetId = 0;
|
||||||
_lockedTargetId = 0;
|
_lockedTargetId = 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();
|
||||||
_facingTarget = false;
|
_facingTarget = false;
|
||||||
_returnToPhysicalCombat = false;
|
_returnToPhysicalCombat = false;
|
||||||
_targetLockedAt = DateTime.MinValue;
|
_targetLockedAt = DateTime.MinValue;
|
||||||
|
|
@ -1775,6 +1778,7 @@ public class CombatManager : IDisposable
|
||||||
fsm.CrossbowArcVelocity = _settings.CrossbowArcVelocity;
|
fsm.CrossbowArcVelocity = _settings.CrossbowArcVelocity;
|
||||||
fsm.AtlatlArcVelocity = _settings.AtlatlArcVelocity;
|
fsm.AtlatlArcVelocity = _settings.AtlatlArcVelocity;
|
||||||
fsm.MagicArcVelocity = _settings.MagicArcVelocity;
|
fsm.MagicArcVelocity = _settings.MagicArcVelocity;
|
||||||
|
fsm.MissileArcClearance = _settings.MissileArcClearance;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deferred predicted kill-shot swap: a cast that armed it is confirmed
|
// Deferred predicted kill-shot swap: a cast that armed it is confirmed
|
||||||
|
|
@ -1990,39 +1994,19 @@ public class CombatManager : IDisposable
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// MAGIC: settle-before-cast facing gate. Never cast mid-turn and
|
// MAGIC and MISSILE: the server turns the player to the target itself,
|
||||||
// never let a turn-stop ride alongside the cast packet — both orphan
|
// as retail did — ACE Rotate(target) before a targeted cast (and again
|
||||||
// the ACE server's deferred targeted-cast windup (root cause of
|
// after the windup if needed) and before the first missile shot and
|
||||||
// "animates but 0 damage / too busy"). Makes combat behave like the
|
// between repeat shots. So the bot doesn't turn at all. A client-side
|
||||||
// working self-buff path. Applies regardless of UseNativeAttack
|
// turn servo on top only fought that rotation: missile characters spun
|
||||||
// (native attack is a physical swing; in Magic mode the bot always
|
// in circles between shots (2026-09-27, Lucy, Olthoi swarm at close
|
||||||
// casts, so the facing race is the same with or without it).
|
// range), and for magic the server waits while the client holds a turn
|
||||||
if (CurrentCombatMode == CombatMode.Magic)
|
// (PendingTurnRelease), which is where the "animates but 0 damage / too
|
||||||
|
// busy" orphaned windups came from. Applies with or without
|
||||||
|
// UseNativeAttack. Only a turn another mode left held is released — with one
|
||||||
|
// settle tick before a cast, so the stop doesn't ride with the packet.
|
||||||
|
if (CurrentCombatMode == CombatMode.Magic || CurrentCombatMode == CombatMode.Missile)
|
||||||
{
|
{
|
||||||
double facingError = GetFacingError(activeTargetId);
|
|
||||||
if (facingError > FACE_TOLERANCE_DEG)
|
|
||||||
{
|
|
||||||
FaceTarget(activeTargetId);
|
|
||||||
if (!_facingTarget)
|
|
||||||
{
|
|
||||||
_facingTarget = true;
|
|
||||||
_faceStartTime = DateTime.Now;
|
|
||||||
}
|
|
||||||
// Keep turning until actually within angle. Do NOT "fire
|
|
||||||
// anyway" while still turning (that was the bug). Only a long
|
|
||||||
// safety timeout falls through, so a jittery point-blank pose
|
|
||||||
// can't wedge combat forever.
|
|
||||||
if ((DateTime.Now - _faceStartTime).TotalMilliseconds < FACE_MAX_WAIT_MS)
|
|
||||||
{
|
|
||||||
LastCombatSkipReason = "facing-turning"; // D4 record-only
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
_host.Log($"[CombatCast] facing did not converge in {FACE_MAX_WAIT_MS:0}ms (err={facingError:0.0}°) — releasing turn + casting anyway");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Within angle (or safety-timed-out). If we were turning, release
|
|
||||||
// the turn motions and give the stop ONE settle tick to reach the
|
|
||||||
// server BEFORE the cast packet.
|
|
||||||
if (_facingTarget)
|
if (_facingTarget)
|
||||||
{
|
{
|
||||||
ClearCombatTurnMotions();
|
ClearCombatTurnMotions();
|
||||||
|
|
@ -2031,7 +2015,8 @@ public class CombatManager : IDisposable
|
||||||
LastCombatSkipReason = "face-settle-release"; // D4 record-only
|
LastCombatSkipReason = "face-settle-release"; // D4 record-only
|
||||||
return true; // settle tick
|
return true; // settle tick
|
||||||
}
|
}
|
||||||
if ((DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS)
|
if (CurrentCombatMode == CombatMode.Magic
|
||||||
|
&& (DateTime.Now - _faceSettledAt).TotalMilliseconds < FACE_SETTLE_MS)
|
||||||
{
|
{
|
||||||
LastCombatSkipReason = "face-settle-wait"; // D4 record-only
|
LastCombatSkipReason = "face-settle-wait"; // D4 record-only
|
||||||
return true; // let the turn-stop settle on the server first
|
return true; // let the turn-stop settle on the server first
|
||||||
|
|
@ -2282,11 +2267,20 @@ public class CombatManager : IDisposable
|
||||||
double bestScore = double.MinValue;
|
double bestScore = double.MinValue;
|
||||||
double heldScore = double.MinValue; // scored total for the incumbent, for the switch log
|
double heldScore = double.MinValue; // scored total for the incumbent, for the switch log
|
||||||
bool incumbentSeen = false;
|
bool incumbentSeen = false;
|
||||||
|
double acquireRange = Math.Max(1.0, _settings.MonsterRange);
|
||||||
foreach (var c in _scannedTargets)
|
foreach (var c in _scannedTargets)
|
||||||
{
|
{
|
||||||
double s = ScoreCandidate(c);
|
double s = ScoreCandidate(c);
|
||||||
|
// The incumbent keeps stickiness and commitment only inside MonsterRange. The
|
||||||
|
// scan holds a locked target out to DisengageDistance (MonsterRange+3 by default)
|
||||||
|
// so a lone mob at the edge doesn't flip engage/peace, not so it can out-score
|
||||||
|
// mobs inside the range the user set. Beyond MonsterRange it competes on its
|
||||||
|
// merits, and any reasonable in-range mob takes over. Before this a target at
|
||||||
|
// 5-8 m kept +45 and could hold off mobs at 3-5 m (2026-09-27, Olthoi swarm:
|
||||||
|
// Monster Range 5, one target kept for over a minute, never out of range).
|
||||||
if (c.Id == _lockedTargetId)
|
if (c.Id == _lockedTargetId)
|
||||||
{
|
{
|
||||||
|
double meritScore = s;
|
||||||
s += TARGET_SWITCH_STICKINESS;
|
s += TARGET_SWITCH_STICKINESS;
|
||||||
// Commitment: once we have COMMITTED to the locked target,
|
// Commitment: once we have COMMITTED to the locked target,
|
||||||
// finishing it outranks any small positional edge a fresh mob
|
// finishing it outranks any small positional edge a fresh mob
|
||||||
|
|
@ -2334,6 +2328,8 @@ public class CombatManager : IDisposable
|
||||||
|
|
||||||
if (!undamaged || (withinFlightWindow && withinUndamagedGrace))
|
if (!undamaged || (withinFlightWindow && withinUndamagedGrace))
|
||||||
s += DAMAGE_COMMITMENT_BONUS;
|
s += DAMAGE_COMMITMENT_BONUS;
|
||||||
|
if (c.Distance > acquireRange)
|
||||||
|
s = meritScore; // beyond MonsterRange: no stickiness, no commitment (see above)
|
||||||
heldScore = s;
|
heldScore = s;
|
||||||
incumbentSeen = true;
|
incumbentSeen = true;
|
||||||
_lockedLastScore = s;
|
_lockedLastScore = s;
|
||||||
|
|
@ -2365,8 +2361,10 @@ public class CombatManager : IDisposable
|
||||||
// up) — if this floods the log, selection is thrashing again and the two
|
// up) — if this floods the log, selection is thrashing again and the two
|
||||||
// scores say by how much.
|
// scores say by how much.
|
||||||
if (_lockedTargetId != 0)
|
if (_lockedTargetId != 0)
|
||||||
_host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' (score={(heldScore == double.MinValue ? "gone" : heldScore.ToString("0.0"))}) " +
|
_host.Log($"[CombatTarget] switch 0x{_lockedTargetId:X8} '{_worldFilter[_lockedTargetId]?.Name}' (score={(heldScore == double.MinValue ? "gone" : heldScore.ToString("0.0"))}, {DescribeTargetPos(_lockedTargetId)}) " +
|
||||||
$"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0})");
|
$"-> 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, {DescribeTargetPos(bestId)})");
|
||||||
|
else
|
||||||
|
_host.Log($"[CombatTarget] lock 0x{bestId:X8} '{_worldFilter[bestId]?.Name}' (score={bestScore:0.0}, {DescribeTargetPos(bestId)})");
|
||||||
|
|
||||||
activeTargetId = bestId;
|
activeTargetId = bestId;
|
||||||
_lockedTargetId = bestId;
|
_lockedTargetId = bestId;
|
||||||
|
|
@ -2898,21 +2896,92 @@ public class CombatManager : IDisposable
|
||||||
return lines;
|
return lines;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attack type for the scan's LOS test. Missile mode names the weapon in hand so the
|
||||||
|
/// bow/crossbow/atlatl arc and its velocity apply (the scan used to pass "", which made
|
||||||
|
/// every missile LOS test a straight line). Peace mode with a missile weapon picked counts
|
||||||
|
/// as missile, so a target acquired from peace is tested with the arc it will be shot on.
|
||||||
|
/// Magic stays a straight line, as before.
|
||||||
|
/// </summary>
|
||||||
private TargetingFSM.AttackType DetermineAttackTypeForLOS()
|
private TargetingFSM.AttackType DetermineAttackTypeForLOS()
|
||||||
{
|
{
|
||||||
if (CurrentCombatMode == CombatMode.Magic)
|
if (_raycastSystem?.TargetingFSM == null) return TargetingFSM.AttackType.Linear;
|
||||||
{
|
|
||||||
// Get rule from current target name if available
|
int mode = CurrentCombatMode;
|
||||||
var targetObj = _worldFilter[activeTargetId];
|
WorldObject? weapon = _equippedWeaponId != 0 ? _worldFilter[_equippedWeaponId] : null;
|
||||||
var rule = GetRuleForTarget(targetObj);
|
bool missileWeapon = weapon != null && weapon.ObjectClass == AcObjectClass.MissileWeapon;
|
||||||
if (rule != null && rule.UseArc) return TargetingFSM.AttackType.MagicArc;
|
if (mode == CombatMode.NonCombat && missileWeapon)
|
||||||
return TargetingFSM.AttackType.Linear;
|
mode = CombatMode.Missile;
|
||||||
|
|
||||||
|
string weaponName = mode == CombatMode.Missile && missileWeapon ? weapon!.Name ?? "" : "";
|
||||||
|
return _raycastSystem.GetAttackType(mode, weaponName);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_raycastSystem?.TargetingFSM != null)
|
// ── LOS / target-distance diagnostics ────────────────────────────────────
|
||||||
return _raycastSystem.GetAttackType(CurrentCombatMode, "");
|
// "Far away" can't be judged from the log without positions, so target lock, switch and
|
||||||
|
// drop lines carry the 3D distance, its horizontal and vertical parts and both cells.
|
||||||
|
// With LosDebugLog on, the scan also logs each target's LOS verdict (line / arc, rise,
|
||||||
|
// hit point) when it changes and at most every LosDebugRepeatMs otherwise.
|
||||||
|
private readonly Dictionary<int, (DateTime At, bool Blocked)> _losDebugLast = new();
|
||||||
|
private const double LosDebugRepeatMs = 5000;
|
||||||
|
private const double LosDebugMinGapMs = 1000;
|
||||||
|
private int _losDebugWeaponId;
|
||||||
|
|
||||||
return TargetingFSM.AttackType.Linear;
|
/// <summary>"d=6.2m (h=5.9 dz=+1.8) cell=0x61450123 me=0x61450119", or why it can't be measured.</summary>
|
||||||
|
private string DescribeTargetPos(int targetId)
|
||||||
|
{
|
||||||
|
uint pid = _host.GetPlayerId();
|
||||||
|
if (pid == 0 || targetId == 0) return "pos=?";
|
||||||
|
if (!_host.TryGetObjectPosition(pid, out uint pc, out float px, out float py, out float pz))
|
||||||
|
return "pos=? (no player position)";
|
||||||
|
if (!_host.TryGetObjectPosition((uint)targetId, out uint tc, out float tx, out float ty, out float tz))
|
||||||
|
return "pos=? (no target position)";
|
||||||
|
double dx = (((tc >> 24) & 0xFF) * 192.0 + tx) - (((pc >> 24) & 0xFF) * 192.0 + px);
|
||||||
|
double dy = (((tc >> 16) & 0xFF) * 192.0 + ty) - (((pc >> 16) & 0xFF) * 192.0 + py);
|
||||||
|
double dz = tz - pz;
|
||||||
|
double h = Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
double d = Math.Sqrt(h * h + dz * dz);
|
||||||
|
return $"d={d:0.0}m (h={h:0.0} dz={dz:+0.0;-0.0;0.0}) cell=0x{tc:X8} me=0x{pc:X8}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LogLosDebug(WorldObject wo, bool blocked, in TargetingFSM.LosDetail det)
|
||||||
|
{
|
||||||
|
DateTime now = DateTime.Now;
|
||||||
|
if (_losDebugLast.TryGetValue(wo.Id, out var last))
|
||||||
|
{
|
||||||
|
double ms = (now - last.At).TotalMilliseconds;
|
||||||
|
bool changed = last.Blocked != blocked;
|
||||||
|
if (ms < LosDebugMinGapMs || (!changed && ms < LosDebugRepeatMs)) return;
|
||||||
|
}
|
||||||
|
if (_losDebugLast.Count > 256) _losDebugLast.Clear();
|
||||||
|
_losDebugLast[wo.Id] = (now, blocked);
|
||||||
|
|
||||||
|
string verdict;
|
||||||
|
if (!det.Checked) verdict = "clear (not tested: no geometry near the path)";
|
||||||
|
else if (det.LineBlocked) verdict = "BLOCKED line";
|
||||||
|
else if (det.ArcChecked && det.Arc.OutOfReach) verdict = "BLOCKED arc: out of reach at this velocity";
|
||||||
|
else if (det.ArcChecked && det.Arc.Blocked) verdict = $"BLOCKED arc: hit {det.Arc.HitAlong:0.0}m out, {det.Arc.HitZ:+0.0;-0.0;0.0}m vs launch";
|
||||||
|
else verdict = "clear";
|
||||||
|
|
||||||
|
string arcInfo = det.Velocity > 0
|
||||||
|
? $" v={det.Velocity:0.0} rise={det.Arc.Sag:0.00} apex={det.Arc.Apex:0.00} clr={_settings.MissileArcClearance:0.0}{(det.ArcChecked ? "" : " (flat: line only)")}"
|
||||||
|
: "";
|
||||||
|
_host.Log($"[LOS] 0x{(uint)wo.Id:X8} '{wo.Name}' {verdict} | {det.Type}{(det.Dungeon ? " dungeon" : "")}{arcInfo} | {DescribeTargetPos(wo.Id)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>LOS debug: once per missile weapon, what the client knows of its launch speed.</summary>
|
||||||
|
private void LogLosDebugWeapon()
|
||||||
|
{
|
||||||
|
int wid = _equippedWeaponId;
|
||||||
|
if (wid == 0 || wid == _losDebugWeaponId) return;
|
||||||
|
var weapon = _worldFilter[wid];
|
||||||
|
if (weapon == null || weapon.ObjectClass != AcObjectClass.MissileWeapon) return;
|
||||||
|
_losDebugWeaponId = wid;
|
||||||
|
double maxVel = _worldFilter.GetDoubleProperty(wid, (uint)DoubleValueKey.MaximumVelocity, 0);
|
||||||
|
var type = DetermineAttackTypeForLOS();
|
||||||
|
float setting = _raycastSystem?.TargetingFSM?.VelocityFor(type) ?? 0f;
|
||||||
|
_host.Log($"[LOS] missile weapon 0x{(uint)wid:X8} '{weapon.Name}': MaximumVelocity={(maxVel > 0 ? maxVel.ToString("0.0") : "unknown (not appraised)")}, " +
|
||||||
|
$"LOS uses {type} v={setting:0.0}");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void FaceTarget(int targetId)
|
private void FaceTarget(int targetId)
|
||||||
|
|
@ -2961,6 +3030,15 @@ public class CombatManager : IDisposable
|
||||||
_host.SetMotion(MotionTurnLeft, false);
|
_host.SetMotion(MotionTurnLeft, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Let go of a turn the facing servo is holding. Called when combat stops
|
||||||
|
/// ticking (macro off), which would otherwise leave the turn held for good.</summary>
|
||||||
|
public void ReleaseHeldTurn()
|
||||||
|
{
|
||||||
|
if (!_facingTarget) return;
|
||||||
|
_facingTarget = false;
|
||||||
|
ClearCombatTurnMotions();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// True while a previously-issued combat cast is still resolving on the ACE
|
/// True while a previously-issued combat cast is still resolving on the ACE
|
||||||
/// server. Serializes magic casts so the next cast's turn/stop motion can't
|
/// server. Serializes magic casts so the next cast's turn/stop motion can't
|
||||||
|
|
|
||||||
|
|
@ -45,6 +45,7 @@ public class MissileCraftingManager
|
||||||
private const int APPLY_RETRY_MS = 2000;
|
private const int APPLY_RETRY_MS = 2000;
|
||||||
private const int CRAFT_TIMEOUT_MS = 15000;
|
private const int CRAFT_TIMEOUT_MS = 15000;
|
||||||
private const int EQUIP_DELAY_MS = 500;
|
private const int EQUIP_DELAY_MS = 500;
|
||||||
|
private const int ERROR_BACKOFF_MS = 60000;
|
||||||
|
|
||||||
private int _headBundleId = 0;
|
private int _headBundleId = 0;
|
||||||
private int _shaftBundleId = 0;
|
private int _shaftBundleId = 0;
|
||||||
|
|
@ -69,9 +70,19 @@ public class MissileCraftingManager
|
||||||
|
|
||||||
public void ProcessCrafting()
|
public void ProcessCrafting()
|
||||||
{
|
{
|
||||||
if (!_settings.EnableMissileCrafting) return;
|
// While State isn't Idle the plugin holds combat, nav and looting, so turning
|
||||||
|
// crafting off mid-craft must let go too.
|
||||||
|
if (!_settings.EnableMissileCrafting)
|
||||||
|
{
|
||||||
|
if (State != CraftState.Idle) Reset("Missile crafting turned off");
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (IsBusy) return;
|
if (IsBusy) return;
|
||||||
|
|
||||||
|
// An exception here used to leave State where it was, and the bot stood still
|
||||||
|
// forever with nothing in chat: say what broke, let go, and try again later.
|
||||||
|
try
|
||||||
|
{
|
||||||
switch (State)
|
switch (State)
|
||||||
{
|
{
|
||||||
case CraftState.Idle: ProcessIdle(); break;
|
case CraftState.Idle: ProcessIdle(); break;
|
||||||
|
|
@ -80,6 +91,14 @@ public class MissileCraftingManager
|
||||||
case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break;
|
case CraftState.EquippingAmmo: ProcessEquippingAmmo(); break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
string reason = $"Stopped by an error ({ex.GetType().Name}: {ex.Message}); trying again in a minute";
|
||||||
|
if (State == CraftState.Idle) ChatLog(reason); // Reset only speaks for a craft in progress
|
||||||
|
Reset(reason);
|
||||||
|
_lastAmmoCheck = DateTime.Now.AddMilliseconds(ERROR_BACKOFF_MS - AMMO_CHECK_INTERVAL_MS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ══════════════════════════════════════════════════════════════════
|
// ══════════════════════════════════════════════════════════════════
|
||||||
// CHAT HANDLER — called from RynthAiPlugin.OnChatWindowText
|
// CHAT HANDLER — called from RynthAiPlugin.OnChatWindowText
|
||||||
|
|
@ -169,9 +188,22 @@ public class MissileCraftingManager
|
||||||
if (bestCraftable != null)
|
if (bestCraftable != null)
|
||||||
{ StartCrafting(bestCraftable, inv); return; }
|
{ StartCrafting(bestCraftable, inv); return; }
|
||||||
|
|
||||||
|
// No ammo at all and only bundles the skill check calls risky: a bow with nothing
|
||||||
|
// to shoot can't fight, so a combine that may fail beats standing there.
|
||||||
if (tooHard != null)
|
if (tooHard != null)
|
||||||
Reset($"No ammo, and Fletching {fletching?.Buffed} is too low to make {tooHard.OutputName} reliably " +
|
{
|
||||||
$"(difficulty {tooHard.Difficulty}; a failed combine destroys both bundles)");
|
int skill = fletching?.Buffed ?? 250;
|
||||||
|
ChatLog($"No ammo: making {tooHard.OutputName} anyway, about " +
|
||||||
|
$"{AmmoRecipes.SuccessChance(skill, tooHard.Difficulty):P0} with Fletching {skill} " +
|
||||||
|
"(a failed combine destroys both bundles)");
|
||||||
|
StartCrafting(tooHard, inv);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fletching != null && fletching.Training < 2
|
||||||
|
&& AmmoRecipes.BestCraftable(inv.Select(i => i.Name), category, 0, out var carried) == null
|
||||||
|
&& carried != null)
|
||||||
|
Reset($"No ammo, and Fletching is untrained, so the bundles for {carried.OutputName} can't be combined");
|
||||||
else
|
else
|
||||||
Reset("No ammo and no bundles available");
|
Reset("No ammo and no bundles available");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -903,7 +903,11 @@ public class WorldObjectCache
|
||||||
float dx = gx1 - gx2;
|
float dx = gx1 - gx2;
|
||||||
float dy = gy1 - gy2;
|
float dy = gy1 - gy2;
|
||||||
float dz = z1 - z2;
|
float dz = z1 - z2;
|
||||||
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
|
double d = Math.Sqrt(dx * dx + dy * dy + dz * dz);
|
||||||
|
// A garbage position read (NaN/∞) must read as out of range. NaN fails every
|
||||||
|
// "dist > limit" test, so it passed both the scan's range gate and Think's
|
||||||
|
// disengage drop, and a target could be kept at any real distance.
|
||||||
|
return double.IsFinite(d) ? d : double.MaxValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Enumerate objects in player's inventory (no physics position).</summary>
|
/// <summary>Enumerate objects in player's inventory (no physics position).</summary>
|
||||||
|
|
@ -1547,7 +1551,7 @@ public class WorldObjectCache
|
||||||
|
|
||||||
// ── Type-flag item classification ─────────────────────────────────────
|
// ── Type-flag item classification ─────────────────────────────────────
|
||||||
|
|
||||||
private static AcObjectClass ClassifyByItemType(uint typeFlags)
|
internal static AcObjectClass ClassifyByItemType(uint typeFlags)
|
||||||
{
|
{
|
||||||
// Most specific / unambiguous types first
|
// Most specific / unambiguous types first
|
||||||
if ((typeFlags & ItemTypePromissoryNote) != 0) return AcObjectClass.TradeNote;
|
if ((typeFlags & ItemTypePromissoryNote) != 0) return AcObjectClass.TradeNote;
|
||||||
|
|
|
||||||
|
|
@ -374,16 +374,32 @@ public sealed partial class RynthAiPlugin
|
||||||
|
|
||||||
public override void OnVendorOpen(uint vendorId)
|
public override void OnVendorOpen(uint vendorId)
|
||||||
{
|
{
|
||||||
|
_metaManager?.OnVendorOpen(vendorId);
|
||||||
|
|
||||||
|
// AutoVendor prints the open line itself (UB's merchant-info line when it can read the
|
||||||
|
// vendor, once per open rather than on every list re-send) and may start a session.
|
||||||
|
var autoVendor = _autoVendor;
|
||||||
|
if (autoVendor != null)
|
||||||
|
{
|
||||||
|
autoVendor.OnVendorOpen(vendorId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}";
|
string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}";
|
||||||
Host.WriteToChat($"[RynthAi] Vendor open: {label}", 1);
|
Host.WriteToChat($"[RynthAi] Vendor open: {label}", 1);
|
||||||
_metaManager?.OnVendorOpen(vendorId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override void OnVendorClose(uint vendorId)
|
public override void OnVendorClose(uint vendorId)
|
||||||
{
|
{
|
||||||
|
_metaManager?.OnVendorClose(vendorId);
|
||||||
|
|
||||||
|
var autoVendor = _autoVendor;
|
||||||
|
if (autoVendor != null)
|
||||||
|
{
|
||||||
|
autoVendor.OnVendorClose(vendorId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}";
|
string label = Host.TryGetObjectName(vendorId, out string name) ? name : $"0x{vendorId:X8}";
|
||||||
Host.WriteToChat($"[RynthAi] Vendor closed: {label}", 1);
|
Host.WriteToChat($"[RynthAi] Vendor closed: {label}", 1);
|
||||||
_metaManager?.OnVendorClose(vendorId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void TickCorpseOpening()
|
private void TickCorpseOpening()
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,9 @@ internal sealed class LegacyAdvancedSettingsUi
|
||||||
|
|
||||||
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _missileCraftingManager = mgr;
|
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _missileCraftingManager = mgr;
|
||||||
|
|
||||||
|
private Func<string>? _autoVendorStatus;
|
||||||
|
public void SetAutoVendorStatusProvider(Func<string> status) => _autoVendorStatus = status;
|
||||||
|
|
||||||
public string MissileCraftingState => _missileCraftingManager?.State.ToString() ?? string.Empty;
|
public string MissileCraftingState => _missileCraftingManager?.State.ToString() ?? string.Empty;
|
||||||
public bool MissileCraftingActive => _missileCraftingManager?.IsCrafting ?? false;
|
public bool MissileCraftingActive => _missileCraftingManager?.IsCrafting ?? false;
|
||||||
public string MissileCraftingStatus => _missileCraftingManager?.StatusMessage ?? string.Empty;
|
public string MissileCraftingStatus => _missileCraftingManager?.StatusMessage ?? string.Empty;
|
||||||
|
|
@ -60,6 +63,51 @@ internal sealed class LegacyAdvancedSettingsUi
|
||||||
ImGui.End();
|
ImGui.End();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void RenderVendoring()
|
||||||
|
{
|
||||||
|
ImGui.Text("AutoVendor (UtilityBelt)");
|
||||||
|
ImGui.Separator();
|
||||||
|
ImGui.Spacing();
|
||||||
|
|
||||||
|
string status = _autoVendorStatus?.Invoke() ?? "Not logged in";
|
||||||
|
ImGui.TextDisabled($"Status: {status}");
|
||||||
|
ImGui.Spacing();
|
||||||
|
|
||||||
|
ImGui.Checkbox("Enabled##AV", ref _settings.AutoVendorEnabled);
|
||||||
|
if (ImGui.IsItemHovered())
|
||||||
|
ImGui.SetTooltip("Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\n" +
|
||||||
|
"Profiles: <Vendor Name>.utl or default.utl in your character's AutoVendor\n" +
|
||||||
|
"folder, the server folder, or " + Vendor.AutoVendorManager.MainProfileDir + ".");
|
||||||
|
ImGui.Checkbox("Test Mode (only print what it would do)##AV", ref _settings.AutoVendorTestMode);
|
||||||
|
if (ImGui.IsItemHovered())
|
||||||
|
ImGui.SetTooltip("Lists what would be bought and sold without trading. Leave this on until\n" +
|
||||||
|
"the list looks right: selling can't be undone.");
|
||||||
|
ImGui.Checkbox("Buy##AV", ref _settings.AutoVendorEnableBuying);
|
||||||
|
ImGui.SameLine();
|
||||||
|
ImGui.Checkbox("Sell##AV", ref _settings.AutoVendorEnableSelling);
|
||||||
|
ImGui.Checkbox("Only Sell From Main Pack##AV", ref _settings.AutoVendorOnlyFromMainPack);
|
||||||
|
ImGui.Checkbox("Show Merchant Info##AV", ref _settings.AutoVendorShowMerchantInfo);
|
||||||
|
if (ImGui.IsItemHovered())
|
||||||
|
ImGui.SetTooltip("Print the vendor's buy/sell rates and max value when it opens.");
|
||||||
|
ImGui.Checkbox("Think When Finished##AV", ref _settings.AutoVendorThink);
|
||||||
|
if (ImGui.IsItemHovered())
|
||||||
|
ImGui.SetTooltip("Send 'AutoVendor finished: <vendor>' (and failures) as a /tell to yourself,\n" +
|
||||||
|
"so a meta's chat condition can wait for it.");
|
||||||
|
|
||||||
|
ImGui.Spacing();
|
||||||
|
ImGui.Text("/ub vendor open");
|
||||||
|
ImGui.SetNextItemWidth(120);
|
||||||
|
if (ImGui.InputInt("Tries##AV", ref _settings.AutoVendorTries))
|
||||||
|
_settings.AutoVendorTries = Math.Clamp(_settings.AutoVendorTries, 1, 20);
|
||||||
|
ImGui.SetNextItemWidth(120);
|
||||||
|
if (ImGui.InputInt("Time Between Tries (ms)##AV", ref _settings.AutoVendorTriesTime, 250))
|
||||||
|
_settings.AutoVendorTriesTime = Math.Clamp(_settings.AutoVendorTriesTime, 500, 30000);
|
||||||
|
|
||||||
|
ImGui.Spacing();
|
||||||
|
ImGui.TextDisabled("Never sold: equipped, attuned, bonded, retained, tinkered, imbued,");
|
||||||
|
ImGui.TextDisabled("inscribed, rare, zero value, packs, or anything a Keep rule could match.");
|
||||||
|
}
|
||||||
|
|
||||||
private void RenderTabContent(int tabIndex)
|
private void RenderTabContent(int tabIndex)
|
||||||
{
|
{
|
||||||
if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length)
|
if (tabIndex < 0 || tabIndex >= _settings.AdvancedTabs.Length)
|
||||||
|
|
@ -147,10 +195,15 @@ internal sealed class LegacyAdvancedSettingsUi
|
||||||
ImGui.Spacing();
|
ImGui.Spacing();
|
||||||
ImGui.Text("Missile Arc Velocities (m/s)");
|
ImGui.Text("Missile Arc Velocities (m/s)");
|
||||||
if (ImGui.IsItemHovered())
|
if (ImGui.IsItemHovered())
|
||||||
ImGui.SetTooltip("Per-weapon projectile speed used for line-of-sight arc checks.\nLower velocity = higher arc. Tune until LoS matches in-game hits.\nDungeons always use linear checks to avoid false ceiling blocks.");
|
ImGui.SetTooltip("Per-weapon launch speed used for line-of-sight arc checks.\n" +
|
||||||
|
"Lower velocity = higher arc. Tune until LoS matches in-game hits\n" +
|
||||||
|
"(/ra lostest bow on a selected mob shows the arc and where it hits).\n" +
|
||||||
|
"Indoors the arc is checked against ceilings too.");
|
||||||
ImGui.Checkbox("Use Arcs for Missile LoS", ref _settings.UseArcs);
|
ImGui.Checkbox("Use Arcs for Missile LoS", ref _settings.UseArcs);
|
||||||
if (ImGui.IsItemHovered())
|
if (ImGui.IsItemHovered())
|
||||||
ImGui.SetTooltip("When off, all missile LoS checks are linear (eye-to-eye).");
|
ImGui.SetTooltip("On: a missile target must pass the straight line AND the arc the\n" +
|
||||||
|
"missile flies (checked against ceilings in dungeons).\n" +
|
||||||
|
"Off: all missile LoS checks are a straight line (eye-to-eye).");
|
||||||
if (_settings.UseArcs)
|
if (_settings.UseArcs)
|
||||||
{
|
{
|
||||||
ImGui.Indent();
|
ImGui.Indent();
|
||||||
|
|
@ -162,8 +215,18 @@ internal sealed class LegacyAdvancedSettingsUi
|
||||||
ImGui.SliderFloat("Atlatl", ref _settings.AtlatlArcVelocity, 10.0f, 60.0f, "%.1f");
|
ImGui.SliderFloat("Atlatl", ref _settings.AtlatlArcVelocity, 10.0f, 60.0f, "%.1f");
|
||||||
ImGui.SetNextItemWidth(150);
|
ImGui.SetNextItemWidth(150);
|
||||||
ImGui.SliderFloat("Magic Arc", ref _settings.MagicArcVelocity, 10.0f, 60.0f, "%.1f");
|
ImGui.SliderFloat("Magic Arc", ref _settings.MagicArcVelocity, 10.0f, 60.0f, "%.1f");
|
||||||
|
ImGui.SetNextItemWidth(150);
|
||||||
|
ImGui.SliderFloat("Arc Clearance (m)", ref _settings.MissileArcClearance, 0.0f, 3.0f, "%.1f");
|
||||||
|
if (ImGui.IsItemHovered())
|
||||||
|
ImGui.SetTooltip("Extra headroom the arc must have at mid-flight. Raise it if shots\n" +
|
||||||
|
"still hit ceilings; lower it if mobs the arrows can reach are skipped.\n" +
|
||||||
|
"Default 0.5.");
|
||||||
ImGui.Unindent();
|
ImGui.Unindent();
|
||||||
}
|
}
|
||||||
|
ImGui.Checkbox("LoS Debug Log", ref _settings.LosDebugLog);
|
||||||
|
if (ImGui.IsItemHovered())
|
||||||
|
ImGui.SetTooltip("Log each in-range mob's LoS verdict ([LOS] lines: straight line or arc,\n" +
|
||||||
|
"how high the arc rises, where it hits, distance and cells). For tuning.");
|
||||||
|
|
||||||
ImGui.Separator();
|
ImGui.Separator();
|
||||||
ImGui.Spacing();
|
ImGui.Spacing();
|
||||||
|
|
@ -490,6 +553,12 @@ internal sealed class LegacyAdvancedSettingsUi
|
||||||
if (ImGui.IsItemHovered())
|
if (ImGui.IsItemHovered())
|
||||||
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint).");
|
ImGui.SetTooltip("Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off (aim straight at each waypoint).");
|
||||||
|
|
||||||
|
ImGui.SetNextItemWidth(80);
|
||||||
|
ImGui.InputFloat("Shortcut Tolerance (yd)", ref _settings.NavShortcutYards, 0.5f, 1f, "%.1f");
|
||||||
|
_settings.NavShortcutYards = Math.Clamp(_settings.NavShortcutYards, 0f, 10f);
|
||||||
|
if (ImGui.IsItemHovered())
|
||||||
|
ImGui.SetTooltip("On reaching a waypoint, skip ahead only while the straight line to a later waypoint passes within this distance of every waypoint skipped. Lower keeps closer to the route; 0 = visit every waypoint.");
|
||||||
|
|
||||||
ImGui.SetNextItemWidth(80);
|
ImGui.SetNextItemWidth(80);
|
||||||
ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f");
|
ImGui.InputFloat("Turn Rate (deg/s)", ref _settings.NavTurnRateDegPerSec, 15f, 45f, "%.0f");
|
||||||
if (ImGui.IsItemHovered())
|
if (ImGui.IsItemHovered())
|
||||||
|
|
@ -541,6 +610,15 @@ internal sealed class LegacyAdvancedSettingsUi
|
||||||
"values (<60s) risk a gap between the old buff dropping and the new one\n" +
|
"values (<60s) risk a gap between the old buff dropping and the new one\n" +
|
||||||
"landing.");
|
"landing.");
|
||||||
|
|
||||||
|
ImGui.SetNextItemWidth(180);
|
||||||
|
ImGui.SliderInt("Also Refresh Under (seconds left)", ref _settings.RebuffTopOffSecondsRemaining, 30, 3600);
|
||||||
|
if (ImGui.IsItemHovered())
|
||||||
|
ImGui.SetTooltip(
|
||||||
|
"When a buff is due, also recast every other buff with less than this\n" +
|
||||||
|
"much time left, so they land together. Buffs with more time are left\n" +
|
||||||
|
"alone. Default 1200 (20 minutes). At or below 'Rebuff With', only the\n" +
|
||||||
|
"expiring buff is recast.");
|
||||||
|
|
||||||
ImGui.Spacing();
|
ImGui.Spacing();
|
||||||
ImGui.Separator();
|
ImGui.Separator();
|
||||||
ImGui.Text("Buff Difficulty (Min Buffed Skill)");
|
ImGui.Text("Buff Difficulty (Min Buffed Skill)");
|
||||||
|
|
@ -667,6 +745,10 @@ internal sealed class LegacyAdvancedSettingsUi
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case "Vendoring":
|
||||||
|
RenderVendoring();
|
||||||
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
ImGui.Text($"Settings for {tabName} are currently under development.");
|
ImGui.Text($"Settings for {tabName} are currently under development.");
|
||||||
break;
|
break;
|
||||||
|
|
|
||||||
|
|
@ -280,6 +280,12 @@ internal sealed class LegacyDashboardRenderer
|
||||||
public void SetWorldFilter(WorldObjectCache cache) => _weaponsUi.SetWorldFilter(cache);
|
public void SetWorldFilter(WorldObjectCache cache) => _weaponsUi.SetWorldFilter(cache);
|
||||||
|
|
||||||
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedSettingsUi.SetMissileCraftingManager(mgr);
|
public void SetMissileCraftingManager(MissileCraftingManager mgr) => _advancedSettingsUi.SetMissileCraftingManager(mgr);
|
||||||
|
public void SetAutoVendorStatusProvider(Func<string> status) => _advancedSettingsUi.SetAutoVendorStatusProvider(status);
|
||||||
|
|
||||||
|
// The open vendor's AutoVendor profile path (null when no vendor is open), for the
|
||||||
|
// dashboard snapshot's vendorProfilePath.
|
||||||
|
private Func<string?>? _vendorProfilePath;
|
||||||
|
public void SetVendorProfilePathProvider(Func<string?> path) => _vendorProfilePath = path;
|
||||||
|
|
||||||
public void SetRaycast(Raycasting.MainLogic raycast)
|
public void SetRaycast(Raycasting.MainLogic raycast)
|
||||||
{
|
{
|
||||||
|
|
@ -766,6 +772,8 @@ internal sealed class LegacyDashboardRenderer
|
||||||
CrossbowArcVelocity = s.CrossbowArcVelocity,
|
CrossbowArcVelocity = s.CrossbowArcVelocity,
|
||||||
AtlatlArcVelocity = s.AtlatlArcVelocity,
|
AtlatlArcVelocity = s.AtlatlArcVelocity,
|
||||||
MagicArcVelocity = s.MagicArcVelocity,
|
MagicArcVelocity = s.MagicArcVelocity,
|
||||||
|
MissileArcClearance = s.MissileArcClearance,
|
||||||
|
LosDebugLog = s.LosDebugLog,
|
||||||
BlacklistAttempts = s.BlacklistAttempts,
|
BlacklistAttempts = s.BlacklistAttempts,
|
||||||
BlacklistTimeoutSec = s.BlacklistTimeoutSec,
|
BlacklistTimeoutSec = s.BlacklistTimeoutSec,
|
||||||
BlacklistCastSettleMs = s.BlacklistCastSettleMs,
|
BlacklistCastSettleMs = s.BlacklistCastSettleMs,
|
||||||
|
|
@ -827,6 +835,7 @@ internal sealed class LegacyDashboardRenderer
|
||||||
NavDeadZone = s.NavDeadZone,
|
NavDeadZone = s.NavDeadZone,
|
||||||
NavSweepMult = s.NavSweepMult,
|
NavSweepMult = s.NavSweepMult,
|
||||||
NavLookaheadYards = s.NavLookaheadYards,
|
NavLookaheadYards = s.NavLookaheadYards,
|
||||||
|
NavShortcutYards = s.NavShortcutYards,
|
||||||
NavTurnRateDegPerSec = s.NavTurnRateDegPerSec,
|
NavTurnRateDegPerSec = s.NavTurnRateDegPerSec,
|
||||||
NavTier1TurnSpeed = s.NavTier1TurnSpeed,
|
NavTier1TurnSpeed = s.NavTier1TurnSpeed,
|
||||||
PostPortalDelaySec = s.PostPortalDelaySec,
|
PostPortalDelaySec = s.PostPortalDelaySec,
|
||||||
|
|
@ -840,6 +849,7 @@ internal sealed class LegacyDashboardRenderer
|
||||||
EnableBuffing = s.EnableBuffing,
|
EnableBuffing = s.EnableBuffing,
|
||||||
RebuffWhenIdle = s.RebuffWhenIdle,
|
RebuffWhenIdle = s.RebuffWhenIdle,
|
||||||
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
|
RebuffSecondsRemaining = s.RebuffSecondsRemaining,
|
||||||
|
RebuffTopOffSecondsRemaining = s.RebuffTopOffSecondsRemaining,
|
||||||
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
|
BuffMinSkillLevelTier1 = s.BuffMinSkillLevelTier1,
|
||||||
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
|
BuffMinSkillLevelTier2 = s.BuffMinSkillLevelTier2,
|
||||||
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
|
BuffMinSkillLevelTier3 = s.BuffMinSkillLevelTier3,
|
||||||
|
|
@ -878,6 +888,16 @@ internal sealed class LegacyDashboardRenderer
|
||||||
SalvageSalvageDelayMs = s.SalvageSalvageDelayMs,
|
SalvageSalvageDelayMs = s.SalvageSalvageDelayMs,
|
||||||
SalvageResultDelayFirstMs = s.SalvageResultDelayFirstMs,
|
SalvageResultDelayFirstMs = s.SalvageResultDelayFirstMs,
|
||||||
SalvageResultDelayFastMs = s.SalvageResultDelayFastMs,
|
SalvageResultDelayFastMs = s.SalvageResultDelayFastMs,
|
||||||
|
// Vendoring (AutoVendor)
|
||||||
|
AutoVendorEnabled = s.AutoVendorEnabled,
|
||||||
|
AutoVendorEnableBuying = s.AutoVendorEnableBuying,
|
||||||
|
AutoVendorEnableSelling = s.AutoVendorEnableSelling,
|
||||||
|
AutoVendorTestMode = s.AutoVendorTestMode,
|
||||||
|
AutoVendorThink = s.AutoVendorThink,
|
||||||
|
AutoVendorShowMerchantInfo = s.AutoVendorShowMerchantInfo,
|
||||||
|
AutoVendorOnlyFromMainPack = s.AutoVendorOnlyFromMainPack,
|
||||||
|
AutoVendorTries = s.AutoVendorTries,
|
||||||
|
AutoVendorTriesTime = s.AutoVendorTriesTime,
|
||||||
};
|
};
|
||||||
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.SettingsBridgePayload);
|
return JsonSerializer.Serialize(payload, RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||||
}
|
}
|
||||||
|
|
@ -892,7 +912,20 @@ internal sealed class LegacyDashboardRenderer
|
||||||
if (string.IsNullOrWhiteSpace(json)) return;
|
if (string.IsNullOrWhiteSpace(json)) return;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var p = JsonSerializer.Deserialize(json, RynthAiJsonContext.Default.SettingsBridgePayload);
|
// Lay the sent fields over the current settings, so a field the sender leaves
|
||||||
|
// out keeps its value instead of deserializing to 0 and being applied. The
|
||||||
|
// overlay's Settings panel keeps its own copy of this payload; when that copy
|
||||||
|
// lacked BlacklistCastSettleMs/MonsterDisengageRange, every click zeroed them.
|
||||||
|
var merged = System.Text.Json.Nodes.JsonNode.Parse(BuildSettingsJson(),
|
||||||
|
new System.Text.Json.Nodes.JsonNodeOptions { PropertyNameCaseInsensitive = true })?.AsObject();
|
||||||
|
if (merged == null) return;
|
||||||
|
using (var sent = JsonDocument.Parse(json))
|
||||||
|
{
|
||||||
|
if (sent.RootElement.ValueKind != JsonValueKind.Object) return;
|
||||||
|
foreach (var prop in sent.RootElement.EnumerateObject())
|
||||||
|
merged[prop.Name] = System.Text.Json.Nodes.JsonNode.Parse(prop.Value.GetRawText());
|
||||||
|
}
|
||||||
|
var p = JsonSerializer.Deserialize(merged.ToJsonString(), RynthAiJsonContext.Default.SettingsBridgePayload);
|
||||||
if (p == null) return;
|
if (p == null) return;
|
||||||
var s = _settings;
|
var s = _settings;
|
||||||
// Display
|
// Display
|
||||||
|
|
@ -918,9 +951,13 @@ internal sealed class LegacyDashboardRenderer
|
||||||
s.CrossbowArcVelocity = p.CrossbowArcVelocity;
|
s.CrossbowArcVelocity = p.CrossbowArcVelocity;
|
||||||
s.AtlatlArcVelocity = p.AtlatlArcVelocity;
|
s.AtlatlArcVelocity = p.AtlatlArcVelocity;
|
||||||
s.MagicArcVelocity = p.MagicArcVelocity;
|
s.MagicArcVelocity = p.MagicArcVelocity;
|
||||||
|
if (p.MissileArcClearance >= 0f) s.MissileArcClearance = Math.Min(p.MissileArcClearance, 3f);
|
||||||
|
s.LosDebugLog = p.LosDebugLog;
|
||||||
s.BlacklistAttempts = p.BlacklistAttempts;
|
s.BlacklistAttempts = p.BlacklistAttempts;
|
||||||
s.BlacklistTimeoutSec = p.BlacklistTimeoutSec;
|
s.BlacklistTimeoutSec = p.BlacklistTimeoutSec;
|
||||||
s.BlacklistCastSettleMs = p.BlacklistCastSettleMs;
|
// -1 = not sent. 0 is never meant (it judges a cast before its damage can land)
|
||||||
|
// and is what the bug saved into profiles, so it keeps the default too.
|
||||||
|
if (p.BlacklistCastSettleMs > 0) s.BlacklistCastSettleMs = p.BlacklistCastSettleMs;
|
||||||
s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec;
|
s.TargetNoProgressTimeoutSec = p.TargetNoProgressTimeoutSec;
|
||||||
s.GiveQueueIntervalMs = p.GiveQueueIntervalMs;
|
s.GiveQueueIntervalMs = p.GiveQueueIntervalMs;
|
||||||
// Recharge
|
// Recharge
|
||||||
|
|
@ -957,7 +994,7 @@ internal sealed class LegacyDashboardRenderer
|
||||||
s.MinSkillLevelTier8 = p.MinSkillLevelTier8;
|
s.MinSkillLevelTier8 = p.MinSkillLevelTier8;
|
||||||
// Ranges
|
// Ranges
|
||||||
s.MonsterRange = p.MonsterRange;
|
s.MonsterRange = p.MonsterRange;
|
||||||
s.MonsterDisengageRange = p.MonsterDisengageRange;
|
if (p.MonsterDisengageRange >= 0) s.MonsterDisengageRange = p.MonsterDisengageRange; // -1 = not sent
|
||||||
s.RingRange = p.RingRange;
|
s.RingRange = p.RingRange;
|
||||||
s.ApproachRange = p.ApproachRange;
|
s.ApproachRange = p.ApproachRange;
|
||||||
s.CorpseApproachRangeMax = p.CorpseApproachRangeMax;
|
s.CorpseApproachRangeMax = p.CorpseApproachRangeMax;
|
||||||
|
|
@ -979,6 +1016,7 @@ internal sealed class LegacyDashboardRenderer
|
||||||
s.NavDeadZone = p.NavDeadZone;
|
s.NavDeadZone = p.NavDeadZone;
|
||||||
s.NavSweepMult = p.NavSweepMult;
|
s.NavSweepMult = p.NavSweepMult;
|
||||||
s.NavLookaheadYards = p.NavLookaheadYards;
|
s.NavLookaheadYards = p.NavLookaheadYards;
|
||||||
|
s.NavShortcutYards = p.NavShortcutYards;
|
||||||
s.NavTurnRateDegPerSec = p.NavTurnRateDegPerSec;
|
s.NavTurnRateDegPerSec = p.NavTurnRateDegPerSec;
|
||||||
s.NavTier1TurnSpeed = p.NavTier1TurnSpeed;
|
s.NavTier1TurnSpeed = p.NavTier1TurnSpeed;
|
||||||
s.PostPortalDelaySec = p.PostPortalDelaySec;
|
s.PostPortalDelaySec = p.PostPortalDelaySec;
|
||||||
|
|
@ -992,6 +1030,7 @@ internal sealed class LegacyDashboardRenderer
|
||||||
s.EnableBuffing = p.EnableBuffing;
|
s.EnableBuffing = p.EnableBuffing;
|
||||||
s.RebuffWhenIdle = p.RebuffWhenIdle;
|
s.RebuffWhenIdle = p.RebuffWhenIdle;
|
||||||
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
|
s.RebuffSecondsRemaining = p.RebuffSecondsRemaining;
|
||||||
|
if (p.RebuffTopOffSecondsRemaining > 0) s.RebuffTopOffSecondsRemaining = p.RebuffTopOffSecondsRemaining;
|
||||||
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
|
s.BuffMinSkillLevelTier1 = p.BuffMinSkillLevelTier1;
|
||||||
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
|
s.BuffMinSkillLevelTier2 = p.BuffMinSkillLevelTier2;
|
||||||
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
|
s.BuffMinSkillLevelTier3 = p.BuffMinSkillLevelTier3;
|
||||||
|
|
@ -1027,6 +1066,16 @@ internal sealed class LegacyDashboardRenderer
|
||||||
s.SalvageSalvageDelayMs = p.SalvageSalvageDelayMs;
|
s.SalvageSalvageDelayMs = p.SalvageSalvageDelayMs;
|
||||||
s.SalvageResultDelayFirstMs = p.SalvageResultDelayFirstMs;
|
s.SalvageResultDelayFirstMs = p.SalvageResultDelayFirstMs;
|
||||||
s.SalvageResultDelayFastMs = p.SalvageResultDelayFastMs;
|
s.SalvageResultDelayFastMs = p.SalvageResultDelayFastMs;
|
||||||
|
// Vendoring: only fields the sender actually included (older panels omit them)
|
||||||
|
if (p.AutoVendorEnabled is bool avOn) s.AutoVendorEnabled = avOn;
|
||||||
|
if (p.AutoVendorEnableBuying is bool avBuy) s.AutoVendorEnableBuying = avBuy;
|
||||||
|
if (p.AutoVendorEnableSelling is bool avSell) s.AutoVendorEnableSelling = avSell;
|
||||||
|
if (p.AutoVendorTestMode is bool avTest) s.AutoVendorTestMode = avTest;
|
||||||
|
if (p.AutoVendorThink is bool avThink) s.AutoVendorThink = avThink;
|
||||||
|
if (p.AutoVendorShowMerchantInfo is bool avInfo) s.AutoVendorShowMerchantInfo = avInfo;
|
||||||
|
if (p.AutoVendorOnlyFromMainPack is bool avMain) s.AutoVendorOnlyFromMainPack = avMain;
|
||||||
|
if (p.AutoVendorTries is int avTries) s.AutoVendorTries = Math.Clamp(avTries, 1, 20);
|
||||||
|
if (p.AutoVendorTriesTime is int avTime) s.AutoVendorTriesTime = Math.Clamp(avTime, 500, 30000);
|
||||||
SaveSettings();
|
SaveSettings();
|
||||||
}
|
}
|
||||||
catch { }
|
catch { }
|
||||||
|
|
@ -1302,6 +1351,7 @@ internal sealed class LegacyDashboardRenderer
|
||||||
dst.NavDeadZone = tmp.NavDeadZone;
|
dst.NavDeadZone = tmp.NavDeadZone;
|
||||||
dst.NavSweepMult = tmp.NavSweepMult;
|
dst.NavSweepMult = tmp.NavSweepMult;
|
||||||
dst.NavLookaheadYards = tmp.NavLookaheadYards;
|
dst.NavLookaheadYards = tmp.NavLookaheadYards;
|
||||||
|
dst.NavShortcutYards = tmp.NavShortcutYards;
|
||||||
dst.NavTurnRateDegPerSec = tmp.NavTurnRateDegPerSec;
|
dst.NavTurnRateDegPerSec = tmp.NavTurnRateDegPerSec;
|
||||||
dst.NavTier1TurnSpeed = tmp.NavTier1TurnSpeed;
|
dst.NavTier1TurnSpeed = tmp.NavTier1TurnSpeed;
|
||||||
dst.PostPortalDelaySec = tmp.PostPortalDelaySec;
|
dst.PostPortalDelaySec = tmp.PostPortalDelaySec;
|
||||||
|
|
@ -1384,9 +1434,12 @@ internal sealed class LegacyDashboardRenderer
|
||||||
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
|
dst.PeaceModeWhenIdle = tmp.PeaceModeWhenIdle;
|
||||||
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
|
dst.RebuffWhenIdle = tmp.RebuffWhenIdle;
|
||||||
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
|
dst.RebuffSecondsRemaining = tmp.RebuffSecondsRemaining;
|
||||||
|
dst.RebuffTopOffSecondsRemaining = tmp.RebuffTopOffSecondsRemaining;
|
||||||
dst.BlacklistAttempts = tmp.BlacklistAttempts;
|
dst.BlacklistAttempts = tmp.BlacklistAttempts;
|
||||||
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
|
dst.BlacklistTimeoutSec = tmp.BlacklistTimeoutSec;
|
||||||
dst.BlacklistCastSettleMs = tmp.BlacklistCastSettleMs;
|
// 0 is never meant (every UI floors it at 250+) and is what the Settings-panel bug
|
||||||
|
// saved into profiles: it judges each cast before its damage can land.
|
||||||
|
dst.BlacklistCastSettleMs = tmp.BlacklistCastSettleMs > 0 ? tmp.BlacklistCastSettleMs : 1500;
|
||||||
dst.TargetNoProgressTimeoutSec = tmp.TargetNoProgressTimeoutSec;
|
dst.TargetNoProgressTimeoutSec = tmp.TargetNoProgressTimeoutSec;
|
||||||
dst.MeleeAttackPower = tmp.MeleeAttackPower;
|
dst.MeleeAttackPower = tmp.MeleeAttackPower;
|
||||||
dst.MissileAttackPower = tmp.MissileAttackPower;
|
dst.MissileAttackPower = tmp.MissileAttackPower;
|
||||||
|
|
@ -1399,6 +1452,8 @@ internal sealed class LegacyDashboardRenderer
|
||||||
dst.CrossbowArcVelocity = tmp.CrossbowArcVelocity;
|
dst.CrossbowArcVelocity = tmp.CrossbowArcVelocity;
|
||||||
dst.AtlatlArcVelocity = tmp.AtlatlArcVelocity;
|
dst.AtlatlArcVelocity = tmp.AtlatlArcVelocity;
|
||||||
dst.MagicArcVelocity = tmp.MagicArcVelocity;
|
dst.MagicArcVelocity = tmp.MagicArcVelocity;
|
||||||
|
dst.MissileArcClearance = tmp.MissileArcClearance >= 0f ? Math.Min(tmp.MissileArcClearance, 3f) : 0.5f;
|
||||||
|
dst.LosDebugLog = tmp.LosDebugLog;
|
||||||
dst.EnableFPSLimit = tmp.EnableFPSLimit;
|
dst.EnableFPSLimit = tmp.EnableFPSLimit;
|
||||||
dst.TargetFPSFocused = tmp.TargetFPSFocused;
|
dst.TargetFPSFocused = tmp.TargetFPSFocused;
|
||||||
dst.TargetFPSBackground = tmp.TargetFPSBackground;
|
dst.TargetFPSBackground = tmp.TargetFPSBackground;
|
||||||
|
|
@ -1453,6 +1508,15 @@ internal sealed class LegacyDashboardRenderer
|
||||||
dst.EnableManaTapping = tmp.EnableManaTapping;
|
dst.EnableManaTapping = tmp.EnableManaTapping;
|
||||||
dst.ManaTapMinMana = tmp.ManaTapMinMana;
|
dst.ManaTapMinMana = tmp.ManaTapMinMana;
|
||||||
dst.ManaStoneKeepCount = tmp.ManaStoneKeepCount;
|
dst.ManaStoneKeepCount = tmp.ManaStoneKeepCount;
|
||||||
|
dst.AutoVendorEnabled = tmp.AutoVendorEnabled;
|
||||||
|
dst.AutoVendorEnableBuying = tmp.AutoVendorEnableBuying;
|
||||||
|
dst.AutoVendorEnableSelling = tmp.AutoVendorEnableSelling;
|
||||||
|
dst.AutoVendorTestMode = tmp.AutoVendorTestMode;
|
||||||
|
dst.AutoVendorThink = tmp.AutoVendorThink;
|
||||||
|
dst.AutoVendorShowMerchantInfo = tmp.AutoVendorShowMerchantInfo;
|
||||||
|
dst.AutoVendorOnlyFromMainPack = tmp.AutoVendorOnlyFromMainPack;
|
||||||
|
dst.AutoVendorTries = tmp.AutoVendorTries;
|
||||||
|
dst.AutoVendorTriesTime = tmp.AutoVendorTriesTime;
|
||||||
dst.MetaDebug = tmp.MetaDebug;
|
dst.MetaDebug = tmp.MetaDebug;
|
||||||
dst.StartMacroOnLogin = tmp.StartMacroOnLogin;
|
dst.StartMacroOnLogin = tmp.StartMacroOnLogin;
|
||||||
dst.PatrolOnLogin = tmp.PatrolOnLogin;
|
dst.PatrolOnLogin = tmp.PatrolOnLogin;
|
||||||
|
|
@ -2542,6 +2606,9 @@ internal sealed class LegacyDashboardRenderer
|
||||||
string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath)); sb.Append(',');
|
string.IsNullOrEmpty(_settings.CurrentNavPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentNavPath)); sb.Append(',');
|
||||||
AppendString(sb, "currentLootName",
|
AppendString(sb, "currentLootName",
|
||||||
string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath)); sb.Append(',');
|
string.IsNullOrEmpty(_settings.CurrentLootPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentLootPath)); sb.Append(',');
|
||||||
|
// Full paths for the dashboard's Edit (✎) button, which opens the Loot Editor.
|
||||||
|
AppendString(sb, "currentLootPath", _settings.CurrentLootPath ?? string.Empty); sb.Append(',');
|
||||||
|
AppendString(sb, "vendorProfilePath", _vendorProfilePath?.Invoke() ?? string.Empty); sb.Append(',');
|
||||||
AppendString(sb, "currentMetaName",
|
AppendString(sb, "currentMetaName",
|
||||||
string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath)); sb.Append(',');
|
string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath)); sb.Append(',');
|
||||||
AppendInt(sb, "selectedNavIdx", _selectedNavIdx); sb.Append(',');
|
AppendInt(sb, "selectedNavIdx", _selectedNavIdx); sb.Append(',');
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,7 @@ public sealed class LegacyUiSettings
|
||||||
public float NavDeadZone = 4f;
|
public float NavDeadZone = 4f;
|
||||||
public float NavSweepMult = 2.5f;
|
public float NavSweepMult = 2.5f;
|
||||||
public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off)
|
public float NavLookaheadYards = 4.0f; // distance to start blending the aim point toward the next waypoint (0 = off)
|
||||||
|
public float NavShortcutYards = 1.0f; // on arrival, skip waypoints only while the straight run to a later one stays within this of every skipped point (0 = visit every point)
|
||||||
public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate
|
public float NavTurnRateDegPerSec = 270f; // mode 0 (heading servo) max turn rate
|
||||||
public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate)
|
public float NavTier1TurnSpeed = 3.0f; // mode 1 (CM_Movement) DoMovement turn-command speed (magnitude of CMotionInterp turn_speed; 1.0 = native keyboard rate)
|
||||||
public float PostPortalDelaySec = 4.0f;
|
public float PostPortalDelaySec = 4.0f;
|
||||||
|
|
@ -149,6 +150,13 @@ public sealed class LegacyUiSettings
|
||||||
/// landing.
|
/// landing.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int RebuffSecondsRemaining = 300;
|
public int RebuffSecondsRemaining = 300;
|
||||||
|
/// <summary>
|
||||||
|
/// When a buff falls under RebuffSecondsRemaining, also refresh every other buff
|
||||||
|
/// with less than this many seconds left, so they land together instead of each
|
||||||
|
/// interrupting the fight on its own. Buffs with more time are left alone. At or
|
||||||
|
/// below RebuffSecondsRemaining only the expiring buff is recast.
|
||||||
|
/// </summary>
|
||||||
|
public int RebuffTopOffSecondsRemaining = 1200;
|
||||||
public bool StartMacroOnLogin;
|
public bool StartMacroOnLogin;
|
||||||
public bool PatrolOnLogin;
|
public bool PatrolOnLogin;
|
||||||
|
|
||||||
|
|
@ -225,6 +233,20 @@ public sealed class LegacyUiSettings
|
||||||
public float CrossbowArcVelocity = 40.0f;
|
public float CrossbowArcVelocity = 40.0f;
|
||||||
public float AtlatlArcVelocity = 22.0f;
|
public float AtlatlArcVelocity = 22.0f;
|
||||||
public float MagicArcVelocity = 25.0f;
|
public float MagicArcVelocity = 25.0f;
|
||||||
|
/// <summary>
|
||||||
|
/// Extra headroom (meters) a missile's arc must have at mid-flight for LoS to pass,
|
||||||
|
/// on top of the modelled flight path (launch speed above, AC gravity 9.8). Covers
|
||||||
|
/// what the model can't know exactly: launch height, the real launch speed, the
|
||||||
|
/// projectile's size. Raise it if shots still hit ceilings, lower it if targets
|
||||||
|
/// under a ceiling the arrows clear are skipped. Only used with UseArcs.
|
||||||
|
/// </summary>
|
||||||
|
public float MissileArcClearance = 0.5f;
|
||||||
|
/// <summary>
|
||||||
|
/// Log each in-range target's LoS verdict (straight line / arc, how high the arc
|
||||||
|
/// rises, where it hits) and the missile weapon's known launch speed. For tuning
|
||||||
|
/// the arc settings; off by default (a few lines a second in a crowd).
|
||||||
|
/// </summary>
|
||||||
|
public bool LosDebugLog;
|
||||||
|
|
||||||
public bool EnableFPSLimit = true;
|
public bool EnableFPSLimit = true;
|
||||||
public int TargetFPSFocused = 60;
|
public int TargetFPSFocused = 60;
|
||||||
|
|
@ -256,6 +278,23 @@ public sealed class LegacyUiSettings
|
||||||
public int ManaTapMinMana = 2500;
|
public int ManaTapMinMana = 2500;
|
||||||
public int ManaStoneKeepCount = 5;
|
public int ManaStoneKeepCount = 5;
|
||||||
|
|
||||||
|
// ── AutoVendor (UtilityBelt AutoVendor; /ub autovendor, /ub vendor) ────────
|
||||||
|
/// <summary>Run AutoVendor when a vendor opens (and allow /ub autovendor). UB defaults this on;
|
||||||
|
/// RynthAi defaults it off because the plugin auto-updates and selling can't be undone.</summary>
|
||||||
|
public bool AutoVendorEnabled = false;
|
||||||
|
public bool AutoVendorEnableBuying = true;
|
||||||
|
public bool AutoVendorEnableSelling = true;
|
||||||
|
/// <summary>Only print what would be bought and sold. On by default in RynthAi (UB: off).</summary>
|
||||||
|
public bool AutoVendorTestMode = true;
|
||||||
|
/// <summary>Send "AutoVendor finished: ..." (and fatal/failed lines) as a /tell to yourself, for metas.</summary>
|
||||||
|
public bool AutoVendorThink = false;
|
||||||
|
public bool AutoVendorShowMerchantInfo = true;
|
||||||
|
public bool AutoVendorOnlyFromMainPack = false;
|
||||||
|
/// <summary>Attempts to open a vendor on /ub vendor open[p].</summary>
|
||||||
|
public int AutoVendorTries = 4;
|
||||||
|
/// <summary>Milliseconds between /ub vendor open attempts.</summary>
|
||||||
|
public int AutoVendorTriesTime = 5000;
|
||||||
|
|
||||||
public List<MonsterRule> MonsterRules { get; set; } = new();
|
public List<MonsterRule> MonsterRules { get; set; } = new();
|
||||||
public List<ItemRule> ItemRules { get; set; } = new();
|
public List<ItemRule> ItemRules { get; set; } = new();
|
||||||
public List<ConsumableRule> ConsumableRules { get; set; } = new();
|
public List<ConsumableRule> ConsumableRules { get; set; } = new();
|
||||||
|
|
@ -372,7 +411,7 @@ public sealed class LegacyUiSettings
|
||||||
public readonly string[] AdvancedTabs =
|
public readonly string[] AdvancedTabs =
|
||||||
{
|
{
|
||||||
"Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat",
|
"Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat",
|
||||||
"Ranges", "Navigation", "Buffing", "Crafting", "Looting"
|
"Ranges", "Navigation", "Buffing", "Crafting", "Looting", "Vendoring"
|
||||||
};
|
};
|
||||||
|
|
||||||
[JsonIgnore]
|
[JsonIgnore]
|
||||||
|
|
@ -571,9 +610,13 @@ public sealed class SettingsBridgePayload
|
||||||
public float CrossbowArcVelocity { get; set; }
|
public float CrossbowArcVelocity { get; set; }
|
||||||
public float AtlatlArcVelocity { get; set; }
|
public float AtlatlArcVelocity { get; set; }
|
||||||
public float MagicArcVelocity { get; set; }
|
public float MagicArcVelocity { get; set; }
|
||||||
|
public float MissileArcClearance { get; set; } = 0.5f; // absent in older payloads
|
||||||
|
public bool LosDebugLog { get; set; }
|
||||||
public int BlacklistAttempts { get; set; }
|
public int BlacklistAttempts { get; set; }
|
||||||
public int BlacklistTimeoutSec { get; set; }
|
public int BlacklistTimeoutSec { get; set; }
|
||||||
public int BlacklistCastSettleMs { get; set; }
|
// -1 = absent from the payload: the overlay's Settings panel didn't send it, and
|
||||||
|
// applying the missing 0 made every panel click zero the setting (2026-09-27).
|
||||||
|
public int BlacklistCastSettleMs { get; set; } = -1;
|
||||||
public int TargetNoProgressTimeoutSec { get; set; }
|
public int TargetNoProgressTimeoutSec { get; set; }
|
||||||
public int GiveQueueIntervalMs { get; set; }
|
public int GiveQueueIntervalMs { get; set; }
|
||||||
|
|
||||||
|
|
@ -614,7 +657,7 @@ public sealed class SettingsBridgePayload
|
||||||
|
|
||||||
// Ranges
|
// Ranges
|
||||||
public int MonsterRange { get; set; }
|
public int MonsterRange { get; set; }
|
||||||
public int MonsterDisengageRange { get; set; }
|
public int MonsterDisengageRange { get; set; } = -1; // -1 = absent, see BlacklistCastSettleMs
|
||||||
public int RingRange { get; set; }
|
public int RingRange { get; set; }
|
||||||
public int ApproachRange { get; set; }
|
public int ApproachRange { get; set; }
|
||||||
public double CorpseApproachRangeMax { get; set; }
|
public double CorpseApproachRangeMax { get; set; }
|
||||||
|
|
@ -637,6 +680,7 @@ public sealed class SettingsBridgePayload
|
||||||
public float NavDeadZone { get; set; }
|
public float NavDeadZone { get; set; }
|
||||||
public float NavSweepMult { get; set; }
|
public float NavSweepMult { get; set; }
|
||||||
public float NavLookaheadYards { get; set; }
|
public float NavLookaheadYards { get; set; }
|
||||||
|
public float NavShortcutYards { get; set; }
|
||||||
public float NavTurnRateDegPerSec { get; set; }
|
public float NavTurnRateDegPerSec { get; set; }
|
||||||
public float NavTier1TurnSpeed { get; set; }
|
public float NavTier1TurnSpeed { get; set; }
|
||||||
public float PostPortalDelaySec { get; set; }
|
public float PostPortalDelaySec { get; set; }
|
||||||
|
|
@ -651,6 +695,7 @@ public sealed class SettingsBridgePayload
|
||||||
public bool EnableBuffing { get; set; }
|
public bool EnableBuffing { get; set; }
|
||||||
public bool RebuffWhenIdle { get; set; }
|
public bool RebuffWhenIdle { get; set; }
|
||||||
public int RebuffSecondsRemaining { get; set; }
|
public int RebuffSecondsRemaining { get; set; }
|
||||||
|
public int RebuffTopOffSecondsRemaining { get; set; } = 1200; // absent in older files
|
||||||
public int BuffMinSkillLevelTier1 { get; set; }
|
public int BuffMinSkillLevelTier1 { get; set; }
|
||||||
public int BuffMinSkillLevelTier2 { get; set; }
|
public int BuffMinSkillLevelTier2 { get; set; }
|
||||||
public int BuffMinSkillLevelTier3 { get; set; }
|
public int BuffMinSkillLevelTier3 { get; set; }
|
||||||
|
|
@ -691,6 +736,17 @@ public sealed class SettingsBridgePayload
|
||||||
public int SalvageSalvageDelayMs { get; set; }
|
public int SalvageSalvageDelayMs { get; set; }
|
||||||
public int SalvageResultDelayFirstMs { get; set; }
|
public int SalvageResultDelayFirstMs { get; set; }
|
||||||
public int SalvageResultDelayFastMs { get; set; }
|
public int SalvageResultDelayFastMs { get; set; }
|
||||||
|
// AutoVendor. Nullable so a settings panel that doesn't know these fields yet
|
||||||
|
// leaves the character's values alone instead of resetting them.
|
||||||
|
public bool? AutoVendorEnabled { get; set; }
|
||||||
|
public bool? AutoVendorEnableBuying { get; set; }
|
||||||
|
public bool? AutoVendorEnableSelling { get; set; }
|
||||||
|
public bool? AutoVendorTestMode { get; set; }
|
||||||
|
public bool? AutoVendorThink { get; set; }
|
||||||
|
public bool? AutoVendorShowMerchantInfo { get; set; }
|
||||||
|
public bool? AutoVendorOnlyFromMainPack { get; set; }
|
||||||
|
public int? AutoVendorTries { get; set; }
|
||||||
|
public int? AutoVendorTriesTime { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum MetaConditionType
|
public enum MetaConditionType
|
||||||
|
|
|
||||||
|
|
@ -158,6 +158,14 @@ public static class VTankLootEvaluator
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One condition on its own, same semantics as inside <see cref="Match(VTankLootRule, WorldObject?, VTankLootContext?)"/>.
|
||||||
|
/// AutoVendor judges conditions one at a time so it can tell "no" from "can't tell".
|
||||||
|
/// Throws on a malformed data line or an unsupported node type (the caller decides what that means).
|
||||||
|
/// </summary>
|
||||||
|
public static bool MatchCondition(VTankLootCondition cond, WorldObject item, VTankLootContext? ctx)
|
||||||
|
=> Match(cond, item, unchecked((uint)item.Id), ctx);
|
||||||
|
|
||||||
private static bool Match(VTankLootCondition cond, WorldObject item, uint itemId, VTankLootContext? ctx)
|
private static bool Match(VTankLootCondition cond, WorldObject item, uint itemId, VTankLootContext? ctx)
|
||||||
{
|
{
|
||||||
var d = cond.DataLines;
|
var d = cond.DataLines;
|
||||||
|
|
|
||||||
|
|
@ -209,6 +209,16 @@ public sealed partial class RynthAiPlugin
|
||||||
["manastonelootcount"] = "ManaStoneKeepCount",
|
["manastonelootcount"] = "ManaStoneKeepCount",
|
||||||
["rebuftimeremainingseconds"] = "RebuffSecondsRemaining",
|
["rebuftimeremainingseconds"] = "RebuffSecondsRemaining",
|
||||||
["navclosestoprange"] = "NavCloseStopRange",
|
["navclosestoprange"] = "NavCloseStopRange",
|
||||||
|
// UtilityBelt AutoVendor options (/ub opt set AutoVendor.TestMode true)
|
||||||
|
["autovendor.enabled"] = "AutoVendorEnabled",
|
||||||
|
["autovendor.enablebuying"] = "AutoVendorEnableBuying",
|
||||||
|
["autovendor.enableselling"] = "AutoVendorEnableSelling",
|
||||||
|
["autovendor.testmode"] = "AutoVendorTestMode",
|
||||||
|
["autovendor.think"] = "AutoVendorThink",
|
||||||
|
["autovendor.showmerchantinfo"] = "AutoVendorShowMerchantInfo",
|
||||||
|
["autovendor.onlyfrommainpack"] = "AutoVendorOnlyFromMainPack",
|
||||||
|
["autovendor.tries"] = "AutoVendorTries",
|
||||||
|
["autovendor.triestime"] = "AutoVendorTriesTime",
|
||||||
};
|
};
|
||||||
|
|
||||||
private string? GetOptionValue(string optName)
|
private string? GetOptionValue(string optName)
|
||||||
|
|
|
||||||
|
|
@ -3204,6 +3204,13 @@ internal sealed class ExpressionEngine
|
||||||
["EnableLooting"] = (() => B(s.EnableLooting), v => s.EnableLooting = ToDouble(v) != 0),
|
["EnableLooting"] = (() => B(s.EnableLooting), v => s.EnableLooting = ToDouble(v) != 0),
|
||||||
["EnableMeta"] = (() => B(s.EnableMeta), v => s.EnableMeta = ToDouble(v) != 0),
|
["EnableMeta"] = (() => B(s.EnableMeta), v => s.EnableMeta = ToDouble(v) != 0),
|
||||||
["EnableRaycasting"] = (() => B(s.EnableRaycasting), v => s.EnableRaycasting = ToDouble(v) != 0),
|
["EnableRaycasting"] = (() => B(s.EnableRaycasting), v => s.EnableRaycasting = ToDouble(v) != 0),
|
||||||
|
["UseArcs"] = (() => B(s.UseArcs), v => s.UseArcs = ToDouble(v) != 0),
|
||||||
|
["LosDebugLog"] = (() => B(s.LosDebugLog), v => s.LosDebugLog = ToDouble(v) != 0),
|
||||||
|
["BowArcVelocity"] = (() => F(s.BowArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.BowArcVelocity = Math.Clamp(f, 10f, 60f); }),
|
||||||
|
["CrossbowArcVelocity"] = (() => F(s.CrossbowArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.CrossbowArcVelocity = Math.Clamp(f, 10f, 80f); }),
|
||||||
|
["AtlatlArcVelocity"] = (() => F(s.AtlatlArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.AtlatlArcVelocity = Math.Clamp(f, 10f, 60f); }),
|
||||||
|
["MagicArcVelocity"] = (() => F(s.MagicArcVelocity), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.MagicArcVelocity = Math.Clamp(f, 10f, 60f); }),
|
||||||
|
["MissileArcClearance"] = (() => F(s.MissileArcClearance), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f) && float.IsFinite(f)) s.MissileArcClearance = Math.Clamp(f, 0f, 3f); }),
|
||||||
["EnableAutostack"] = (() => B(s.EnableAutostack), v => s.EnableAutostack = ToDouble(v) != 0),
|
["EnableAutostack"] = (() => B(s.EnableAutostack), v => s.EnableAutostack = ToDouble(v) != 0),
|
||||||
["EnableAutocram"] = (() => B(s.EnableAutocram), v => s.EnableAutocram = ToDouble(v) != 0),
|
["EnableAutocram"] = (() => B(s.EnableAutocram), v => s.EnableAutocram = ToDouble(v) != 0),
|
||||||
["EnableCombineSalvage"]= (() => B(s.EnableCombineSalvage),v => s.EnableCombineSalvage= ToDouble(v) != 0),
|
["EnableCombineSalvage"]= (() => B(s.EnableCombineSalvage),v => s.EnableCombineSalvage= ToDouble(v) != 0),
|
||||||
|
|
@ -3236,7 +3243,19 @@ 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; }),
|
["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; }),
|
["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; }),
|
["RebuffSecondsRemaining"] = (() => I(s.RebuffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffSecondsRemaining = i; }),
|
||||||
|
["RebuffTopOffSecondsRemaining"] = (() => I(s.RebuffTopOffSecondsRemaining), v => { if (int.TryParse(v, out int i)) s.RebuffTopOffSecondsRemaining = i; }),
|
||||||
|
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
|
||||||
|
["AutoVendorEnabled"] = (() => B(s.AutoVendorEnabled), v => s.AutoVendorEnabled = ToDouble(v) != 0),
|
||||||
|
["AutoVendorEnableBuying"] = (() => B(s.AutoVendorEnableBuying), v => s.AutoVendorEnableBuying = ToDouble(v) != 0),
|
||||||
|
["AutoVendorEnableSelling"] = (() => B(s.AutoVendorEnableSelling), v => s.AutoVendorEnableSelling = ToDouble(v) != 0),
|
||||||
|
["AutoVendorTestMode"] = (() => B(s.AutoVendorTestMode), v => s.AutoVendorTestMode = ToDouble(v) != 0),
|
||||||
|
["AutoVendorThink"] = (() => B(s.AutoVendorThink), v => s.AutoVendorThink = ToDouble(v) != 0),
|
||||||
|
["AutoVendorShowMerchantInfo"] = (() => B(s.AutoVendorShowMerchantInfo), v => s.AutoVendorShowMerchantInfo = ToDouble(v) != 0),
|
||||||
|
["AutoVendorOnlyFromMainPack"] = (() => B(s.AutoVendorOnlyFromMainPack), v => s.AutoVendorOnlyFromMainPack = ToDouble(v) != 0),
|
||||||
|
["AutoVendorTries"] = (() => I(s.AutoVendorTries), v => { if (int.TryParse(v, out int i)) s.AutoVendorTries = Math.Clamp(i, 1, 20); }),
|
||||||
|
["AutoVendorTriesTime"] = (() => I(s.AutoVendorTriesTime), v => { if (int.TryParse(v, out int i)) s.AutoVendorTriesTime = Math.Clamp(i, 500, 30000); }),
|
||||||
["NavCloseStopRange"] = (() => F(s.NavCloseStopRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavCloseStopRange = f; }),
|
["NavCloseStopRange"] = (() => F(s.NavCloseStopRange), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavCloseStopRange = f; }),
|
||||||
|
["NavShortcutYards"] = (() => F(s.NavShortcutYards), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavShortcutYards = Math.Clamp(f, 0f, 10f); }),
|
||||||
["MaxMonRange"] = (() => D(s.MaxMonRange), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.MaxMonRange = d; }),
|
["MaxMonRange"] = (() => D(s.MaxMonRange), v => { if (double.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out double d)) s.MaxMonRange = d; }),
|
||||||
["NavRingThickness"] = (() => F(s.NavRingThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavRingThickness = f; }),
|
["NavRingThickness"] = (() => F(s.NavRingThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavRingThickness = f; }),
|
||||||
["NavLineThickness"] = (() => F(s.NavLineThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavLineThickness = f; }),
|
["NavLineThickness"] = (() => F(s.NavLineThickness), v => { if (float.TryParse(v, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out float f)) s.NavLineThickness = f; }),
|
||||||
|
|
|
||||||
|
|
@ -121,6 +121,11 @@ internal sealed class NavigationEngine
|
||||||
// waypoint). Tunable in Advanced ▸ Navigation ▸ Steering.
|
// waypoint). Tunable in Advanced ▸ Navigation ▸ Steering.
|
||||||
private double LookaheadYards => Math.Max(0.0, _settings.NavLookaheadYards);
|
private double LookaheadYards => Math.Max(0.0, _settings.NavLookaheadYards);
|
||||||
|
|
||||||
|
// Straight-line shortcut on arrival: skip waypoints only while the straight run
|
||||||
|
// to a later one stays within this many yards of every waypoint skipped.
|
||||||
|
// 0 = off (visit every waypoint). Tunable in Advanced ▸ Navigation ▸ Steering.
|
||||||
|
private double ShortcutYards => Math.Max(0.0, _settings.NavShortcutYards);
|
||||||
|
|
||||||
// Mode 0 heading servo: cap the heading change we command per tick so the
|
// Mode 0 heading servo: cap the heading change we command per tick so the
|
||||||
// turn is smooth and never overshoots (deadbeat). Floored at 10°/s so a
|
// turn is smooth and never overshoots (deadbeat). Floored at 10°/s so a
|
||||||
// stray 0 from an old config can't freeze turning.
|
// stray 0 from an old config can't freeze turning.
|
||||||
|
|
@ -423,7 +428,16 @@ internal sealed class NavigationEngine
|
||||||
{
|
{
|
||||||
_inPause = false;
|
_inPause = false;
|
||||||
_inRecovery = false;
|
_inRecovery = false;
|
||||||
_linearDir = 1;
|
// _linearDir is NOT reset here. Stop() runs on every pause (combat, loot,
|
||||||
|
// buff, door), and resetting it turned a Linear route around after each
|
||||||
|
// fight on the way back: the bot re-walked the far leg to the end instead of
|
||||||
|
// finishing the return. A new route resets it (route swap / ResetRouteState).
|
||||||
|
//
|
||||||
|
// Combat, looting, buffing and doors stop nav and move the character. The
|
||||||
|
// closest-approach reading from before the pause says nothing about where we
|
||||||
|
// are now; kept, the first tick back reads the displacement as a sweep-pass
|
||||||
|
// and advances past a waypoint that was never reached.
|
||||||
|
_prevDist = double.MaxValue;
|
||||||
_stopRequestedAt = long.MaxValue;
|
_stopRequestedAt = long.MaxValue;
|
||||||
ResetPortalState();
|
ResetPortalState();
|
||||||
_host.SetAutoRun(false);
|
_host.SetAutoRun(false);
|
||||||
|
|
@ -436,6 +450,7 @@ internal sealed class NavigationEngine
|
||||||
public void ResetRouteState()
|
public void ResetRouteState()
|
||||||
{
|
{
|
||||||
Stop();
|
Stop();
|
||||||
|
_linearDir = 1;
|
||||||
_stuckCount = 0;
|
_stuckCount = 0;
|
||||||
_recoveryKind = RecoveryKind.Jump;
|
_recoveryKind = RecoveryKind.Jump;
|
||||||
_prevDist = double.MaxValue;
|
_prevDist = double.MaxValue;
|
||||||
|
|
@ -871,36 +886,59 @@ internal sealed class NavigationEngine
|
||||||
if (skipped > 0)
|
if (skipped > 0)
|
||||||
_host.Log($"Nav: skipped {skipped} dense waypoint(s) within {arrival:F1}yd → now on [{_settings.ActiveNavIndex}]");
|
_host.Log($"Nav: skipped {skipped} dense waypoint(s) within {arrival:F1}yd → now on [{_settings.ActiveNavIndex}]");
|
||||||
|
|
||||||
// Collinear-waypoint skip: if current target lies nearly on the straight
|
// Straight-line shortcut: bypass waypoints that the straight run from here
|
||||||
// line from the player to the waypoint after it, skip it. Handles straight
|
// to a later waypoint already passes close to (straight corridors, recorded
|
||||||
// dungeon corridors and outdoor paths with too many recorded points.
|
// routes with many points on a line). EVERY bypassed waypoint must lie
|
||||||
const double CollinearThreshYards = 2.0;
|
// within ShortcutYards of the segment player→new target.
|
||||||
const int ColSkipBudget = 64;
|
//
|
||||||
int colSkipped = 0;
|
// This used to test each waypoint only against the line to its immediate
|
||||||
while (colSkipped < ColSkipBudget && IndexValid(_settings.ActiveNavIndex, route))
|
// successor. A point is never farther than one spacing from the line to the
|
||||||
|
// next point, so on a player-made route with 1-3yd spacing the test passed
|
||||||
|
// step after step around curves and corners: one arrival jumped up to 64
|
||||||
|
// waypoints and aimed a straight line 15-50yd off the route, into walls,
|
||||||
|
// where the stuck ladder then skipped more (2026-09-27). Replaying every
|
||||||
|
// arrival of 518 real VTank routes: 5% cut a corner by >3yd, worst 49.6yd.
|
||||||
|
// The cumulative test caps the deviation at ShortcutYards by construction.
|
||||||
|
double tolerance = ShortcutYards;
|
||||||
|
if (tolerance > 0.0)
|
||||||
{
|
{
|
||||||
var curr = route.Points[_settings.ActiveNavIndex];
|
const int ShortcutBudget = 64;
|
||||||
|
Span<int> bypassed = stackalloc int[ShortcutBudget];
|
||||||
|
int count = 0;
|
||||||
|
double worst = 0.0;
|
||||||
|
while (count < ShortcutBudget && IndexValid(_settings.ActiveNavIndex, route))
|
||||||
|
{
|
||||||
|
int ci = _settings.ActiveNavIndex;
|
||||||
|
var curr = route.Points[ci];
|
||||||
if (curr.Type != NavPointType.Point) break;
|
if (curr.Type != NavPointType.Point) break;
|
||||||
|
|
||||||
int ni = PeekNext(_settings.ActiveNavIndex, route);
|
int ni = PeekNext(ci, route);
|
||||||
if (ni < 0 || ni == _settings.ActiveNavIndex) break;
|
if (ni < 0 || ni == ci) break;
|
||||||
var next = route.Points[ni];
|
var next = route.Points[ni];
|
||||||
if (next.Type != NavPointType.Point) break;
|
if (next.Type != NavPointType.Point) break;
|
||||||
|
|
||||||
// Only skip if next is farther from player than curr (don't skip past a turn)
|
// Only shortcut forward: the new target must be farther from the
|
||||||
|
// player than the one it replaces (don't skip past a turn back).
|
||||||
double dCurrNS = curr.NS - curNs, dCurrEW = curr.EW - curEw;
|
double dCurrNS = curr.NS - curNs, dCurrEW = curr.EW - curEw;
|
||||||
double dNextNS = next.NS - curNs, dNextEW = next.EW - curEw;
|
double dNextNS = next.NS - curNs, dNextEW = next.EW - curEw;
|
||||||
if (dNextNS * dNextNS + dNextEW * dNextEW <= dCurrNS * dCurrNS + dCurrEW * dCurrEW) break;
|
if (dNextNS * dNextNS + dNextEW * dNextEW <= dCurrNS * dCurrNS + dCurrEW * dCurrEW) break;
|
||||||
|
|
||||||
if (CrossDistYards(curNs, curEw, curr.NS, curr.EW, next.NS, next.EW) >= CollinearThreshYards) break;
|
double off = SegmentDistYards(curr.NS, curr.EW, curNs, curEw, next.NS, next.EW);
|
||||||
|
for (int b = 0; b < count && off < tolerance; b++)
|
||||||
int beforeCol = _settings.ActiveNavIndex;
|
{
|
||||||
AdvanceOneIndex(route);
|
var bp = route.Points[bypassed[b]];
|
||||||
if (_settings.ActiveNavIndex == beforeCol) break;
|
off = Math.Max(off, SegmentDistYards(bp.NS, bp.EW, curNs, curEw, next.NS, next.EW));
|
||||||
colSkipped++;
|
}
|
||||||
|
if (off >= tolerance) break;
|
||||||
|
|
||||||
|
AdvanceOneIndex(route);
|
||||||
|
if (_settings.ActiveNavIndex == ci) break;
|
||||||
|
bypassed[count++] = ci;
|
||||||
|
if (off > worst) worst = off;
|
||||||
|
}
|
||||||
|
if (count > 0)
|
||||||
|
_host.Log($"Nav: shortcut past {count} waypoint(s), ≤{worst:F1}yd off route → now on [{_settings.ActiveNavIndex}]");
|
||||||
}
|
}
|
||||||
if (colSkipped > 0)
|
|
||||||
_host.Log($"Nav: skipped {colSkipped} collinear waypoint(s) → now on [{_settings.ActiveNavIndex}]");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_settings.ActiveNavIndex != oldIdx && IndexValid(_settings.ActiveNavIndex, route))
|
if (_settings.ActiveNavIndex != oldIdx && IndexValid(_settings.ActiveNavIndex, route))
|
||||||
|
|
@ -1734,13 +1772,14 @@ internal sealed class NavigationEngine
|
||||||
|
|
||||||
private static double Lerp(double a, double b, double t) => a + (b - a) * t;
|
private static double Lerp(double a, double b, double t) => a + (b - a) * t;
|
||||||
|
|
||||||
// Perpendicular distance (yards) from point B to the infinite line through A and C.
|
// Distance (yards) from point P to the segment A→B.
|
||||||
private static double CrossDistYards(double aNS, double aEW, double bNS, double bEW, double cNS, double cEW)
|
private static double SegmentDistYards(double pNS, double pEW, double aNS, double aEW, double bNS, double bEW)
|
||||||
{
|
{
|
||||||
double acNS = cNS - aNS, acEW = cEW - aEW;
|
|
||||||
double acLen = Math.Sqrt(acNS * acNS + acEW * acEW);
|
|
||||||
if (acLen < 1e-9) return 0.0;
|
|
||||||
double abNS = bNS - aNS, abEW = bEW - aEW;
|
double abNS = bNS - aNS, abEW = bEW - aEW;
|
||||||
return Math.Abs(abNS * acEW - abEW * acNS) / acLen * 240.0;
|
double len2 = abNS * abNS + abEW * abEW;
|
||||||
|
double t = len2 < 1e-18 ? 0.0
|
||||||
|
: Math.Clamp(((pNS - aNS) * abNS + (pEW - aEW) * abEW) / len2, 0.0, 1.0);
|
||||||
|
double dNS = pNS - (aNS + t * abNS), dEW = pEW - (aEW + t * abEW);
|
||||||
|
return Math.Sqrt(dNS * dNS + dEW * dEW) * 240.0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
182
Plugins/RynthCore.Plugin.RynthAi/Raycasting/MissileBallistics.cs
Normal file
182
Plugins/RynthCore.Plugin.RynthAi/Raycasting/MissileBallistics.cs
Normal file
|
|
@ -0,0 +1,182 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The flight path of an AC missile (arrow, bolt, dart), as pure math: no host, no
|
||||||
|
/// geometry, no allocation. Kept dependency-free so Tools/RynthCore.MissileArcTests
|
||||||
|
/// compiles it directly.
|
||||||
|
///
|
||||||
|
/// The server launches every missile at the weapon's fixed speed on the LOW solution of
|
||||||
|
/// the ballistic arc to the aim point, under gravity (ACE GetProjectileVelocity →
|
||||||
|
/// Trajectory.solve_ballistic_arc, first solution; PhysicsGlobals.Gravity = 9.8). So the
|
||||||
|
/// arc height is not a constant: it grows with distance and shrinks with launch speed.
|
||||||
|
/// At 5 m a bow shot is a straight line; at 40 m with 25 m/s it rises about 3.5 m above
|
||||||
|
/// the launch point, which is enough to hit a dungeon ceiling the straight line clears.
|
||||||
|
///
|
||||||
|
/// Units are meters, Z up. "t" is the horizontal fraction of the shot, 0 at the launch
|
||||||
|
/// point and 1 at the aim point.
|
||||||
|
/// </summary>
|
||||||
|
public readonly struct MissileArc
|
||||||
|
{
|
||||||
|
/// <summary>Launch point.</summary>
|
||||||
|
public readonly float OX, OY, OZ;
|
||||||
|
/// <summary>Unit horizontal direction from launch point to aim point.</summary>
|
||||||
|
public readonly float DirX, DirY;
|
||||||
|
/// <summary>Horizontal distance from launch point to aim point.</summary>
|
||||||
|
public readonly float HorizDist;
|
||||||
|
/// <summary>Aim point Z minus launch point Z.</summary>
|
||||||
|
public readonly float Rise;
|
||||||
|
/// <summary>Tangent of the launch elevation (low solution).</summary>
|
||||||
|
public readonly float TanTheta;
|
||||||
|
/// <summary>Curvature: height(x) = x·TanTheta − K·x², K = g(1+tan²θ)/(2v²).</summary>
|
||||||
|
public readonly float K;
|
||||||
|
/// <summary>False when the aim point is out of reach at this launch speed.</summary>
|
||||||
|
public readonly bool Valid;
|
||||||
|
/// <summary>True for a (near) vertical shot, flown as a straight line.</summary>
|
||||||
|
public readonly bool Vertical;
|
||||||
|
|
||||||
|
internal MissileArc(float ox, float oy, float oz, float dirX, float dirY, float horizDist,
|
||||||
|
float rise, float tanTheta, float k, bool valid, bool vertical)
|
||||||
|
{
|
||||||
|
OX = ox; OY = oy; OZ = oz;
|
||||||
|
DirX = dirX; DirY = dirY;
|
||||||
|
HorizDist = horizDist; Rise = rise;
|
||||||
|
TanTheta = tanTheta; K = k;
|
||||||
|
Valid = valid; Vertical = vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Height above the launch point at horizontal fraction t (no clearance).</summary>
|
||||||
|
public float HeightAt(float t)
|
||||||
|
{
|
||||||
|
if (!Valid) return 0f;
|
||||||
|
if (Vertical) return Rise * t;
|
||||||
|
float x = t * HorizDist;
|
||||||
|
return x * TanTheta - K * x * x;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The point at horizontal fraction t, raised by <paramref name="clearance"/> at
|
||||||
|
/// mid-flight (see <see cref="MissileBallistics.ClearanceBump"/>). The ends never
|
||||||
|
/// move: t=0 is the launch point and t=1 the aim point.
|
||||||
|
/// </summary>
|
||||||
|
public void PointAt(float t, float clearance, out float x, out float y, out float z)
|
||||||
|
{
|
||||||
|
float h = t * HorizDist;
|
||||||
|
x = OX + DirX * h;
|
||||||
|
y = OY + DirY * h;
|
||||||
|
z = OZ + HeightAt(t) + MissileBallistics.ClearanceBump(t, clearance);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// How far the arc rises above the straight line from launch point to aim point, at
|
||||||
|
/// its highest. This is the part a straight line-of-sight check never sees.
|
||||||
|
/// </summary>
|
||||||
|
public float MaxRiseAboveChord
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (!Valid || Vertical || HorizDist <= 0f || K <= 0f) return 0f;
|
||||||
|
// height(x) − Rise·x/d = x·(tanθ − Rise/d) − K·x². Its maximum is at
|
||||||
|
// x* = a/(2K), value a²/(4K), where a = tanθ − Rise/d.
|
||||||
|
float a = TanTheta - Rise / HorizDist;
|
||||||
|
if (a <= 0f) return 0f;
|
||||||
|
float xStar = a / (2f * K);
|
||||||
|
if (xStar >= HorizDist) xStar = HorizDist;
|
||||||
|
return a * xStar - K * xStar * xStar;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Highest point of the flight above the launch point (never below the ends).</summary>
|
||||||
|
public float ApexAboveLaunch
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (!Valid) return 0f;
|
||||||
|
if (Vertical) return Math.Max(0f, Rise);
|
||||||
|
if (K <= 0f) return Math.Max(0f, Rise);
|
||||||
|
float xApex = TanTheta / (2f * K);
|
||||||
|
float apex = xApex > 0f && xApex < HorizDist
|
||||||
|
? TanTheta * xApex - K * xApex * xApex
|
||||||
|
: 0f;
|
||||||
|
return Math.Max(apex, Math.Max(0f, Rise));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class MissileBallistics
|
||||||
|
{
|
||||||
|
/// <summary>AC's gravity (PhysicsGlobals.Gravity = -9.8).</summary>
|
||||||
|
public const float AcGravity = 9.8f;
|
||||||
|
|
||||||
|
/// <summary>Below this horizontal distance a shot is treated as vertical.</summary>
|
||||||
|
private const float VerticalEpsilon = 0.05f;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Solves the low ballistic arc from the launch point to the aim point at a fixed launch
|
||||||
|
/// speed. Out of reach (the speed can't carry that far or that high) gives Valid=false.
|
||||||
|
/// </summary>
|
||||||
|
public static MissileArc Solve(float ox, float oy, float oz,
|
||||||
|
float tx, float ty, float tz,
|
||||||
|
float speed, float gravity = AcGravity)
|
||||||
|
{
|
||||||
|
float dx = tx - ox, dy = ty - oy;
|
||||||
|
float rise = tz - oz;
|
||||||
|
float d = (float)Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
|
||||||
|
if (float.IsNaN(d) || float.IsNaN(rise) || speed <= 0f || gravity <= 0f)
|
||||||
|
return new MissileArc(ox, oy, oz, 0f, 0f, 0f, 0f, 0f, 0f, valid: false, vertical: false);
|
||||||
|
|
||||||
|
if (d < VerticalEpsilon)
|
||||||
|
return new MissileArc(ox, oy, oz, 0f, 0f, d, rise, 0f, 0f, valid: true, vertical: true);
|
||||||
|
|
||||||
|
// Low-angle solution of rise = d·tanθ − g·d²·(1+tan²θ)/(2v²):
|
||||||
|
// tanθ = (v² − √(v⁴ − g(g·d² + 2·rise·v²))) / (g·d)
|
||||||
|
double v2 = (double)speed * speed;
|
||||||
|
double disc = v2 * v2 - gravity * (gravity * (double)d * d + 2.0 * rise * v2);
|
||||||
|
if (disc < 0.0)
|
||||||
|
return new MissileArc(ox, oy, oz, dx / d, dy / d, d, rise, 0f, 0f, valid: false, vertical: false);
|
||||||
|
|
||||||
|
double tan = (v2 - Math.Sqrt(disc)) / (gravity * (double)d);
|
||||||
|
double k = gravity * (1.0 + tan * tan) / (2.0 * v2);
|
||||||
|
return new MissileArc(ox, oy, oz, dx / d, dy / d, d, rise, (float)tan, (float)k, valid: true, vertical: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extra height added to the tested path: <paramref name="clearance"/> at mid-flight,
|
||||||
|
/// tapering to zero at both ends (4t(1−t)), so the launch and aim points stay put. It
|
||||||
|
/// covers what the model can't know exactly: launch height, the real launch speed, the
|
||||||
|
/// projectile's own size.
|
||||||
|
/// </summary>
|
||||||
|
public static float ClearanceBump(float t, float clearance)
|
||||||
|
{
|
||||||
|
if (clearance <= 0f || t <= 0f || t >= 1f) return 0f;
|
||||||
|
return clearance * 4f * t * (1f - t);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Number of straight segments used to test an arc: about one per 2.5 m, 6 to 24.</summary>
|
||||||
|
public static int SegmentCount(float horizDist)
|
||||||
|
{
|
||||||
|
if (float.IsNaN(horizDist) || horizDist <= 0f) return 6;
|
||||||
|
int n = (int)Math.Ceiling(horizDist / 2.5f);
|
||||||
|
return Math.Clamp(n, 6, 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Highest Z the tested path reaches (arc plus clearance), sampled like the geometry
|
||||||
|
/// test samples it. Lets a caller compare the path against a known ceiling height.
|
||||||
|
/// </summary>
|
||||||
|
public static float MaxPathZ(in MissileArc arc, float clearance)
|
||||||
|
{
|
||||||
|
if (!arc.Valid) return float.NaN;
|
||||||
|
int n = SegmentCount(arc.HorizDist) * 4;
|
||||||
|
float best = Math.Max(arc.OZ, arc.OZ + arc.Rise);
|
||||||
|
for (int i = 1; i < n; i++)
|
||||||
|
{
|
||||||
|
arc.PointAt((float)i / n, clearance, out _, out _, out float z);
|
||||||
|
if (z > best) best = z;
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -224,6 +224,89 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||||
return false; // Arc clears all obstacles
|
return false; // Arc clears all obstacles
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>What <see cref="IsBallisticArcBlocked"/> found, for the LOS debug log and /ra lostest.</summary>
|
||||||
|
public struct ArcLosResult
|
||||||
|
{
|
||||||
|
public bool Blocked;
|
||||||
|
public bool OutOfReach; // the launch speed can't carry the shot that far / that high
|
||||||
|
public float Sag; // how far the arc rises above the straight line, at most (m)
|
||||||
|
public float Apex; // highest point of the flight above the launch point (m)
|
||||||
|
public float HitAlong; // horizontal distance from the shooter to the hit (m)
|
||||||
|
public float HitZ; // height of the hit above the launch point (m)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests the path a missile really flies: the low ballistic arc at the weapon's launch
|
||||||
|
/// speed (see <see cref="MissileBallistics"/>), raised by <paramref name="clearance"/>
|
||||||
|
/// at mid-flight. Unlike <see cref="IsArcPathBlocked"/> (the old flat-ground
|
||||||
|
/// approximation, kept for magic arcs), the arc passes exactly through the aim point
|
||||||
|
/// for any height difference. Floors and ceilings are part of the dungeon geometry, so
|
||||||
|
/// an arc that rises into a ceiling reports blocked. Out of reach counts as blocked.
|
||||||
|
/// Hits within 0.5 m of the shooter or 0.3 m of the target are ignored, as in the
|
||||||
|
/// straight-line test.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsBallisticArcBlocked(Vector3 origin, Vector3 target, float speed, float clearance,
|
||||||
|
List<BoundingVolume> geometry, out ArcLosResult result)
|
||||||
|
{
|
||||||
|
result = default;
|
||||||
|
if (float.IsNaN(origin.X) || float.IsNaN(origin.Y) || float.IsNaN(origin.Z) ||
|
||||||
|
float.IsNaN(target.X) || float.IsNaN(target.Y) || float.IsNaN(target.Z))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var arc = MissileBallistics.Solve(origin.X, origin.Y, origin.Z, target.X, target.Y, target.Z, speed);
|
||||||
|
result.Sag = arc.MaxRiseAboveChord;
|
||||||
|
result.Apex = arc.ApexAboveLaunch;
|
||||||
|
if (!arc.Valid)
|
||||||
|
{
|
||||||
|
result.OutOfReach = true;
|
||||||
|
result.Blocked = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (geometry == null || geometry.Count == 0)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
clearance = Math.Max(0f, clearance);
|
||||||
|
int n = MissileBallistics.SegmentCount(arc.HorizDist);
|
||||||
|
Vector3 prev = origin;
|
||||||
|
float travelled = 0f;
|
||||||
|
|
||||||
|
for (int i = 1; i <= n; i++)
|
||||||
|
{
|
||||||
|
float t = (float)i / n;
|
||||||
|
Vector3 cur;
|
||||||
|
if (i == n) cur = target;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
arc.PointAt(t, clearance, out float px, out float py, out float pz);
|
||||||
|
cur = new Vector3(px, py, pz);
|
||||||
|
}
|
||||||
|
|
||||||
|
Vector3 seg = cur - prev;
|
||||||
|
float len = seg.Length();
|
||||||
|
if (len > 1e-4f)
|
||||||
|
{
|
||||||
|
Vector3 dir = seg / len;
|
||||||
|
foreach (var volume in geometry)
|
||||||
|
{
|
||||||
|
if (volume.IsDoor) continue;
|
||||||
|
if (!volume.RayIntersect(prev, dir, len, out float hd)) continue;
|
||||||
|
if (hd < 0f || hd > len) continue;
|
||||||
|
if (travelled + hd < 0.5f) continue; // at the shooter
|
||||||
|
if (i == n && hd > len - 0.3f) continue; // at the target
|
||||||
|
Vector3 hit = prev + dir * hd;
|
||||||
|
float hx = hit.X - origin.X, hy = hit.Y - origin.Y;
|
||||||
|
result.Blocked = true;
|
||||||
|
result.HitAlong = (float)Math.Sqrt(hx * hx + hy * hy);
|
||||||
|
result.HitZ = hit.Z - origin.Z;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
travelled += len;
|
||||||
|
prev = cur;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Tests if a line segment between two points intersects any geometry.
|
/// Tests if a line segment between two points intersects any geometry.
|
||||||
/// Used internally for arc sampling.
|
/// Used internally for arc sampling.
|
||||||
|
|
|
||||||
|
|
@ -45,6 +45,41 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||||
// If true, use arc checks for missile weapons. If false, treat all as linear.
|
// If true, use arc checks for missile weapons. If false, treat all as linear.
|
||||||
public bool UseArcs { get; set; } = true;
|
public bool UseArcs { get; set; } = true;
|
||||||
|
|
||||||
|
// Extra headroom (m) the missile arc must have at mid-flight, on top of the modelled
|
||||||
|
// flight path. Covers launch height, the real launch speed and the projectile's size.
|
||||||
|
// CombatManager overrides it from LegacyUiSettings.MissileArcClearance each tick.
|
||||||
|
public float MissileArcClearance { get; set; } = 0.5f;
|
||||||
|
|
||||||
|
// An arc that rises less than this above the straight line is flown as that line:
|
||||||
|
// the straight-line test (multi-ray in dungeons, ±0.3 m) already covers it, and the
|
||||||
|
// clearance bump is not applied to short, flat shots.
|
||||||
|
private const float ArcSagIgnoreMeters = 0.15f;
|
||||||
|
|
||||||
|
/// <summary>How a LOS verdict was reached, for the LOS debug log.</summary>
|
||||||
|
public struct LosDetail
|
||||||
|
{
|
||||||
|
public AttackType Type;
|
||||||
|
public bool Dungeon;
|
||||||
|
public bool Checked; // false = no verdict computed (no geometry near, too far, no position)
|
||||||
|
public float Velocity; // launch speed used for a missile arc (0 = straight line)
|
||||||
|
public bool LineBlocked;
|
||||||
|
public bool ArcChecked;
|
||||||
|
public RaycastEngine.ArcLosResult Arc;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsMissileArc(AttackType t) =>
|
||||||
|
t == AttackType.BowArc || t == AttackType.CrossbowArc || t == AttackType.AtlatlArc;
|
||||||
|
|
||||||
|
/// <summary>Launch speed configured for a missile attack type.</summary>
|
||||||
|
public float VelocityFor(AttackType t) => t switch
|
||||||
|
{
|
||||||
|
AttackType.BowArc => BowArcVelocity,
|
||||||
|
AttackType.CrossbowArc => CrossbowArcVelocity,
|
||||||
|
AttackType.AtlatlArc => AtlatlArcVelocity,
|
||||||
|
AttackType.MagicArc => MagicArcVelocity,
|
||||||
|
_ => 0f,
|
||||||
|
};
|
||||||
|
|
||||||
// Max scan distance in meters. Only check LOS for targets within this range.
|
// Max scan distance in meters. Only check LOS for targets within this range.
|
||||||
// Set from CombatManager based on MonsterRange + buffer.
|
// Set from CombatManager based on MonsterRange + buffer.
|
||||||
public float MaxScanDistanceMeters { get; set; } = 120.0f;
|
public float MaxScanDistanceMeters { get; set; } = 120.0f;
|
||||||
|
|
@ -62,7 +97,23 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||||
/// Returns false if the target is clear to attack.
|
/// Returns false if the target is clear to attack.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsTargetBlocked(RynthCoreHost host, uint targetId, AttackType attackType)
|
public bool IsTargetBlocked(RynthCoreHost host, uint targetId, AttackType attackType)
|
||||||
|
=> IsTargetBlocked(host, targetId, attackType, out _);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// As <see cref="IsTargetBlocked(RynthCoreHost, uint, AttackType)"/>, and reports how the
|
||||||
|
/// verdict was reached.
|
||||||
|
///
|
||||||
|
/// Missile weapons (bow, crossbow, atlatl) with UseArcs on: the target must pass the
|
||||||
|
/// straight line (walls, corner seams) AND the arc the missile really flies, low
|
||||||
|
/// ballistic solution at the weapon's launch speed plus MissileArcClearance headroom.
|
||||||
|
/// Indoors this is what catches ceilings: the old code forced a straight-line test in
|
||||||
|
/// dungeons, so a target 20-50 m down a corridor passed LOS while the arrow, rising
|
||||||
|
/// 2-6 m on its way there, hit the ceiling (2026-09-27, Longbow, Olthoi swarm).
|
||||||
|
/// </summary>
|
||||||
|
public bool IsTargetBlocked(RynthCoreHost host, uint targetId, AttackType attackType, out LosDetail detail)
|
||||||
{
|
{
|
||||||
|
detail = default;
|
||||||
|
detail.Type = attackType;
|
||||||
if (!_geoLoader.IsInitialized)
|
if (!_geoLoader.IsInitialized)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
|
@ -90,55 +141,72 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||||
uint landcell = GetPlayerLandcell(host);
|
uint landcell = GetPlayerLandcell(host);
|
||||||
uint cellPart = landcell & 0xFFFF;
|
uint cellPart = landcell & 0xFFFF;
|
||||||
bool isDungeon = cellPart >= 0x0100;
|
bool isDungeon = cellPart >= 0x0100;
|
||||||
|
detail.Dungeon = isDungeon;
|
||||||
|
|
||||||
// Force linear checks indoors — arc trajectories hit ceilings
|
bool missileArc = UseArcs && IsMissileArc(attackType);
|
||||||
if (isDungeon)
|
|
||||||
|
// Magic arcs keep the old rule: straight line indoors.
|
||||||
|
if (isDungeon && !missileArc)
|
||||||
attackType = AttackType.Linear;
|
attackType = AttackType.Linear;
|
||||||
|
detail.Type = attackType;
|
||||||
|
|
||||||
var geometry = _geoLoader.GetLandblockGeometry(landcell);
|
var geometry = _geoLoader.GetLandblockGeometry(landcell);
|
||||||
|
|
||||||
if (geometry == null || geometry.Count == 0)
|
if (geometry == null || geometry.Count == 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
// The missile's real path: solved up front so the pre-filter box covers its apex.
|
||||||
|
MissileArc arc = default;
|
||||||
|
float arcHeadroom = 0f;
|
||||||
|
if (missileArc)
|
||||||
|
{
|
||||||
|
detail.Velocity = VelocityFor(attackType);
|
||||||
|
arc = MissileBallistics.Solve(origin.X, origin.Y, origin.Z,
|
||||||
|
targetPos.X, targetPos.Y, targetPos.Z, detail.Velocity);
|
||||||
|
arcHeadroom = arc.ApexAboveLaunch + Math.Max(0f, MissileArcClearance) + 0.5f;
|
||||||
|
}
|
||||||
|
|
||||||
// Pre-filter: skip full ray test if no geometry near the path
|
// Pre-filter: skip full ray test if no geometry near the path
|
||||||
float margin = Math.Min(flatDist * 0.3f, 15.0f);
|
float margin = Math.Min(flatDist * 0.3f, 15.0f);
|
||||||
margin = Math.Max(margin, 3.0f);
|
margin = Math.Max(margin, 3.0f);
|
||||||
|
margin = Math.Max(margin, arcHeadroom);
|
||||||
if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin))
|
if (!RaycastEngine.HasNearbyGeometry(origin, targetPos, geometry, margin))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
detail.Checked = true;
|
||||||
|
|
||||||
|
if (missileArc)
|
||||||
|
{
|
||||||
|
// Walls first (cheap, and most blocked targets stop here). In dungeons use
|
||||||
|
// multi-ray: 5 rays covering the player silhouette catch thin corner
|
||||||
|
// geometry that a single center ray slips through.
|
||||||
|
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
||||||
|
if (detail.LineBlocked)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
// A short, flat shot is the straight line just tested.
|
||||||
|
if (arc.Valid && arc.MaxRiseAboveChord < ArcSagIgnoreMeters)
|
||||||
|
{
|
||||||
|
detail.Arc.Sag = arc.MaxRiseAboveChord;
|
||||||
|
detail.Arc.Apex = arc.ApexAboveLaunch;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
detail.ArcChecked = true;
|
||||||
|
return RaycastEngine.IsBallisticArcBlocked(origin, targetPos, detail.Velocity,
|
||||||
|
MissileArcClearance, geometry, out detail.Arc);
|
||||||
|
}
|
||||||
|
|
||||||
// In dungeons use multi-ray checks — 5 rays covering the player silhouette
|
// In dungeons use multi-ray checks — 5 rays covering the player silhouette
|
||||||
// catch thin corner geometry that a single center ray slips through.
|
// catch thin corner geometry that a single center ray slips through.
|
||||||
switch (attackType)
|
switch (attackType)
|
||||||
{
|
{
|
||||||
case AttackType.Linear:
|
case AttackType.Linear:
|
||||||
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
case AttackType.BowArc: // arcs off (UseArcs=false) → straight line
|
||||||
|
|
||||||
case AttackType.BowArc:
|
|
||||||
if (UseArcs)
|
|
||||||
{
|
|
||||||
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, BowArcVelocity, geometry))
|
|
||||||
return false;
|
|
||||||
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
|
||||||
}
|
|
||||||
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
|
||||||
|
|
||||||
case AttackType.CrossbowArc:
|
case AttackType.CrossbowArc:
|
||||||
if (UseArcs)
|
|
||||||
{
|
|
||||||
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, CrossbowArcVelocity, geometry))
|
|
||||||
return false;
|
|
||||||
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
|
||||||
}
|
|
||||||
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
|
||||||
|
|
||||||
case AttackType.AtlatlArc:
|
case AttackType.AtlatlArc:
|
||||||
if (UseArcs)
|
detail.LineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
||||||
{
|
return detail.LineBlocked;
|
||||||
if (!RaycastEngine.IsArcPathBlocked(origin, targetPos, AtlatlArcVelocity, geometry))
|
|
||||||
return false;
|
|
||||||
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
|
||||||
}
|
|
||||||
return RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
|
||||||
|
|
||||||
case AttackType.MagicArc:
|
case AttackType.MagicArc:
|
||||||
if (UseArcs && !isDungeon)
|
if (UseArcs && !isDungeon)
|
||||||
|
|
@ -289,8 +357,14 @@ namespace RynthCore.Plugin.RynthAi.Raycasting
|
||||||
if (currentCombatMode == 2)
|
if (currentCombatMode == 2)
|
||||||
return AttackType.Linear;
|
return AttackType.Linear;
|
||||||
|
|
||||||
// MISSILE MODE: Check the weapon name for bow vs crossbow vs thrown
|
// MISSILE MODE: Check the weapon name for bow vs crossbow vs thrown.
|
||||||
if (currentCombatMode == 4 && !string.IsNullOrEmpty(wieldedWeaponName))
|
// No name (weapon not resolved yet) is still a missile shot: bow arc. The
|
||||||
|
// combat scan used to pass "" here, which fell through to Linear, so no missile
|
||||||
|
// LOS check ever used an arc or the per-weapon velocities.
|
||||||
|
if (currentCombatMode == 4 && string.IsNullOrEmpty(wieldedWeaponName))
|
||||||
|
return UseArcs ? AttackType.BowArc : AttackType.Linear;
|
||||||
|
|
||||||
|
if (currentCombatMode == 4)
|
||||||
{
|
{
|
||||||
string name = wieldedWeaponName.ToLower();
|
string name = wieldedWeaponName.ToLower();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,8 @@ public sealed partial class RynthAiPlugin
|
||||||
ChatLine("[RynthAi] /ra bufftest — one-shot: snapshot enchant registries pre/post next item-spell cast (logs to RynthCore.log)");
|
ChatLine("[RynthAi] /ra bufftest — one-shot: snapshot enchant registries pre/post next item-spell cast (logs to RynthCore.log)");
|
||||||
ChatLine("[RynthAi] /ra settings savechar <name> — save current settings to named profile (create if new)");
|
ChatLine("[RynthAi] /ra settings savechar <name> — save current settings to named profile (create if new)");
|
||||||
ChatLine("[RynthAi] /ra settings loadchar <name> — load named settings profile (create from current if new)");
|
ChatLine("[RynthAi] /ra settings loadchar <name> — load named settings profile (create from current if new)");
|
||||||
|
ChatLine("[RynthAi] /ub autovendor [profile.utl|cancel] — run AutoVendor at the open vendor (TestMode on by default)");
|
||||||
|
ChatLine("[RynthAi] /ub vendor open[p] <name|id|selected> | opencancel | addbuy[p]/addsell[p] [n] <item> | buyall | sellall | clearbuy | clearsell");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void HandlePowerCommand(string[] parts)
|
private void HandlePowerCommand(string[] parts)
|
||||||
|
|
@ -324,8 +326,20 @@ public sealed partial class RynthAiPlugin
|
||||||
|
|
||||||
if (geometry != null && geometry.Count > 0)
|
if (geometry != null && geometry.Count > 0)
|
||||||
{
|
{
|
||||||
staticBlocked = RaycastEngine.IsArcPathBlocked(origin, targetPos, arcVelocity, geometry);
|
// Same test combat runs for missile targets: straight line (walls), then the
|
||||||
ChatLine($"[RynthAi LOS] IsArcPathBlocked: {staticBlocked}{(isDungeon && staticBlocked ? " (likely ceiling — combat LoS forces Linear in dungeons)" : "")}");
|
// arc the missile flies plus the clearance headroom (ceilings indoors).
|
||||||
|
float clearance = settings?.MissileArcClearance ?? 0.5f;
|
||||||
|
bool lineBlocked = RaycastEngine.IsLinearPathBlocked(origin, targetPos, geometry, multiRay: isDungeon);
|
||||||
|
bool arcBlocked = RaycastEngine.IsBallisticArcBlocked(origin, targetPos, arcVelocity, clearance, geometry, out var arc);
|
||||||
|
staticBlocked = lineBlocked || arcBlocked;
|
||||||
|
ChatLine($"[RynthAi LOS] Straight line ({(isDungeon ? "multi-ray" : "single-ray")}): {(lineBlocked ? "BLOCKED" : "clear")}");
|
||||||
|
ChatLine($"[RynthAi LOS] Arc: rises {arc.Sag:F2}m above the line, apex {arc.Apex:F2}m above launch, clearance {clearance:F1}m");
|
||||||
|
if (arc.OutOfReach)
|
||||||
|
ChatLine($"[RynthAi LOS] Arc: OUT OF REACH at v={arcVelocity:F1} (raise the velocity or get closer)");
|
||||||
|
else if (arcBlocked)
|
||||||
|
ChatLine($"[RynthAi LOS] Arc: BLOCKED {arc.HitAlong:F1}m out, {arc.HitZ:+0.0;-0.0;0.0}m vs launch{(isDungeon && arc.HitZ > 0.5f ? " (ceiling)" : "")}");
|
||||||
|
else
|
||||||
|
ChatLine("[RynthAi LOS] Arc: clear");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|
@ -392,63 +406,30 @@ public sealed partial class RynthAiPlugin
|
||||||
ChatLine($"[RynthAi LOS] Combined LoS ({modeLabel}): {verdict}");
|
ChatLine($"[RynthAi LOS] Combined LoS ({modeLabel}): {verdict}");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Samples a parabolic arc from origin→target at the given launch velocity,
|
// Samples the missile's arc from origin→target at the given launch speed and returns
|
||||||
// returns true if any sample point dips below terrain Z. Mirrors the math
|
// true if any sample point dips below terrain Z. Same flight path as combat's missile
|
||||||
// in RaycastEngine.IsArcPathBlocked so the terrain check tracks the same
|
// LOS (MissileBallistics: low ballistic solution, AC gravity), without the clearance.
|
||||||
// trajectory the static-geometry check uses.
|
|
||||||
private static bool TerrainBlockedAlongArc(Raycasting.Vector3 origin, Raycasting.Vector3 target,
|
private static bool TerrainBlockedAlongArc(Raycasting.Vector3 origin, Raycasting.Vector3 target,
|
||||||
float velocity, Raycasting.GeometryLoader geo,
|
float velocity, Raycasting.GeometryLoader geo,
|
||||||
out float hitDist, out Raycasting.Vector3 hitPoint)
|
out float hitDist, out Raycasting.Vector3 hitPoint)
|
||||||
{
|
{
|
||||||
hitDist = 0f;
|
hitDist = 0f;
|
||||||
hitPoint = origin;
|
hitPoint = origin;
|
||||||
const float GRAVITY = 9.81f;
|
|
||||||
const int SAMPLES = 20;
|
const int SAMPLES = 20;
|
||||||
|
|
||||||
var delta = target - origin;
|
var arc = Raycasting.MissileBallistics.Solve(origin.X, origin.Y, origin.Z, target.X, target.Y, target.Z, velocity);
|
||||||
float horiz = delta.Length2D();
|
if (!arc.Valid || arc.Vertical) return false; // out of reach is the shooter's problem, not terrain's
|
||||||
if (horiz < 0.1f) return false;
|
|
||||||
|
|
||||||
float maxRange = (velocity * velocity) / GRAVITY;
|
|
||||||
if (horiz > maxRange) return false; // out-of-range is the shooter's problem, not terrain's
|
|
||||||
|
|
||||||
float sinArg = (GRAVITY * horiz) / (velocity * velocity);
|
|
||||||
if (sinArg > 1.0f) sinArg = 1.0f;
|
|
||||||
float launchAngle = (float)(0.5 * Math.Asin(sinArg));
|
|
||||||
if (launchAngle < 0.1f) launchAngle = (float)(Math.PI / 4);
|
|
||||||
|
|
||||||
float cosA = (float)Math.Cos(launchAngle);
|
|
||||||
float sinA = (float)Math.Sin(launchAngle);
|
|
||||||
float vH = velocity * cosA;
|
|
||||||
float vV = velocity * sinA;
|
|
||||||
if (vH < 0.01f) return false;
|
|
||||||
|
|
||||||
float totalTime = horiz / vH;
|
|
||||||
float hdx = delta.X / horiz;
|
|
||||||
float hdy = delta.Y / horiz;
|
|
||||||
|
|
||||||
for (int i = 1; i <= SAMPLES; i++)
|
for (int i = 1; i <= SAMPLES; i++)
|
||||||
{
|
{
|
||||||
float t = (float)i / SAMPLES;
|
float t = (float)i / SAMPLES;
|
||||||
float time = t * totalTime;
|
arc.PointAt(t, 0f, out float wx, out float wy, out float z);
|
||||||
float hDistAlong = vH * time;
|
|
||||||
// Deep-audit finding #31 (2026-06-18) — mirrors the fix in
|
|
||||||
// RaycastEngine.IsArcPathBlocked: the flat-range parabolic sag
|
|
||||||
// (vV*time - 0.5g*time²) is exactly 0 at t=0 AND t=1 by
|
|
||||||
// construction (totalTime is the equal-height time-of-flight),
|
|
||||||
// so adding it to a straight lerp(origin.Z, target.Z) anchors
|
|
||||||
// both endpoints exactly instead of double-applying the
|
|
||||||
// elevation difference via a separate (1-t) blend.
|
|
||||||
float z = origin.Z + delta.Z * t + (vV * time - 0.5f * GRAVITY * time * time);
|
|
||||||
|
|
||||||
float wx = origin.X + hdx * hDistAlong;
|
|
||||||
float wy = origin.Y + hdy * hDistAlong;
|
|
||||||
float groundZ = geo.GetTerrainZWorld(wx, wy);
|
float groundZ = geo.GetTerrainZWorld(wx, wy);
|
||||||
if (float.IsNaN(groundZ)) continue;
|
if (float.IsNaN(groundZ)) continue;
|
||||||
|
|
||||||
if (z < groundZ)
|
if (z < groundZ)
|
||||||
{
|
{
|
||||||
hitDist = hDistAlong;
|
hitDist = t * arc.HorizDist;
|
||||||
hitPoint = new Raycasting.Vector3(wx, wy, z);
|
hitPoint = new Raycasting.Vector3(wx, wy, z);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ using RynthCore.Plugin.RynthAi.LegacyUi;
|
||||||
using RynthCore.Plugin.RynthAi.Loot;
|
using RynthCore.Plugin.RynthAi.Loot;
|
||||||
using RynthCore.Plugin.RynthAi.Meta;
|
using RynthCore.Plugin.RynthAi.Meta;
|
||||||
using RynthCore.Plugin.RynthAi.Raycasting;
|
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||||
|
using RynthCore.Plugin.RynthAi.Vendor;
|
||||||
using RynthCore.PluginCore;
|
using RynthCore.PluginCore;
|
||||||
using RynthCore.Loot;
|
using RynthCore.Loot;
|
||||||
using RynthCore.Loot.VTank;
|
using RynthCore.Loot.VTank;
|
||||||
|
|
@ -64,6 +65,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi");
|
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("RynthAi");
|
||||||
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.5.0-legacy-ui");
|
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.5.0-legacy-ui");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Oldest engine RynthAi runs on. Players get plugin updates automatically but engine
|
||||||
|
/// updates only when they click, so this stays at 66 while newer calls are feature-
|
||||||
|
/// detected (Host.HasVendorTrade for API v67 vendor trading: AutoVendor reports "needs a
|
||||||
|
/// RynthCore update" without it). The SDK default is CurrentApiVersion, which would make
|
||||||
|
/// every SDK bump refuse older engines. Raise it only for a call RynthAi can't run without.
|
||||||
|
/// </summary>
|
||||||
|
public override uint MinimumApiVersion => 66;
|
||||||
|
|
||||||
private LegacyDashboardRenderer? _dashboard;
|
private LegacyDashboardRenderer? _dashboard;
|
||||||
|
|
||||||
/// <summary>Snapshot bridge accessor for engine-side panels.</summary>
|
/// <summary>Snapshot bridge accessor for engine-side panels.</summary>
|
||||||
|
|
@ -245,6 +255,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
_missileCraftingManager = null;
|
_missileCraftingManager = null;
|
||||||
_jumper?.Cancel();
|
_jumper?.Cancel();
|
||||||
_jumper = null;
|
_jumper = null;
|
||||||
|
_autoVendor?.Reset();
|
||||||
|
_autoVendor = null;
|
||||||
_playerId = 0;
|
_playerId = 0;
|
||||||
_loginComplete = false;
|
_loginComplete = false;
|
||||||
_windowVisible = false;
|
_windowVisible = false;
|
||||||
|
|
@ -425,6 +437,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
|
|
||||||
_jumper = new Jumper(Host, _dashboard.Settings, s => Host.WriteToChat(s, 1));
|
_jumper = new Jumper(Host, _dashboard.Settings, s => Host.WriteToChat(s, 1));
|
||||||
|
|
||||||
|
if (_objectCache != null)
|
||||||
|
{
|
||||||
|
var dashForAv = _dashboard;
|
||||||
|
_autoVendor = new AutoVendorManager(Host, _dashboard.Settings, _objectCache, _playerId,
|
||||||
|
() => dashForAv?.CharFolder ?? string.Empty);
|
||||||
|
var avForUi = _autoVendor;
|
||||||
|
_dashboard.SetAutoVendorStatusProvider(() => avForUi.Status);
|
||||||
|
_dashboard.SetVendorProfilePathProvider(() => avForUi.OpenVendorProfilePath);
|
||||||
|
}
|
||||||
|
|
||||||
Log("RynthAi: login complete, legacy ImGui dashboard ready.");
|
Log("RynthAi: login complete, legacy ImGui dashboard ready.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -436,6 +458,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
// away from Navigating, and the arbiter's decision is the only thing that
|
// away from Navigating, and the arbiter's decision is the only thing that
|
||||||
// decides whether nav runs at all. One edge-detect replaces the cascade.
|
// decides whether nav runs at all. One edge-detect replaces the cascade.
|
||||||
private BotActivity _activity = BotActivity.Idle; // last arbiter decision
|
private BotActivity _activity = BotActivity.Idle; // last arbiter decision
|
||||||
|
private bool _macroWasRunning; // edge: release held turns when the macro stops
|
||||||
private BotActivity _navStoppedFor = BotActivity.Idle; // activity we last issued a nav Stop() for
|
private BotActivity _navStoppedFor = BotActivity.Idle; // activity we last issued a nav Stop() for
|
||||||
private bool _navStopIssued;
|
private bool _navStopIssued;
|
||||||
// Buffing-coma watchdog (see the Priority-1 block): how long BotAction has
|
// Buffing-coma watchdog (see the Priority-1 block): how long BotAction has
|
||||||
|
|
@ -554,7 +577,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
["TargetFPSFocused"] = (10, 240), ["TargetFPSBackground"] = (5, 60),
|
["TargetFPSFocused"] = (10, 240), ["TargetFPSBackground"] = (5, 60),
|
||||||
["BlacklistAttempts"] = (1, 20), ["BlacklistTimeoutSec"] = (5, 120), ["BlacklistCastSettleMs"] = (500, 5000),
|
["BlacklistAttempts"] = (1, 20), ["BlacklistTimeoutSec"] = (5, 120), ["BlacklistCastSettleMs"] = (500, 5000),
|
||||||
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000),
|
["TargetNoProgressTimeoutSec"] = (0, 300), ["GiveQueueIntervalMs"] = (50, 2000),
|
||||||
["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60),
|
["BowArcVelocity"] = (10, 60), ["CrossbowArcVelocity"] = (10, 80), ["AtlatlArcVelocity"] = (10, 60), ["MagicArcVelocity"] = (10, 60), ["MissileArcClearance"] = (0, 3),
|
||||||
["HealAt"] = (0, 100), ["RestamAt"] = (0, 100), ["GetManaAt"] = (0, 100),
|
["HealAt"] = (0, 100), ["RestamAt"] = (0, 100), ["GetManaAt"] = (0, 100),
|
||||||
["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100),
|
["TopOffHP"] = (0, 100), ["TopOffStam"] = (0, 100), ["TopOffMana"] = (0, 100),
|
||||||
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
|
["HealOthersAt"] = (0, 100), ["RestamOthersAt"] = (0, 100), ["InfuseOthersAt"] = (0, 100),
|
||||||
|
|
@ -569,10 +592,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
["FollowNavMin"] = (0.5, 20), ["NavRingThickness"] = (1, 16), ["NavLineThickness"] = (1, 16),
|
["FollowNavMin"] = (0.5, 20), ["NavRingThickness"] = (1, 16), ["NavLineThickness"] = (1, 16),
|
||||||
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 2),
|
["NavHeightOffset"] = (-5, 5), ["NavSlopeSink"] = (0, 8), ["OpenDoorRange"] = (0.1, 70), ["MovementMode"] = (0, 2),
|
||||||
["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10),
|
["NavStopTurnAngle"] = (1, 90), ["NavResumeTurnAngle"] = (1, 45), ["NavDeadZone"] = (0.5, 20), ["NavSweepMult"] = (0.5, 10),
|
||||||
["NavLookaheadYards"] = (0, 30), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30),
|
["NavLookaheadYards"] = (0, 30), ["NavShortcutYards"] = (0, 10), ["NavTurnRateDegPerSec"] = (30, 720), ["NavTier1TurnSpeed"] = (0.5, 15), ["PostPortalDelaySec"] = (0, 30),
|
||||||
["T2Speed"] = (0.1, 5), ["T2WalkWithinYd"] = (1, 50), ["T2DistanceTo"] = (0.1, 10), ["T2ReissueMs"] = (100, 10000),
|
["T2Speed"] = (0.1, 5), ["T2WalkWithinYd"] = (1, 50), ["T2DistanceTo"] = (0.1, 10), ["T2ReissueMs"] = (100, 10000),
|
||||||
["T2MaxRangeYd"] = (50, 2000), ["T2MaxLandblocks"] = (1, 20),
|
["T2MaxRangeYd"] = (50, 2000), ["T2MaxLandblocks"] = (1, 20),
|
||||||
["RebuffSecondsRemaining"] = (30, 1800),
|
["RebuffSecondsRemaining"] = (30, 1800), ["RebuffTopOffSecondsRemaining"] = (30, 3600),
|
||||||
|
["AutoVendorTries"] = (1, 20), ["AutoVendorTriesTime"] = (500, 30000),
|
||||||
["BuffMinSkillLevelTier1"] = (1, 500), ["BuffMinSkillLevelTier2"] = (1, 500), ["BuffMinSkillLevelTier3"] = (1, 500), ["BuffMinSkillLevelTier4"] = (1, 500),
|
["BuffMinSkillLevelTier1"] = (1, 500), ["BuffMinSkillLevelTier2"] = (1, 500), ["BuffMinSkillLevelTier3"] = (1, 500), ["BuffMinSkillLevelTier4"] = (1, 500),
|
||||||
["BuffMinSkillLevelTier5"] = (1, 500), ["BuffMinSkillLevelTier6"] = (1, 500), ["BuffMinSkillLevelTier7"] = (1, 500), ["BuffMinSkillLevelTier8"] = (1, 500),
|
["BuffMinSkillLevelTier5"] = (1, 500), ["BuffMinSkillLevelTier6"] = (1, 500), ["BuffMinSkillLevelTier7"] = (1, 500), ["BuffMinSkillLevelTier8"] = (1, 500),
|
||||||
["LootJumpHeight"] = (1, 100), ["LootOwnership"] = (0, 2),
|
["LootJumpHeight"] = (1, 100), ["LootOwnership"] = (0, 2),
|
||||||
|
|
@ -1116,6 +1140,12 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
return;
|
return;
|
||||||
if (diag) Host.Log($"[RynthAi] OnTick: settings ok, macro={settings.IsMacroRunning} action={settings.BotAction}");
|
if (diag) Host.Log($"[RynthAi] OnTick: settings ok, macro={settings.IsMacroRunning} action={settings.BotAction}");
|
||||||
|
|
||||||
|
// Macro switched off: combat stops ticking, so a turn it was holding would
|
||||||
|
// stay held and the character spun on its own (2026-09-27). Let go once.
|
||||||
|
if (_macroWasRunning && !settings.IsMacroRunning)
|
||||||
|
_combatManager?.ReleaseHeldTurn();
|
||||||
|
_macroWasRunning = settings.IsMacroRunning;
|
||||||
|
|
||||||
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
|
if (_patrolOnLoginPending && _raycast?.GeometryLoader?.CellDat?.IsLoaded == true)
|
||||||
{
|
{
|
||||||
_patrolOnLoginPending = false;
|
_patrolOnLoginPending = false;
|
||||||
|
|
@ -1232,6 +1262,25 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
}
|
}
|
||||||
catch { /* arbiter must never throw out of the live tick */ }
|
catch { /* arbiter must never throw out of the live tick */ }
|
||||||
|
|
||||||
|
// ── AutoVendor (UtilityBelt-style) ───────────────────────────────
|
||||||
|
// Runs whether or not the macro is on: it starts when a vendor opens.
|
||||||
|
// While it holds the bot (a vendoring session, or /ub vendor open
|
||||||
|
// trying to reach a vendor) nothing else moves the character or the
|
||||||
|
// inventory — UB takes VTank's Navigation + ItemUse locks the same way.
|
||||||
|
// Bounded by AutoVendor's own 60 s bail timer.
|
||||||
|
var autoVendor = _autoVendor;
|
||||||
|
if (autoVendor != null)
|
||||||
|
{
|
||||||
|
autoVendor.Tick(_busyCount);
|
||||||
|
if (autoVendor.HoldsBot)
|
||||||
|
{
|
||||||
|
if (settings.IsMacroRunning)
|
||||||
|
StopNavFor(BotActivity.Idle);
|
||||||
|
_metaManager?.Think();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── Priority 1: Buffing ───────────────────────────────────────────
|
// ── Priority 1: Buffing ───────────────────────────────────────────
|
||||||
// Blocks combat, looting, and navigation entirely. The coma
|
// Blocks combat, looting, and navigation entirely. The coma
|
||||||
// watchdog that used to live here now runs ahead of the decision
|
// watchdog that used to live here now runs ahead of the decision
|
||||||
|
|
@ -1543,6 +1592,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
|
|
||||||
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
|
public override void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
|
||||||
{
|
{
|
||||||
|
float prevRatio = _objectCache?.GetHealthRatio(unchecked((int)targetId)) ?? -1f;
|
||||||
_objectCache?.OnUpdateHealth(targetId, healthRatio);
|
_objectCache?.OnUpdateHealth(targetId, healthRatio);
|
||||||
_dashboard?.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
|
_dashboard?.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
|
||||||
if (_loginComplete && targetId == _playerId && maxHealth > 0)
|
if (_loginComplete && targetId == _playerId && maxHealth > 0)
|
||||||
|
|
@ -1551,9 +1601,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
_vitals.MaxHealth = maxHealth;
|
_vitals.MaxHealth = maxHealth;
|
||||||
}
|
}
|
||||||
|
|
||||||
// When a creature's health changes, something hit it — reset its miss counter
|
// When a creature's health DROPS, something hit it — reset its miss counter so the
|
||||||
// so the blacklist doesn't trigger on valid in-combat targets.
|
// blacklist doesn't trigger on valid in-combat targets. Only a drop counts: the
|
||||||
if (targetId != _playerId)
|
// client also gets health for a mob the player merely selects (QueryHealth reply),
|
||||||
|
// for the fight target combat queries at lock, and on regen, all at unchanged or
|
||||||
|
// higher health. Counting those as hits reset the no-damage miss streak,
|
||||||
|
// un-blacklisted the mob and gave it the damage-commitment bonus, so selecting a
|
||||||
|
// mob could steer combat and a target the arrows weren't hurting could be held far
|
||||||
|
// past BlacklistAttempts misses (2026-09-27, Olthoi swarm).
|
||||||
|
if (targetId != _playerId && IsHealthDrop(prevRatio, healthRatio))
|
||||||
_combatManager?.ReportDamageOnTarget((int)targetId);
|
_combatManager?.ReportDamageOnTarget((int)targetId);
|
||||||
|
|
||||||
// Capture observed creature data into the persistent store. maxHealth>0 means
|
// Capture observed creature data into the persistent store. maxHealth>0 means
|
||||||
|
|
@ -1563,6 +1619,16 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|
||||||
CaptureCreatureSample(targetId, maxHealth);
|
CaptureCreatureSample(targetId, maxHealth);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True when a health update means the creature lost health: lower than the last ratio
|
||||||
|
/// we knew, or, for the first report of a creature, below full.
|
||||||
|
/// </summary>
|
||||||
|
private static bool IsHealthDrop(float prevRatio, float newRatio)
|
||||||
|
{
|
||||||
|
if (float.IsNaN(newRatio)) return false;
|
||||||
|
return prevRatio < 0f ? newRatio < 0.999f : newRatio < prevRatio - 0.0005f;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Something you can fight — what the Damage tab and creatures.json should learn from.
|
/// Something you can fight — what the Damage tab and creatures.json should learn from.
|
||||||
/// Appraising an NPC, a vendor, another player or your own pet also returns health, and
|
/// Appraising an NPC, a vendor, another player or your own pet also returns health, and
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,10 @@ public sealed partial class RynthAiPlugin
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// /ub autovendor ... and /ub vendor ... (UtilityBelt AutoVendor) — Vendor/AutoVendorCommands.cs
|
||||||
|
if (TryHandleAutoVendorCommand(cmd, fullCommand))
|
||||||
|
return true;
|
||||||
|
|
||||||
// Most remaining /ub verbs (use / usep / uselp / useip / face / give /
|
// Most remaining /ub verbs (use / usep / uselp / useip / face / give /
|
||||||
// givep / combatstate / cast …) share semantics with the natively
|
// givep / combatstate / cast …) share semantics with the natively
|
||||||
// implemented /mt verbs, which talk to host primitives (UseObject /
|
// implemented /mt verbs, which talk to host primitives (UseObject /
|
||||||
|
|
|
||||||
94
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorCommands.cs
vendored
Normal file
94
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorCommands.cs
vendored
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
using System;
|
||||||
|
using RynthCore.Plugin.RynthAi.Vendor;
|
||||||
|
|
||||||
|
namespace RynthCore.Plugin.RynthAi;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// UtilityBelt's /ub autovendor and /ub vendor commands. Parsed here (chat thread),
|
||||||
|
/// run by AutoVendorManager on the plugin tick thread.
|
||||||
|
/// </summary>
|
||||||
|
public sealed partial class RynthAiPlugin
|
||||||
|
{
|
||||||
|
private AutoVendorManager? _autoVendor;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// /ub autovendor [cancel|stop|quit|profile]
|
||||||
|
/// /ub vendor {open[p] [name|id|hex|selected] | opencancel | buy[all] | sell[all] |
|
||||||
|
/// clearbuy | clearsell | addbuy[p] [count] item | addsell[p] [count] item}
|
||||||
|
/// Returns false when the verb isn't an AutoVendor verb.
|
||||||
|
/// </summary>
|
||||||
|
private bool TryHandleAutoVendorCommand(string cmd, string fullCommand)
|
||||||
|
{
|
||||||
|
if (cmd != "autovendor" && cmd != "vendor")
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var av = _autoVendor;
|
||||||
|
if (av == null)
|
||||||
|
{
|
||||||
|
ChatLine("[RynthAi] AutoVendor isn't ready yet (log in first).");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
string rest = AfterWords(fullCommand, 2); // everything after "/ub <verb>"
|
||||||
|
|
||||||
|
if (cmd == "autovendor")
|
||||||
|
{
|
||||||
|
av.Enqueue(() => av.CommandAutoVendor(rest));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
string action = rest;
|
||||||
|
string args = string.Empty;
|
||||||
|
int asp = rest.IndexOf(' ');
|
||||||
|
if (asp >= 0)
|
||||||
|
{
|
||||||
|
action = rest.Substring(0, asp);
|
||||||
|
args = rest.Substring(asp + 1).Trim();
|
||||||
|
}
|
||||||
|
action = action.ToLowerInvariant();
|
||||||
|
|
||||||
|
switch (action)
|
||||||
|
{
|
||||||
|
case "buy":
|
||||||
|
case "buyall": av.Enqueue(av.CommandBuyAll); break;
|
||||||
|
case "sell":
|
||||||
|
case "sellall": av.Enqueue(av.CommandSellAll); break;
|
||||||
|
case "clearbuy": av.Enqueue(av.CommandClearBuy); break;
|
||||||
|
case "clearsell": av.Enqueue(av.CommandClearSell); break;
|
||||||
|
// UB: "open" with no name picks the nearest vendor, like openp.
|
||||||
|
case "open": av.Enqueue(() => av.CommandOpen(args, partial: args.Length == 0)); break;
|
||||||
|
case "openp": av.Enqueue(() => av.CommandOpen(args, partial: true)); break;
|
||||||
|
case "opencancel": av.Enqueue(av.CommandOpenCancel); break;
|
||||||
|
case "addbuy":
|
||||||
|
case "addbuyp":
|
||||||
|
if (args.Length == 0) { VendorUsage(); break; }
|
||||||
|
av.Enqueue(() => av.CommandAddBuy(args, partial: action == "addbuyp"));
|
||||||
|
break;
|
||||||
|
case "addsell":
|
||||||
|
case "addsellp":
|
||||||
|
if (args.Length == 0) { VendorUsage(); break; }
|
||||||
|
av.Enqueue(() => av.CommandAddSell(args, partial: action == "addsellp"));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
VendorUsage();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The text after the first <paramref name="words"/> space-separated words, trimmed.</summary>
|
||||||
|
private static string AfterWords(string text, int words)
|
||||||
|
{
|
||||||
|
int i = 0;
|
||||||
|
string s = text ?? string.Empty;
|
||||||
|
for (int w = 0; w < words; w++)
|
||||||
|
{
|
||||||
|
while (i < s.Length && char.IsWhiteSpace(s[i])) i++;
|
||||||
|
while (i < s.Length && !char.IsWhiteSpace(s[i])) i++;
|
||||||
|
}
|
||||||
|
return i < s.Length ? s.Substring(i).Trim() : string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VendorUsage()
|
||||||
|
=> ChatLine("[RynthAi] Usage: /ub vendor {open[p] <vendorname,vendorid,vendorhex> | buyall | sellall | clearbuy | clearsell | opencancel | addbuy[p] [count] <item> | addsell[p] [count] <item>}");
|
||||||
|
}
|
||||||
1470
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs
vendored
Normal file
1470
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorManager.cs
vendored
Normal file
File diff suppressed because it is too large
Load diff
497
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs
vendored
Normal file
497
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorPlanner.cs
vendored
Normal file
|
|
@ -0,0 +1,497 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Linq;
|
||||||
|
using RynthCore.Loot;
|
||||||
|
|
||||||
|
namespace RynthCore.Plugin.RynthAi.Vendor;
|
||||||
|
|
||||||
|
// Pure planning for AutoVendor, a port of UtilityBelt's AutoVendor.DoVendoring /
|
||||||
|
// GetBuyItems / GetSellItems / ItemIsSafeToGetRidOf / AddItemToSellList. No host calls:
|
||||||
|
// the manager fills these views from the engine's vendor snapshot and the inventory,
|
||||||
|
// executes the plan, waits for the server, and plans again. One transaction per plan,
|
||||||
|
// buying before selling, exactly as UB does.
|
||||||
|
|
||||||
|
/// <summary>The open vendor (engine VendorInfo).</summary>
|
||||||
|
internal sealed class VendorView
|
||||||
|
{
|
||||||
|
public uint Id { get; init; }
|
||||||
|
public string Name { get; init; } = string.Empty;
|
||||||
|
/// <summary>Vendor pays value x BuyRate when you sell.</summary>
|
||||||
|
public float BuyRate { get; init; } = 1f;
|
||||||
|
/// <summary>Vendor charges value x SellRate when you buy.</summary>
|
||||||
|
public float SellRate { get; init; } = 1f;
|
||||||
|
public uint ItemTypes { get; init; }
|
||||||
|
public int MaxValue { get; init; }
|
||||||
|
public bool UsesAltCurrency { get; init; }
|
||||||
|
|
||||||
|
public bool Buys(uint itemType) => (ItemTypes & itemType) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One item on the vendor's list (engine VendorItem).</summary>
|
||||||
|
internal sealed class Listing
|
||||||
|
{
|
||||||
|
public uint Id { get; init; }
|
||||||
|
public string Name { get; init; } = string.Empty;
|
||||||
|
public AcObjectClass Class { get; init; }
|
||||||
|
public uint ItemType { get; init; }
|
||||||
|
/// <summary>How many the vendor has; negative = unlimited.</summary>
|
||||||
|
public int Amount { get; init; } = -1;
|
||||||
|
public int StackSize { get; init; } = 1;
|
||||||
|
public int MaxStackSize { get; init; } = 1;
|
||||||
|
/// <summary>Value of the listed stack.</summary>
|
||||||
|
public int Value { get; init; }
|
||||||
|
/// <summary>Engine's per-unit price at this vendor (0 = unknown).</summary>
|
||||||
|
public int UnitPrice { get; init; }
|
||||||
|
/// <summary>Burden of the listed stack.</summary>
|
||||||
|
public int Burden { get; init; }
|
||||||
|
public bool NeedsContainerSlot { get; init; }
|
||||||
|
|
||||||
|
public bool Unlimited => Amount < 0;
|
||||||
|
public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
|
||||||
|
public int UnitValue => StackSize > 1 ? Value / StackSize : Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A vendor item the profile wants, with how many (int.MaxValue = all you can afford).</summary>
|
||||||
|
internal sealed class BuyWant
|
||||||
|
{
|
||||||
|
public Listing Item { get; init; } = null!;
|
||||||
|
public int Amount { get; init; }
|
||||||
|
public string RuleName { get; init; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An inventory item that passed the safety checks and a Sell rule.</summary>
|
||||||
|
internal sealed class SellItem
|
||||||
|
{
|
||||||
|
public uint Id { get; init; }
|
||||||
|
public string Name { get; init; } = string.Empty;
|
||||||
|
public AcObjectClass Class { get; init; }
|
||||||
|
public uint ItemType { get; init; }
|
||||||
|
public int StackSize { get; init; } = 1;
|
||||||
|
/// <summary>Value of the whole stack.</summary>
|
||||||
|
public int Value { get; init; }
|
||||||
|
public string RuleName { get; init; } = string.Empty;
|
||||||
|
public string Location { get; init; } = string.Empty;
|
||||||
|
public int SortSlot { get; init; }
|
||||||
|
|
||||||
|
public bool IsNote => Class == AcObjectClass.TradeNote || (ItemType & AutoVendorPlanner.ItemTypePromissoryNote) != 0;
|
||||||
|
public int UnitValue => StackSize > 1 ? Value / StackSize : Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Money and room, read fresh before each plan.</summary>
|
||||||
|
internal sealed class PackState
|
||||||
|
{
|
||||||
|
/// <summary>Pyreals, or the vendor's alt currency.</summary>
|
||||||
|
public long Funds { get; init; }
|
||||||
|
/// <summary>Free item slots in the MAIN pack (UB: Weenie(player).FreeSpace).</summary>
|
||||||
|
public int FreeMainSlots { get; init; }
|
||||||
|
public int FreeContainerSlots { get; init; }
|
||||||
|
public int PyrealStackSize { get; init; } = AutoVendorPlanner.DefaultPyrealStackSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum PlanKind : byte
|
||||||
|
{
|
||||||
|
Done = 0,
|
||||||
|
Buy = 1,
|
||||||
|
Sell = 2,
|
||||||
|
Split = 3,
|
||||||
|
Fatal = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal readonly record struct BuyLine(Listing Item, int Amount);
|
||||||
|
|
||||||
|
internal sealed class VendorPlan
|
||||||
|
{
|
||||||
|
public PlanKind Kind { get; init; }
|
||||||
|
public List<BuyLine> Buys { get; init; } = new();
|
||||||
|
public List<SellItem> Sells { get; init; } = new();
|
||||||
|
/// <summary>Buy: estimated cost. Sell: estimated payout.</summary>
|
||||||
|
public long Total { get; init; }
|
||||||
|
public SellItem? SplitItem { get; init; }
|
||||||
|
public int SplitAmount { get; init; }
|
||||||
|
public string Message { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public static VendorPlan Done() => new() { Kind = PlanKind.Done };
|
||||||
|
public static VendorPlan Fatal(string msg) => new() { Kind = PlanKind.Fatal, Message = msg };
|
||||||
|
public static VendorPlan Split(SellItem item, int amount, string why) =>
|
||||||
|
new() { Kind = PlanKind.Split, SplitItem = item, SplitAmount = amount, Message = why };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the manager read about an inventory item for UB's "safe to get rid of" checks.</summary>
|
||||||
|
internal sealed class SafetyFacts
|
||||||
|
{
|
||||||
|
/// <summary>Has appraisal data: without it the checks below can't be trusted, so never sell.</summary>
|
||||||
|
public bool Appraised { get; init; }
|
||||||
|
public AcObjectClass Class { get; init; }
|
||||||
|
public int Value { get; init; }
|
||||||
|
/// <summary>ACE IsSellable (69); null = unknown (treated as sellable, like UB's default).</summary>
|
||||||
|
public bool? CanBeSold { get; init; }
|
||||||
|
public bool IsRare { get; init; }
|
||||||
|
public bool InMainPack { get; init; }
|
||||||
|
public bool Equipped { get; init; }
|
||||||
|
public int Attuned { get; init; }
|
||||||
|
public int Bonded { get; init; }
|
||||||
|
public bool Retained { get; init; }
|
||||||
|
public int TimesTinkered { get; init; }
|
||||||
|
public int Imbued { get; init; }
|
||||||
|
public string Inscription { get; init; } = string.Empty;
|
||||||
|
/// <summary>A pack or focus (holds items).</summary>
|
||||||
|
public bool HoldsItems { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class AutoVendorPlanner
|
||||||
|
{
|
||||||
|
public const int MaxVendorBuyCount = 5000; // UB MAX_VENDOR_BUY_COUNT
|
||||||
|
public const int MaxSellLines = 99; // UB: GDLE rejects 100+ items per transaction
|
||||||
|
public const int DefaultPyrealStackSize = 25000;
|
||||||
|
public const uint PyrealWcid = 273;
|
||||||
|
public const uint ItemTypePromissoryNote = 0x00040000;
|
||||||
|
|
||||||
|
// UB ShopItemListTypes: shop category names for the test-mode report.
|
||||||
|
private static readonly (uint Bit, string Name)[] ShopCategories =
|
||||||
|
{
|
||||||
|
(0x00000001, "Weapons"), (0x00000002, "Armor"), (0x00000004, "Clothing"), (0x00000008, "Jewelry"),
|
||||||
|
(0x00000010, "Miscellaneous"), (0x00000020, "Food"), (0x00000080, "Miscellaneous"), (0x00000100, "Weapons"),
|
||||||
|
(0x00000200, "Containers"), (0x00000400, "Miscellaneous"), (0x00000800, "Gems"), (0x00001000, "Spell Components"),
|
||||||
|
(0x00002000, "Books, Paper"), (0x00004000, "Keys, Tools"), (0x00008000, "Magic Items"), (0x00040000, "Trade Notes"),
|
||||||
|
(0x00080000, "Mana Stones"), (0x00100000, "Services"), (0x00400000, "Cooking Items"), (0x00800000, "Alchemical Items"),
|
||||||
|
(0x01000000, "Fletching Items"), (0x04000000, "Alchemical Items"), (0x08000000, "Fletching Items"), (0x20000000, "Keys, Tools"),
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string CategoryName(uint itemType)
|
||||||
|
{
|
||||||
|
foreach (var (bit, name) in ShopCategories)
|
||||||
|
if ((itemType & bit) != 0) return name;
|
||||||
|
return $"Unknown Category 0x{itemType:X8}";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Prices (ACE Vendor.GetSellCost / GetBuyCost, as the engine checks them) ──────────
|
||||||
|
|
||||||
|
/// <summary>What you pay for one created stack worth <paramref name="stackValue"/>.</summary>
|
||||||
|
public static long PlayerPays(VendorView v, bool isNote, long stackValue)
|
||||||
|
{
|
||||||
|
float rate = isNote ? 1.15f : v.SellRate;
|
||||||
|
float product = rate * stackValue;
|
||||||
|
return Math.Max(1L, (long)Math.Ceiling(product - 0.1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the vendor pays for one item (whole stack) worth <paramref name="value"/>.</summary>
|
||||||
|
public static long VendorPays(VendorView v, bool isNote, long value)
|
||||||
|
{
|
||||||
|
float rate = isNote ? 1.0f : v.BuyRate;
|
||||||
|
float product = rate * value;
|
||||||
|
return Math.Max(1L, (long)Math.Floor(product + 0.1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Per-unit price: the engine's figure, else UB's (int)(Value/Stack) x rate rounded like ACE.</summary>
|
||||||
|
public static long UnitPrice(VendorView v, Listing item)
|
||||||
|
{
|
||||||
|
if (item.UnitPrice > 0) return item.UnitPrice;
|
||||||
|
if (item.UnitValue <= 0) return 0;
|
||||||
|
return PlayerPays(v, item.IsNote, item.UnitValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The engine's EstimateBuy: stackables in full stacks, limited listings at least the whole listing.</summary>
|
||||||
|
public static long EstimateCost(VendorView v, Listing item, int amount)
|
||||||
|
{
|
||||||
|
if (amount <= 0) return 0;
|
||||||
|
long unitValue = Math.Max(0, item.UnitValue);
|
||||||
|
long cost;
|
||||||
|
if (item.MaxStackSize > 1)
|
||||||
|
{
|
||||||
|
long max = item.MaxStackSize;
|
||||||
|
long full = amount / max;
|
||||||
|
long rem = amount % max;
|
||||||
|
cost = full * PlayerPays(v, item.IsNote, unitValue * max) + (rem > 0 ? PlayerPays(v, item.IsNote, unitValue * rem) : 0);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
cost = amount * PlayerPays(v, item.IsNote, unitValue);
|
||||||
|
}
|
||||||
|
if (!item.Unlimited)
|
||||||
|
cost = Math.Max(cost, PlayerPays(v, item.IsNote, Math.Max(0, item.Value)));
|
||||||
|
return cost;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Largest amount in [0, max] whose EstimateCost fits <paramref name="money"/> (cost only grows with amount).</summary>
|
||||||
|
public static int MostAffordable(VendorView v, Listing item, int max, long money)
|
||||||
|
{
|
||||||
|
int lo = 0, hi = Math.Max(0, max);
|
||||||
|
while (lo < hi)
|
||||||
|
{
|
||||||
|
int mid = lo + (hi - lo + 1) / 2;
|
||||||
|
if (EstimateCost(v, item, mid) <= money) lo = mid;
|
||||||
|
else hi = mid - 1;
|
||||||
|
}
|
||||||
|
return lo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int SlotsFor(Listing item, int amount)
|
||||||
|
{
|
||||||
|
int max = Math.Max(1, item.MaxStackSize);
|
||||||
|
return (int)((amount + (long)max - 1) / max);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>UB PyrealsWillFitInMainPack: always leaves one main-pack slot free.</summary>
|
||||||
|
public static bool PyrealsFit(PackState p, double amount)
|
||||||
|
{
|
||||||
|
int stack = Math.Max(1, p.PyrealStackSize);
|
||||||
|
return p.FreeMainSlots - Math.Ceiling(amount / stack) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Safety (UB ItemIsSafeToGetRidOf + Util.IsItemSafeToGetRidOf, stricter) ──────────
|
||||||
|
|
||||||
|
/// <summary>Null when the item may be sold; otherwise the reason it never will be.</summary>
|
||||||
|
public static string? UnsafeReason(SafetyFacts f, bool onlyFromMainPack)
|
||||||
|
{
|
||||||
|
if (!f.Appraised) return "not identified";
|
||||||
|
if (f.Equipped) return "equipped";
|
||||||
|
if (f.Class == AcObjectClass.Money) return "money";
|
||||||
|
if (f.Class == AcObjectClass.Container || f.HoldsItems) return "container";
|
||||||
|
if (f.Class == AcObjectClass.Foci) return "focus";
|
||||||
|
if (f.Value <= 0) return "no value";
|
||||||
|
if (f.CanBeSold == false) return "not sellable";
|
||||||
|
if (f.IsRare) return "rare";
|
||||||
|
if (onlyFromMainPack && !f.InMainPack) return "not in main pack";
|
||||||
|
if (f.Attuned != 0) return "attuned";
|
||||||
|
if (f.Bonded != 0) return "bonded";
|
||||||
|
if (f.Retained) return "retained";
|
||||||
|
if (f.TimesTinkered > 0) return "tinkered";
|
||||||
|
if (f.Imbued != 0) return "imbued";
|
||||||
|
if (!string.IsNullOrEmpty(f.Inscription)) return "inscribed";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// UB VendorInfo.WillBuyItem. Trade notes skip the value cap like UB, but the vendor must
|
||||||
|
/// still list the note item type: the engine refuses anything outside the vendor's types.
|
||||||
|
/// </summary>
|
||||||
|
public static bool VendorWillBuy(VendorView v, uint itemType, bool isNote, int unitValue)
|
||||||
|
{
|
||||||
|
if (!v.Buys(itemType)) return false;
|
||||||
|
if (isNote) return true;
|
||||||
|
return v.MaxValue > 0 && unitValue <= v.MaxValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Buy list (UB GetBuyItems) ────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Keep # buys (count - have), where have is the inventory count by exact name (containers:
|
||||||
|
/// by object class, and only the first container rule). Keep buys int.MaxValue. Sorted
|
||||||
|
/// trade notes last, then cheapest unit price first.
|
||||||
|
/// </summary>
|
||||||
|
public static List<BuyWant> BuildBuyWants(
|
||||||
|
VendorView v,
|
||||||
|
IEnumerable<(Listing Item, BuyDecision Decision)> judged,
|
||||||
|
Func<string, int> countByName,
|
||||||
|
Func<AcObjectClass, int> countByClass)
|
||||||
|
{
|
||||||
|
var list = judged.ToList();
|
||||||
|
var wants = new List<BuyWant>();
|
||||||
|
bool buyingContainers = false;
|
||||||
|
|
||||||
|
foreach (var (item, d) in list)
|
||||||
|
{
|
||||||
|
if (d.Kind != BuyKind.KeepUpTo) continue;
|
||||||
|
if (item.Class == AcObjectClass.Container)
|
||||||
|
{
|
||||||
|
int have = countByClass(AcObjectClass.Container);
|
||||||
|
if (!buyingContainers && d.KeepCount > have)
|
||||||
|
{
|
||||||
|
buyingContainers = true;
|
||||||
|
wants.Add(new BuyWant { Item = item, Amount = d.KeepCount - have, RuleName = d.RuleName });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
int have = countByName(item.Name);
|
||||||
|
if (d.KeepCount > have)
|
||||||
|
wants.Add(new BuyWant { Item = item, Amount = d.KeepCount - have, RuleName = d.RuleName });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (item, d) in list)
|
||||||
|
if (d.Kind == BuyKind.Keep)
|
||||||
|
wants.Add(new BuyWant { Item = item, Amount = int.MaxValue, RuleName = d.RuleName });
|
||||||
|
|
||||||
|
return wants
|
||||||
|
.OrderBy(w => w.Item.IsNote ? 1 : 0)
|
||||||
|
.ThenBy(w => UnitPrice(v, w.Item))
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>UB GetSellItems sort: trade notes last, then cheapest stack payout first.</summary>
|
||||||
|
public static List<SellItem> SortSells(VendorView v, IEnumerable<SellItem> items) =>
|
||||||
|
items.OrderBy(s => s.IsNote ? 1 : 0)
|
||||||
|
.ThenBy(s => VendorPays(v, s.IsNote, s.Value))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
// ── One transaction (UB DoVendoring) ─────────────────────────────────────
|
||||||
|
|
||||||
|
/// <param name="wants">From BuildBuyWants (already sorted).</param>
|
||||||
|
/// <param name="sells">From SortSells.</param>
|
||||||
|
public static VendorPlan PlanNext(VendorView v, IReadOnlyList<BuyWant> wants, IReadOnlyList<SellItem> sells, PackState p)
|
||||||
|
{
|
||||||
|
// ── Buy first ──
|
||||||
|
var buys = new List<BuyLine>();
|
||||||
|
long totalCost = 0;
|
||||||
|
int totalSlots = 0, totalContainerSlots = 0;
|
||||||
|
|
||||||
|
// UB re-orders by the listing's raw Value here (a stable sort over the price order).
|
||||||
|
foreach (var want in wants.OrderBy(w => w.Item.Value))
|
||||||
|
{
|
||||||
|
Listing item = want.Item;
|
||||||
|
long price = UnitPrice(v, item);
|
||||||
|
if (price <= 0)
|
||||||
|
return VendorPlan.Fatal(string.Format(CultureInfo.InvariantCulture,
|
||||||
|
"AutoVendor Fatal - No vendor price found while adding {0:n0}x {1}[0x{2:X8}] Value: {3:n}",
|
||||||
|
want.Amount, item.Name, item.Id, (double)price));
|
||||||
|
|
||||||
|
bool fits;
|
||||||
|
if (item.NeedsContainerSlot)
|
||||||
|
fits = p.FreeContainerSlots - totalContainerSlots > 0;
|
||||||
|
else
|
||||||
|
fits = p.FreeMainSlots - totalSlots > (item.IsNote ? 0 : 1);
|
||||||
|
|
||||||
|
if (totalCost + price <= p.Funds && fits)
|
||||||
|
{
|
||||||
|
long affordable = (p.Funds - totalCost) / price;
|
||||||
|
long count = Math.Min(affordable, want.Amount);
|
||||||
|
count = Math.Min(count, MaxVendorBuyCount);
|
||||||
|
if (!item.Unlimited) count = Math.Min(count, item.Amount);
|
||||||
|
|
||||||
|
if (item.NeedsContainerSlot)
|
||||||
|
{
|
||||||
|
count = Math.Min(count, p.FreeContainerSlots - totalContainerSlots);
|
||||||
|
}
|
||||||
|
else if (p.FreeMainSlots < SlotsFor(item, (int)count) + totalSlots)
|
||||||
|
{
|
||||||
|
// UB: limit to what fits, keeping two slots spare (never below zero).
|
||||||
|
long fit = (long)Math.Max(1, item.MaxStackSize) * Math.Max(0, (p.FreeMainSlots - 2) - totalSlots);
|
||||||
|
count = Math.Min(count, fit);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The engine's exact cost can exceed the per-unit estimate (a limited listing
|
||||||
|
// costs at least the whole listing): take the most that still fits the money.
|
||||||
|
if (count > 0 && totalCost + EstimateCost(v, item, (int)count) > p.Funds)
|
||||||
|
count = MostAffordable(v, item, (int)count, p.Funds - totalCost);
|
||||||
|
if (count <= 0)
|
||||||
|
break;
|
||||||
|
|
||||||
|
int n = (int)count;
|
||||||
|
buys.Add(new BuyLine(item, n));
|
||||||
|
if (item.NeedsContainerSlot) totalContainerSlots += n;
|
||||||
|
else totalSlots += SlotsFor(item, n);
|
||||||
|
totalCost += EstimateCost(v, item, n);
|
||||||
|
|
||||||
|
if (want.Amount > n)
|
||||||
|
break; // couldn't take all of it: don't reach for the next item
|
||||||
|
}
|
||||||
|
else if (buys.Count > 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (buys.Count > 0)
|
||||||
|
return new VendorPlan { Kind = PlanKind.Buy, Buys = buys, Total = totalCost };
|
||||||
|
|
||||||
|
// ── Then sell ──
|
||||||
|
// nextBuy: the item we want but couldn't afford (notes are sold only to pay for it).
|
||||||
|
// An alt-currency vendor isn't paid in pyreals, so selling can't fund its items.
|
||||||
|
Listing? nextBuy = !v.UsesAltCurrency && wants.Count > 0 ? wants[0].Item : null;
|
||||||
|
|
||||||
|
var chosen = new List<SellItem>();
|
||||||
|
long totalValue = 0;
|
||||||
|
for (int i = 0; i < sells.Count && chosen.Count < MaxSellLines; i++)
|
||||||
|
{
|
||||||
|
SellItem item = sells[i];
|
||||||
|
int stack = Math.Max(1, item.StackSize);
|
||||||
|
long stackPayout = VendorPays(v, item.IsNote, item.Value);
|
||||||
|
double unit = (double)stackPayout / stack;
|
||||||
|
|
||||||
|
// Never sell notes to buy notes, and never sell notes when there's nothing to buy.
|
||||||
|
if (item.IsNote && (nextBuy == null || nextBuy.IsNote))
|
||||||
|
break;
|
||||||
|
|
||||||
|
// Selling notes to afford something: one note at a time, and only on its own.
|
||||||
|
if (nextBuy != null && item.IsNote)
|
||||||
|
{
|
||||||
|
if (chosen.Count > 0) break;
|
||||||
|
if (!PyrealsFit(p, unit))
|
||||||
|
return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}");
|
||||||
|
|
||||||
|
SellItem? single = null;
|
||||||
|
foreach (var s in sells)
|
||||||
|
if (s.IsNote && s.StackSize <= 1 && string.Equals(s.Name, item.Name, StringComparison.Ordinal))
|
||||||
|
{ single = s; break; }
|
||||||
|
if (single != null)
|
||||||
|
return new VendorPlan { Kind = PlanKind.Sell, Sells = new List<SellItem> { single }, Total = VendorPays(v, true, single.Value) };
|
||||||
|
|
||||||
|
return VendorPlan.Split(item, 1, $"one {item.Name} to afford {nextBuy.Name}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Can't sell the whole stack? Split off what the pyreals will fit.
|
||||||
|
if (!PyrealsFit(p, totalValue + stackPayout))
|
||||||
|
{
|
||||||
|
if (chosen.Count < 1)
|
||||||
|
{
|
||||||
|
int newStack = unit > 0 ? (int)Math.Floor((p.FreeMainSlots - 2) * (double)Math.Max(1, p.PyrealStackSize) / unit) : 0;
|
||||||
|
newStack = Math.Min(newStack, stack - 1);
|
||||||
|
if (newStack > 0)
|
||||||
|
return VendorPlan.Split(item, newStack, "the pyreals for the whole stack won't fit");
|
||||||
|
return VendorPlan.Fatal($"AutoVendor Fatal - No inventory room to sell {item.Name}");
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
chosen.Add(item);
|
||||||
|
totalValue += stackPayout;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (chosen.Count > 0)
|
||||||
|
return new VendorPlan { Kind = PlanKind.Sell, Sells = chosen, Total = totalValue };
|
||||||
|
|
||||||
|
return VendorPlan.Done();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── /ub vendor addsell (UB AddItemToSellList) ────────────────────────────
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whole stacks that fit in the remaining count are taken; if units are still missing,
|
||||||
|
/// the smallest stack bigger than what's missing is returned to be split.
|
||||||
|
/// </summary>
|
||||||
|
public static (List<SellItem> Whole, int Missing, SellItem? SplitFrom) PlanAddSell(IReadOnlyList<SellItem> matches, int count)
|
||||||
|
{
|
||||||
|
var whole = new List<SellItem>();
|
||||||
|
int needed = Math.Max(0, count);
|
||||||
|
SellItem? oversized = null;
|
||||||
|
foreach (var m in matches)
|
||||||
|
{
|
||||||
|
if (needed == 0) break;
|
||||||
|
int stack = Math.Max(1, m.StackSize);
|
||||||
|
if (stack <= needed)
|
||||||
|
{
|
||||||
|
whole.Add(m);
|
||||||
|
needed -= stack;
|
||||||
|
}
|
||||||
|
else if (oversized == null || oversized.StackSize > stack)
|
||||||
|
{
|
||||||
|
oversized = m;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (whole, needed, needed > 0 ? oversized : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Shared parsing ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// <summary>"[count] name" as UB's addbuy/addsell read it; count defaults to 1.</summary>
|
||||||
|
public static (int Count, string Name) ParseCountAndName(string args)
|
||||||
|
{
|
||||||
|
string s = (args ?? string.Empty).Trim();
|
||||||
|
int sp = s.IndexOf(' ');
|
||||||
|
if (sp > 0 && int.TryParse(s.Substring(0, sp), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
|
||||||
|
return (n, s.Substring(sp + 1).Trim());
|
||||||
|
return (1, s);
|
||||||
|
}
|
||||||
|
}
|
||||||
318
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs
vendored
Normal file
318
Plugins/RynthCore.Plugin.RynthAi/Vendor/AutoVendorRules.cs
vendored
Normal file
|
|
@ -0,0 +1,318 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using RynthCore.Loot;
|
||||||
|
using RynthCore.Loot.VTank;
|
||||||
|
|
||||||
|
namespace RynthCore.Plugin.RynthAi.Vendor;
|
||||||
|
|
||||||
|
// Pure rule judging for AutoVendor: no host, no WorldObject. The manager hands in a
|
||||||
|
// per-condition matcher (VTankLootEvaluator.MatchCondition) and the facts it has about
|
||||||
|
// the item; this file decides which conditions can be answered with that data and turns
|
||||||
|
// the answers into a profile verdict. Kept dependency-free so the test project can link it.
|
||||||
|
//
|
||||||
|
// Selling is destructive, so every answer is three-valued: Yes, No, or Unknown ("we don't
|
||||||
|
// have the data VTank would use"). A rule with an Unknown condition never counts as a
|
||||||
|
// match. UB leans on VTank's own evaluator; ours has approximations (buffed damage, colour
|
||||||
|
// similarity, base skill), and those node types always read Unknown here.
|
||||||
|
|
||||||
|
internal enum Tri : byte
|
||||||
|
{
|
||||||
|
No = 0,
|
||||||
|
Yes = 1,
|
||||||
|
Unknown = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the manager knows about an item before judging it.</summary>
|
||||||
|
internal readonly struct ItemFacts
|
||||||
|
{
|
||||||
|
/// <summary>An item on the vendor's list: only the engine's vendor snapshot is known.</summary>
|
||||||
|
public bool IsVendorListing { get; init; }
|
||||||
|
/// <summary>Inventory item with appraisal (ID) data.</summary>
|
||||||
|
public bool Appraised { get; init; }
|
||||||
|
public AcObjectClass ObjectClass { get; init; }
|
||||||
|
/// <summary>The item's spell list can be read (appraised and the host exposes spell ids).</summary>
|
||||||
|
public bool HasSpellData { get; init; }
|
||||||
|
public bool HasPalettes { get; init; }
|
||||||
|
public bool HasCharacterSkills { get; init; }
|
||||||
|
public bool HasCharacterLevel { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The profile's answer for one item.</summary>
|
||||||
|
internal sealed class ProfileVerdict
|
||||||
|
{
|
||||||
|
/// <summary>First rule that matched (Certain) or might match (!Certain); null = no rule can match.</summary>
|
||||||
|
public VTankLootRule? Rule { get; init; }
|
||||||
|
public int RuleIndex { get; init; } = -1;
|
||||||
|
/// <summary>True when Rule definitely matched, or when no rule can match at all.</summary>
|
||||||
|
public bool Certain { get; init; }
|
||||||
|
/// <summary>Some Keep / Keep # rule anywhere in the profile matches or might match.</summary>
|
||||||
|
public bool KeepPossible { get; init; }
|
||||||
|
/// <summary>Name of a Keep / Keep # rule that matches or might match (for messages).</summary>
|
||||||
|
public string KeepRuleName { get; init; } = string.Empty;
|
||||||
|
/// <summary>Why the deciding rule could not be judged (node type name), when !Certain.</summary>
|
||||||
|
public string UnknownReason { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public string RuleName => Rule == null ? string.Empty : AutoVendorRules.RuleLabel(Rule, RuleIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal enum BuyKind : byte
|
||||||
|
{
|
||||||
|
None = 0,
|
||||||
|
/// <summary>Keep: buy as many as you can afford.</summary>
|
||||||
|
Keep = 1,
|
||||||
|
/// <summary>Keep #: buy up to the rule's count.</summary>
|
||||||
|
KeepUpTo = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal readonly record struct BuyDecision(BuyKind Kind, int KeepCount, string RuleName);
|
||||||
|
|
||||||
|
internal readonly record struct SellDecision(bool Sell, string RuleName, string Reason);
|
||||||
|
|
||||||
|
internal static class AutoVendorRules
|
||||||
|
{
|
||||||
|
// STypeInt keys a vendor listing carries (engine VendorItem: ItemType, Burden,
|
||||||
|
// MaxStackSize, StackSize, Value). Anything else on a listing is unknown.
|
||||||
|
internal static readonly HashSet<int> ListingIntKeys = new() { 1, 5, 11, 12, 19 };
|
||||||
|
|
||||||
|
// Keys the client keeps in PublicWeenieDesc, readable without appraisal
|
||||||
|
// (items/containers capacity, locations, wielded location, stack sizes, material).
|
||||||
|
internal static readonly HashSet<int> PwdIntKeys = new() { 6, 7, 9, 10, 11, 12, 131 };
|
||||||
|
|
||||||
|
// Decal's synthetic LongValueKey ids start at 0x0D000000; RynthAi reads STypes only.
|
||||||
|
internal const int MaxStandardKey = 0xFFFF;
|
||||||
|
|
||||||
|
// RynthAi derives ObjectClass from ITEM_TYPE alone. Decal splits these further
|
||||||
|
// (Misc -> HealingKit/Lockpick, Book -> Scroll/Journal/Sign, Container -> Foci,
|
||||||
|
// Key -> Lockpick, Food -> Plant), so an ObjectClass test on them is unknown.
|
||||||
|
internal static readonly HashSet<AcObjectClass> CoarseClasses = new()
|
||||||
|
{
|
||||||
|
AcObjectClass.Unknown, AcObjectClass.Misc, AcObjectClass.Book,
|
||||||
|
AcObjectClass.Container, AcObjectClass.Food, AcObjectClass.Key,
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string RuleLabel(VTankLootRule rule, int index)
|
||||||
|
=> string.IsNullOrWhiteSpace(rule.Name) ? $"#{index}" : rule.Name.Trim();
|
||||||
|
|
||||||
|
/// <summary>Can this condition be answered for an item with these facts?</summary>
|
||||||
|
public static bool CanJudge(VTankLootCondition cond, in ItemFacts f)
|
||||||
|
{
|
||||||
|
var d = cond.DataLines;
|
||||||
|
switch (cond.NodeType)
|
||||||
|
{
|
||||||
|
case VTankNodeTypes.DisabledRule:
|
||||||
|
case VTankNodeTypes.DamagePercentGE: // VTank itself always answers "no"
|
||||||
|
case VTankNodeTypes.ObjectClass: // coarse classes handled in JudgeObjectClass
|
||||||
|
return true;
|
||||||
|
|
||||||
|
case VTankNodeTypes.CharacterMainPackEmptySlotsGE:
|
||||||
|
return true;
|
||||||
|
case VTankNodeTypes.CharacterSkillGE:
|
||||||
|
return f.HasCharacterSkills;
|
||||||
|
case VTankNodeTypes.CharacterLevelGE:
|
||||||
|
case VTankNodeTypes.CharacterLevelLE:
|
||||||
|
return f.HasCharacterLevel;
|
||||||
|
|
||||||
|
case VTankNodeTypes.StringValueMatch:
|
||||||
|
{
|
||||||
|
if (!TryKey(d, 1, out int key)) return false;
|
||||||
|
if (key == 1) return true; // Name
|
||||||
|
return !f.IsVendorListing && f.Appraised && key <= MaxStandardKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
case VTankNodeTypes.LongValKeyLE:
|
||||||
|
case VTankNodeTypes.LongValKeyGE:
|
||||||
|
case VTankNodeTypes.LongValKeyE:
|
||||||
|
case VTankNodeTypes.LongValKeyNE:
|
||||||
|
case VTankNodeTypes.LongValKeyFlagExists:
|
||||||
|
{
|
||||||
|
if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false;
|
||||||
|
if (f.IsVendorListing) return ListingIntKeys.Contains(key);
|
||||||
|
return f.Appraised || PwdIntKeys.Contains(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
case VTankNodeTypes.DoubleValKeyLE:
|
||||||
|
case VTankNodeTypes.DoubleValKeyGE:
|
||||||
|
{
|
||||||
|
if (!TryKey(d, 1, out int key) || key < 0 || key > MaxStandardKey) return false;
|
||||||
|
return !f.IsVendorListing && f.Appraised;
|
||||||
|
}
|
||||||
|
|
||||||
|
case VTankNodeTypes.SpellNameMatch:
|
||||||
|
case VTankNodeTypes.SpellMatch:
|
||||||
|
case VTankNodeTypes.SpellCountGE:
|
||||||
|
return !f.IsVendorListing && f.HasSpellData;
|
||||||
|
|
||||||
|
case VTankNodeTypes.SlotExactPalette:
|
||||||
|
return !f.IsVendorListing && f.HasPalettes;
|
||||||
|
|
||||||
|
case VTankNodeTypes.TotalRatingsGE:
|
||||||
|
return !f.IsVendorListing && f.Appraised;
|
||||||
|
|
||||||
|
// Approximated or not implemented by RynthAi's evaluator: never trusted.
|
||||||
|
case VTankNodeTypes.AnySimilarColor:
|
||||||
|
case VTankNodeTypes.SimilarColorArmorType:
|
||||||
|
case VTankNodeTypes.SlotSimilarColor:
|
||||||
|
case VTankNodeTypes.CharacterBaseSkill:
|
||||||
|
case VTankNodeTypes.MinDamageGE:
|
||||||
|
case VTankNodeTypes.BuffedMedianDamageGE:
|
||||||
|
case VTankNodeTypes.BuffedMissileDamageGE:
|
||||||
|
case VTankNodeTypes.BuffedLongValKeyGE:
|
||||||
|
case VTankNodeTypes.BuffedDoubleValKeyGE:
|
||||||
|
case VTankNodeTypes.CalcdBuffedTinkedDamageGE:
|
||||||
|
case VTankNodeTypes.CalcedBuffedTinkedTargetMeleeGE:
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>ObjectClass test without the evaluator: unknown for classes Decal splits further.</summary>
|
||||||
|
public static Tri JudgeObjectClass(VTankLootCondition cond, AcObjectClass itemClass)
|
||||||
|
{
|
||||||
|
if (!TryKey(cond.DataLines, 0, out int target)) return Tri.Unknown;
|
||||||
|
if (CoarseClasses.Contains(itemClass)) return Tri.Unknown;
|
||||||
|
return (int)itemClass == target ? Tri.Yes : Tri.No;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Judge one condition. <paramref name="match"/> is only called for conditions that
|
||||||
|
/// CanJudge says are answerable; if it throws (malformed data line) the answer is Unknown.
|
||||||
|
/// </summary>
|
||||||
|
public static Tri JudgeCondition(VTankLootCondition cond, in ItemFacts f, Func<VTankLootCondition, bool> match)
|
||||||
|
{
|
||||||
|
if (!CanJudge(cond, f)) return Tri.Unknown;
|
||||||
|
if (cond.NodeType == VTankNodeTypes.ObjectClass) return JudgeObjectClass(cond, f.ObjectClass);
|
||||||
|
try { return match(cond) ? Tri.Yes : Tri.No; }
|
||||||
|
catch { return Tri.Unknown; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>All conditions must hold: any No -> No, else any Unknown -> Unknown, else Yes.</summary>
|
||||||
|
public static Tri JudgeRule(VTankLootRule rule, Func<VTankLootCondition, Tri> cond, out string unknownReason)
|
||||||
|
{
|
||||||
|
unknownReason = string.Empty;
|
||||||
|
if (rule.Conditions.Count == 0) return Tri.Yes;
|
||||||
|
bool unknown = false;
|
||||||
|
foreach (var c in rule.Conditions)
|
||||||
|
{
|
||||||
|
Tri t = cond(c);
|
||||||
|
if (t == Tri.No) { unknownReason = string.Empty; return Tri.No; }
|
||||||
|
if (t == Tri.Unknown && !unknown)
|
||||||
|
{
|
||||||
|
unknown = true;
|
||||||
|
unknownReason = VTankNodeTypes.DisplayName(c.NodeType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return unknown ? Tri.Unknown : Tri.Yes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// VTank order: the first rule that matches decides. A rule that might match stops the
|
||||||
|
/// scan too (we can't know whether it or a later rule applies). Also records whether
|
||||||
|
/// any Keep / Keep # rule anywhere could match, which AutoVendor treats as "never sell".
|
||||||
|
/// </summary>
|
||||||
|
public static ProfileVerdict Decide(IReadOnlyList<VTankLootRule> rules, Func<VTankLootCondition, Tri> cond)
|
||||||
|
{
|
||||||
|
VTankLootRule? decided = null;
|
||||||
|
int decidedIdx = -1;
|
||||||
|
bool certain = true;
|
||||||
|
string reason = string.Empty;
|
||||||
|
bool keepPossible = false;
|
||||||
|
string keepName = string.Empty;
|
||||||
|
|
||||||
|
for (int i = 0; i < rules.Count; i++)
|
||||||
|
{
|
||||||
|
var rule = rules[i];
|
||||||
|
bool isKeep = rule.Action is VTankLootAction.Keep or VTankLootAction.KeepUpTo;
|
||||||
|
if (decided != null && (!isKeep || keepPossible))
|
||||||
|
continue; // only still scanning for keep rules
|
||||||
|
|
||||||
|
Tri t = JudgeRule(rule, cond, out string why);
|
||||||
|
if (t == Tri.No) continue;
|
||||||
|
|
||||||
|
if (isKeep && !keepPossible)
|
||||||
|
{
|
||||||
|
keepPossible = true;
|
||||||
|
keepName = RuleLabel(rule, i);
|
||||||
|
}
|
||||||
|
if (decided == null)
|
||||||
|
{
|
||||||
|
decided = rule;
|
||||||
|
decidedIdx = i;
|
||||||
|
certain = t == Tri.Yes;
|
||||||
|
reason = why;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ProfileVerdict
|
||||||
|
{
|
||||||
|
Rule = decided,
|
||||||
|
RuleIndex = decidedIdx,
|
||||||
|
Certain = decided == null || certain,
|
||||||
|
UnknownReason = reason,
|
||||||
|
KeepPossible = keepPossible,
|
||||||
|
KeepRuleName = keepName,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// UB GetBuyItems for one vendor listing: Keep # buys up to the count, Keep buys all it
|
||||||
|
/// can afford. First match decides, as in VTank. A rule we can't judge (a listing carries
|
||||||
|
/// only name, type, value, stack and burden) is handled so we never buy more than VTank would:
|
||||||
|
/// an unjudgeable non-buy rule ends the scan with no purchase (it might be the one that
|
||||||
|
/// matches); an unjudgeable Keep / Keep # rule lets the scan go on, since either way the
|
||||||
|
/// item gets bought, and the smallest count seen is used.
|
||||||
|
/// </summary>
|
||||||
|
public static BuyDecision DecideBuy(IReadOnlyList<VTankLootRule> rules, Func<VTankLootCondition, Tri> cond)
|
||||||
|
{
|
||||||
|
long cap = long.MaxValue;
|
||||||
|
for (int i = 0; i < rules.Count; i++)
|
||||||
|
{
|
||||||
|
var rule = rules[i];
|
||||||
|
Tri t = JudgeRule(rule, cond, out _);
|
||||||
|
if (t == Tri.No) continue;
|
||||||
|
|
||||||
|
long count = rule.Action switch
|
||||||
|
{
|
||||||
|
VTankLootAction.KeepUpTo => Math.Max(0, rule.KeepCount ?? 0),
|
||||||
|
VTankLootAction.Keep => int.MaxValue,
|
||||||
|
_ => -1,
|
||||||
|
};
|
||||||
|
if (count < 0)
|
||||||
|
return new BuyDecision(BuyKind.None, 0, RuleLabel(rule, i)); // a non-buy rule matches or might
|
||||||
|
|
||||||
|
cap = Math.Min(cap, count);
|
||||||
|
if (t == Tri.Yes)
|
||||||
|
{
|
||||||
|
int n = (int)Math.Min(cap, int.MaxValue);
|
||||||
|
return n == int.MaxValue
|
||||||
|
? new BuyDecision(BuyKind.Keep, int.MaxValue, RuleLabel(rule, i))
|
||||||
|
: new BuyDecision(BuyKind.KeepUpTo, n, RuleLabel(rule, i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new BuyDecision(BuyKind.None, 0, string.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// UB GetSellItems (result.IsSell), stricter: the deciding rule must be a Sell rule that
|
||||||
|
/// definitely matched, and no Keep / Keep # rule anywhere in the profile may match or
|
||||||
|
/// possibly match the item.
|
||||||
|
/// </summary>
|
||||||
|
public static SellDecision JudgeSell(ProfileVerdict v)
|
||||||
|
{
|
||||||
|
if (v.Rule == null) return new SellDecision(false, string.Empty, "no rule matches");
|
||||||
|
if (v.Rule.Action != VTankLootAction.Sell)
|
||||||
|
return new SellDecision(false, v.RuleName, $"first rule is {v.Rule.Action}");
|
||||||
|
if (!v.Certain)
|
||||||
|
return new SellDecision(false, v.RuleName, $"rule '{v.RuleName}' needs {v.UnknownReason} data we don't have");
|
||||||
|
if (v.KeepPossible)
|
||||||
|
return new SellDecision(false, v.RuleName, $"also matches keep rule '{v.KeepRuleName}'");
|
||||||
|
return new SellDecision(true, v.RuleName, string.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryKey(IList<string> d, int idx, out int value)
|
||||||
|
{
|
||||||
|
value = 0;
|
||||||
|
return d != null && idx < d.Count
|
||||||
|
&& int.TryParse(d[idx].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
|
||||||
|
}
|
||||||
|
}
|
||||||
541
Tools/RynthCore.AutoVendorTests/Program.cs
Normal file
541
Tools/RynthCore.AutoVendorTests/Program.cs
Normal file
|
|
@ -0,0 +1,541 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using RynthCore.Loot;
|
||||||
|
using RynthCore.Loot.VTank;
|
||||||
|
using RynthCore.Plugin.RynthAi.Vendor;
|
||||||
|
|
||||||
|
namespace RynthCore.AutoVendorTests;
|
||||||
|
|
||||||
|
// Tests for AutoVendor's pure logic: three-valued rule judging, UB's buy-up-to-N math,
|
||||||
|
// one-transaction planning (buy first, sell second, notes, pyreal room, splits) and the
|
||||||
|
// "never sell" checks. Self-contained fixtures only; fails on zero assertions.
|
||||||
|
//
|
||||||
|
// Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||||
|
internal static class Program
|
||||||
|
{
|
||||||
|
private static int _asserts;
|
||||||
|
private static int _fails;
|
||||||
|
|
||||||
|
private static void Check(bool cond, string msg)
|
||||||
|
{
|
||||||
|
_asserts++;
|
||||||
|
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Eq<T>(T actual, T expected, string msg)
|
||||||
|
{
|
||||||
|
_asserts++;
|
||||||
|
if (!EqualityComparer<T>.Default.Equals(actual, expected))
|
||||||
|
{ _fails++; Console.WriteLine($" [FAIL] {msg}: expected <{expected}>, got <{actual}>"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Main()
|
||||||
|
{
|
||||||
|
Console.WriteLine("=== AutoVendor tests ===");
|
||||||
|
TestJudgeRule();
|
||||||
|
TestCanJudge();
|
||||||
|
TestObjectClass();
|
||||||
|
TestDecideAndSell();
|
||||||
|
TestDecideFromUtl();
|
||||||
|
TestJudgeBuy();
|
||||||
|
TestBuildBuyWants();
|
||||||
|
TestPlanBuy();
|
||||||
|
TestPlanSell();
|
||||||
|
TestPlanNotes();
|
||||||
|
TestPrices();
|
||||||
|
TestSafety();
|
||||||
|
TestVendorWillBuy();
|
||||||
|
TestAddSell();
|
||||||
|
TestParse();
|
||||||
|
|
||||||
|
Console.WriteLine($"\n{_asserts} assertions, {_fails} failed.");
|
||||||
|
if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; }
|
||||||
|
Console.WriteLine(_fails == 0 ? "ALL AUTOVENDOR TESTS PASSED." : $"{_fails} FAILURE(S).");
|
||||||
|
return _fails == 0 ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── helpers ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static VTankLootCondition Cond(int type, params string[] data) => new(type, "0", data);
|
||||||
|
|
||||||
|
private static VTankLootRule Rule(string name, VTankLootAction action, int? keep, params VTankLootCondition[] conds)
|
||||||
|
=> new() { Name = name, Action = action, KeepCount = keep, Conditions = conds.ToList() };
|
||||||
|
|
||||||
|
private static Func<VTankLootCondition, Tri> Fixed(params Tri[] answers)
|
||||||
|
{
|
||||||
|
int i = 0;
|
||||||
|
return _ => answers[i++ % answers.Length];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A stand-in for VTankLootEvaluator: name regex (key 1), long equality, disabled flag.</summary>
|
||||||
|
private static bool FakeMatch(VTankLootCondition c, string name, Dictionary<int, int> ints)
|
||||||
|
{
|
||||||
|
var d = c.DataLines;
|
||||||
|
return c.NodeType switch
|
||||||
|
{
|
||||||
|
VTankNodeTypes.StringValueMatch => Regex.IsMatch(name, d[0], RegexOptions.IgnoreCase),
|
||||||
|
VTankNodeTypes.LongValKeyE => ints.TryGetValue(int.Parse(d[1], CultureInfo.InvariantCulture), out int v)
|
||||||
|
&& v == int.Parse(d[0], CultureInfo.InvariantCulture),
|
||||||
|
VTankNodeTypes.DisabledRule => !string.Equals(d[0].Trim(), "true", StringComparison.OrdinalIgnoreCase),
|
||||||
|
_ => throw new InvalidOperationException("fake matcher: unsupported node"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Func<VTankLootCondition, Tri> JudgeFake(ItemFacts f, string name, Dictionary<int, int>? ints = null)
|
||||||
|
{
|
||||||
|
ints ??= new Dictionary<int, int>();
|
||||||
|
return c => AutoVendorRules.JudgeCondition(c, f, cc => FakeMatch(cc, name, ints));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly ItemFacts AppraisedSalvage = new() { Appraised = true, ObjectClass = AcObjectClass.Salvage, HasCharacterSkills = true, HasCharacterLevel = true };
|
||||||
|
private static readonly ItemFacts ListingComp = new() { IsVendorListing = true, ObjectClass = AcObjectClass.SpellComponent, HasCharacterSkills = true, HasCharacterLevel = true };
|
||||||
|
|
||||||
|
private static VendorView Vendor(float buy = 0.5f, float sell = 1.5f, uint types = 0xFFFFFFFF, int maxValue = 50000, bool alt = false)
|
||||||
|
=> new() { Id = 1, Name = "Test Vendor", BuyRate = buy, SellRate = sell, ItemTypes = types, MaxValue = maxValue, UsesAltCurrency = alt };
|
||||||
|
|
||||||
|
private static Listing L(uint id, string name, int unitPrice, int value = 10, int maxStack = 1, int amount = -1,
|
||||||
|
AcObjectClass cls = AcObjectClass.SpellComponent, uint type = 0x1000, bool packSlot = false)
|
||||||
|
=> new() { Id = id, Name = name, UnitPrice = unitPrice, Value = value, MaxStackSize = maxStack, Amount = amount, Class = cls, ItemType = type, NeedsContainerSlot = packSlot };
|
||||||
|
|
||||||
|
private static SellItem S(uint id, string name, int value, int stack = 1, AcObjectClass cls = AcObjectClass.Salvage, uint type = 0x40000000)
|
||||||
|
=> new() { Id = id, Name = name, Value = value, StackSize = stack, Class = cls, ItemType = type, RuleName = "S" };
|
||||||
|
|
||||||
|
private static PackState Pack(long funds, int free = 50, int freePacks = 2, int pyrealStack = 25000)
|
||||||
|
=> new() { Funds = funds, FreeMainSlots = free, FreeContainerSlots = freePacks, PyrealStackSize = pyrealStack };
|
||||||
|
|
||||||
|
// ── rules ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static void TestJudgeRule()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- JudgeRule --");
|
||||||
|
var r2 = Rule("r", VTankLootAction.Sell, null, Cond(1, "x", "1"), Cond(1, "y", "1"));
|
||||||
|
Eq(AutoVendorRules.JudgeRule(r2, Fixed(Tri.Yes, Tri.Yes), out _), Tri.Yes, "yes+yes");
|
||||||
|
Eq(AutoVendorRules.JudgeRule(r2, Fixed(Tri.Yes, Tri.Unknown), out string why), Tri.Unknown, "yes+unknown");
|
||||||
|
Eq(why, VTankNodeTypes.DisplayName(1), "unknown reason names the node type");
|
||||||
|
Eq(AutoVendorRules.JudgeRule(r2, Fixed(Tri.Unknown, Tri.No), out _), Tri.No, "unknown+no = no (AND)");
|
||||||
|
Eq(AutoVendorRules.JudgeRule(Rule("empty", VTankLootAction.Sell, null), Fixed(Tri.No), out _), Tri.Yes, "no conditions = unconditional");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestCanJudge()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- CanJudge --");
|
||||||
|
Check(AutoVendorRules.CanJudge(Cond(1, "Taper", "1"), ListingComp), "listing: name match");
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(1, "x", "16"), ListingComp), "listing: other string key unknown");
|
||||||
|
Check(AutoVendorRules.CanJudge(Cond(12, "250000", "19"), ListingComp), "listing: Value");
|
||||||
|
Check(AutoVendorRules.CanJudge(Cond(3, "5", "12"), ListingComp), "listing: StackSize");
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(12, "6", "131"), ListingComp), "listing: Material unknown");
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(0, "Blood"), ListingComp), "listing: spell name unknown");
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(5, "0.5", "22"), ListingComp), "listing: double unknown");
|
||||||
|
|
||||||
|
Check(AutoVendorRules.CanJudge(Cond(12, "6", "131"), AppraisedSalvage), "appraised: Material");
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(12, "6", "218103842"), AppraisedSalvage), "Decal synthetic key unknown");
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(0, "Blood"), AppraisedSalvage), "spells need spell data");
|
||||||
|
Check(AutoVendorRules.CanJudge(Cond(0, "Blood"), AppraisedSalvage with { HasSpellData = true }), "spells with data");
|
||||||
|
|
||||||
|
var unappraised = AppraisedSalvage with { Appraised = false };
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(12, "250", "19"), unappraised), "unappraised: Value unknown");
|
||||||
|
Check(AutoVendorRules.CanJudge(Cond(12, "6", "131"), unappraised), "unappraised: Material is in PWD");
|
||||||
|
Check(AutoVendorRules.CanJudge(Cond(1, "x", "1"), unappraised), "unappraised: name");
|
||||||
|
|
||||||
|
foreach (int t in new[] { 10, 14, 15, 16, 1004, 2000, 2001, 2003, 2005, 2006, 2008, 424242 })
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(t, "0", "0", "0", "0", "0", "0"), AppraisedSalvage with { HasSpellData = true, HasPalettes = true }), $"approximated/unknown node {t} never judged");
|
||||||
|
|
||||||
|
Check(!AutoVendorRules.CanJudge(Cond(1000, "200", "39"), AppraisedSalvage with { HasCharacterSkills = false }), "skill needs skill reads");
|
||||||
|
Check(AutoVendorRules.CanJudge(Cond(9999, "false"), ListingComp), "disabled flag");
|
||||||
|
|
||||||
|
// A matcher that throws (malformed line) reads as Unknown, not No.
|
||||||
|
Eq(AutoVendorRules.JudgeCondition(Cond(1, "x", "1"), ListingComp, _ => throw new FormatException()), Tri.Unknown, "throwing matcher = unknown");
|
||||||
|
Eq(AutoVendorRules.JudgeCondition(Cond(12, "abc", "notakey"), AppraisedSalvage, _ => true), Tri.Unknown, "unparseable key = unknown");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestObjectClass()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- ObjectClass --");
|
||||||
|
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "39"), AcObjectClass.Salvage), Tri.Yes, "salvage = salvage");
|
||||||
|
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "12"), AcObjectClass.Salvage), Tri.No, "salvage != comps");
|
||||||
|
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "29"), AcObjectClass.Misc), Tri.Unknown, "Misc may be a healing kit");
|
||||||
|
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "8"), AcObjectClass.Misc), Tri.Unknown, "Misc vs Misc still unknown");
|
||||||
|
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "42"), AcObjectClass.Book), Tri.Unknown, "Book may be a scroll");
|
||||||
|
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "38"), AcObjectClass.Container), Tri.Unknown, "Container may be a focus");
|
||||||
|
Eq(AutoVendorRules.JudgeObjectClass(Cond(7, "15"), AcObjectClass.TradeNote), Tri.Yes, "trade note");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestDecideAndSell()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- Decide / JudgeSell --");
|
||||||
|
var keepGranite = Rule("K: Granite", VTankLootAction.Keep, null, Cond(12, "67", "131"));
|
||||||
|
var sellSalvage = Rule("S: Salvage", VTankLootAction.Sell, null, Cond(1, "Salvage", "1"));
|
||||||
|
var rules = new List<VTankLootRule> { keepGranite, sellSalvage };
|
||||||
|
|
||||||
|
var granite = new Dictionary<int, int> { [131] = 67 };
|
||||||
|
var steel = new Dictionary<int, int> { [131] = 64 };
|
||||||
|
|
||||||
|
var v1 = AutoVendorRules.Decide(rules, JudgeFake(AppraisedSalvage, "Salvage (100)", granite));
|
||||||
|
Eq(v1.Rule?.Name, "K: Granite", "granite: keep rule decides");
|
||||||
|
Check(!AutoVendorRules.JudgeSell(v1).Sell, "granite not sold");
|
||||||
|
|
||||||
|
var v2 = AutoVendorRules.Decide(rules, JudgeFake(AppraisedSalvage, "Salvage (100)", steel));
|
||||||
|
Eq(v2.Rule?.Name, "S: Salvage", "steel: sell rule decides");
|
||||||
|
Check(v2.Certain && !v2.KeepPossible, "steel: certain, no keep");
|
||||||
|
Check(AutoVendorRules.JudgeSell(v2).Sell, "steel sold");
|
||||||
|
|
||||||
|
// Sell rule first, keep rule later: UB (first match) would sell; we don't.
|
||||||
|
var sellFirst = new List<VTankLootRule> { sellSalvage, keepGranite };
|
||||||
|
var v3 = AutoVendorRules.Decide(sellFirst, JudgeFake(AppraisedSalvage, "Salvage (100)", granite));
|
||||||
|
Eq(v3.Rule?.Name, "S: Salvage", "sell-first: sell rule decides");
|
||||||
|
Check(v3.KeepPossible, "sell-first: later keep rule noticed");
|
||||||
|
var sd3 = AutoVendorRules.JudgeSell(v3);
|
||||||
|
Check(!sd3.Sell && sd3.Reason.Contains("K: Granite"), "sell-first: held back by keep rule");
|
||||||
|
|
||||||
|
// A keep rule we can't judge also blocks selling.
|
||||||
|
var keepBuffed = Rule("K: Good weapons", VTankLootAction.Keep, null, Cond(2003, "50", "160"));
|
||||||
|
var v4 = AutoVendorRules.Decide(new List<VTankLootRule> { keepBuffed, sellSalvage }, JudgeFake(AppraisedSalvage, "Salvage (100)", steel));
|
||||||
|
Check(v4.Rule == keepBuffed && !v4.Certain, "unjudgeable keep rule stops the scan");
|
||||||
|
Check(!AutoVendorRules.JudgeSell(v4).Sell, "not sold behind an unjudgeable keep rule");
|
||||||
|
|
||||||
|
// A sell rule we can't judge never sells.
|
||||||
|
var sellBuffed = Rule("S: Weak weapons", VTankLootAction.Sell, null, Cond(2003, "10", "160"));
|
||||||
|
var v5 = AutoVendorRules.Decide(new List<VTankLootRule> { sellBuffed }, JudgeFake(AppraisedSalvage, "Sword", steel));
|
||||||
|
Check(!v5.Certain && !AutoVendorRules.JudgeSell(v5).Sell, "unjudgeable sell rule never sells");
|
||||||
|
|
||||||
|
// Disabled rules are skipped.
|
||||||
|
var disabledKeep = Rule("K: off", VTankLootAction.Keep, null, Cond(1, "Salvage", "1"), Cond(9999, "true"));
|
||||||
|
var v6 = AutoVendorRules.Decide(new List<VTankLootRule> { disabledKeep, sellSalvage }, JudgeFake(AppraisedSalvage, "Salvage (100)", steel));
|
||||||
|
Check(AutoVendorRules.JudgeSell(v6).Sell, "disabled keep rule doesn't protect");
|
||||||
|
|
||||||
|
var none = AutoVendorRules.Decide(rules, JudgeFake(AppraisedSalvage, "Sword", steel));
|
||||||
|
Check(none.Rule == null && none.Certain, "no rule matches");
|
||||||
|
Check(!AutoVendorRules.JudgeSell(none).Sell, "unmatched not sold");
|
||||||
|
}
|
||||||
|
|
||||||
|
private const string FixtureUtl =
|
||||||
|
"UTL\n1\n5\n" +
|
||||||
|
"K: Granite\n\n0;1;12\n9\n67\n131\n" +
|
||||||
|
"Taper stock\n\n0;10;7;1\n100\n4\n12\n20\nPrismatic Taper\n1\n" +
|
||||||
|
"S: Salvage\n\n0;3;7\n4\n39\n" +
|
||||||
|
"S: Peas\n\n0;3;1\n19\nLead Pea|Copper Pea\n1\n" +
|
||||||
|
"S: Buffed\n\n0;3;2003\n3\n50\n160\n";
|
||||||
|
|
||||||
|
private static void TestDecideFromUtl()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- Decide from a parsed .utl --");
|
||||||
|
var profile = VTankLootParser.LoadFromText(FixtureUtl);
|
||||||
|
Eq(profile.Rules.Count, 5, "rule count");
|
||||||
|
Eq(profile.Rules[1].Action, VTankLootAction.KeepUpTo, "keep # action");
|
||||||
|
Eq(profile.Rules[1].KeepCount, 100, "keep # count");
|
||||||
|
|
||||||
|
// "K: Granite" (Material) can't be judged on a listing, but it's a keep rule: either
|
||||||
|
// way the taper is bought, at the taper rule's count.
|
||||||
|
var buy = AutoVendorRules.DecideBuy(profile.Rules, JudgeFake(ListingComp, "Prismatic Taper"));
|
||||||
|
Eq(buy.Kind, BuyKind.KeepUpTo, "taper listing: keep #");
|
||||||
|
Eq(buy.KeepCount, 100, "taper listing: count");
|
||||||
|
Eq(buy.RuleName, "Taper stock", "taper listing: rule");
|
||||||
|
var peaListing = AutoVendorRules.DecideBuy(profile.Rules, JudgeFake(ListingComp, "Lead Pea"));
|
||||||
|
Eq(peaListing.Kind, BuyKind.None, "pea listing: a sell rule, not bought");
|
||||||
|
|
||||||
|
var pea = AutoVendorRules.Decide(profile.Rules, JudgeFake(ListingComp with { IsVendorListing = false, Appraised = true }, "Copper Pea"));
|
||||||
|
Check(AutoVendorRules.JudgeSell(pea).Sell, "copper pea sold");
|
||||||
|
|
||||||
|
var sword = AutoVendorRules.Decide(profile.Rules, JudgeFake(AppraisedSalvage with { ObjectClass = AcObjectClass.MeleeWeapon }, "Sword"));
|
||||||
|
Eq(sword.Rule?.Name, "S: Buffed", "sword falls to the buffed rule");
|
||||||
|
Check(!sword.Certain && !AutoVendorRules.JudgeSell(sword).Sell, "buffed rule unjudged: sword kept");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestJudgeBuy()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- JudgeBuy --");
|
||||||
|
var keepAll = Rule("B: notes", VTankLootAction.Keep, null);
|
||||||
|
var all = AutoVendorRules.DecideBuy(new List<VTankLootRule> { keepAll }, Fixed(Tri.Yes));
|
||||||
|
Eq(all.Kind, BuyKind.Keep, "keep = buy all");
|
||||||
|
Eq(all.KeepCount, int.MaxValue, "keep amount");
|
||||||
|
|
||||||
|
var keep5 = Rule("u", VTankLootAction.KeepUpTo, 5, Cond(0, "x"));
|
||||||
|
Eq(AutoVendorRules.DecideBuy(new List<VTankLootRule> { keep5 }, Fixed(Tri.Unknown)).Kind, BuyKind.None, "only an unjudgeable rule: not bought");
|
||||||
|
|
||||||
|
var sell = Rule("s", VTankLootAction.Sell, null, Cond(0, "x"));
|
||||||
|
Eq(AutoVendorRules.DecideBuy(new List<VTankLootRule> { sell }, Fixed(Tri.Yes)).Kind, BuyKind.None, "sell rule never buys");
|
||||||
|
|
||||||
|
// An unjudgeable SELL rule ahead of a keep rule might be the match: don't buy.
|
||||||
|
var keep100 = Rule("k100", VTankLootAction.KeepUpTo, 100, Cond(1, "x", "1"));
|
||||||
|
Eq(AutoVendorRules.DecideBuy(new List<VTankLootRule> { sell, keep100 }, Fixed(Tri.Unknown, Tri.Yes)).Kind, BuyKind.None, "unjudgeable sell rule first: no buy");
|
||||||
|
|
||||||
|
// Unjudgeable keep rules ahead: buy, at the smallest count seen.
|
||||||
|
var r = AutoVendorRules.DecideBuy(new List<VTankLootRule> { keep5, keep100 }, Fixed(Tri.Unknown, Tri.Yes));
|
||||||
|
Eq(r.Kind, BuyKind.KeepUpTo, "unjudgeable keep # then keep #");
|
||||||
|
Eq(r.KeepCount, 5, "smallest count");
|
||||||
|
var keepAllIf = Rule("all?", VTankLootAction.Keep, null, Cond(0, "x"));
|
||||||
|
var r2 = AutoVendorRules.DecideBuy(new List<VTankLootRule> { keepAllIf, keep100 }, Fixed(Tri.Unknown, Tri.Yes));
|
||||||
|
Eq(r2.Kind, BuyKind.KeepUpTo, "unjudgeable keep-all then keep #: capped");
|
||||||
|
Eq(r2.KeepCount, 100, "keep # count");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── buy-up-to-N ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private static void TestBuildBuyWants()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- BuildBuyWants --");
|
||||||
|
var v = Vendor();
|
||||||
|
var taper = L(10, "Prismatic Taper", 5);
|
||||||
|
var scarab = L(11, "Mana Scarab", 40);
|
||||||
|
var note = L(12, "Trade Note (250,000)", 287500, 250000, cls: AcObjectClass.TradeNote, type: 0x40000);
|
||||||
|
var packA = L(13, "Pack", 100, cls: AcObjectClass.Container, type: 0x200, packSlot: true);
|
||||||
|
var packB = L(14, "Bag", 50, cls: AcObjectClass.Container, type: 0x200, packSlot: true);
|
||||||
|
|
||||||
|
var have = new Dictionary<string, int> { ["Prismatic Taper"] = 250, ["Mana Scarab"] = 60 };
|
||||||
|
var judged = new List<(Listing, BuyDecision)>
|
||||||
|
{
|
||||||
|
(note, new BuyDecision(BuyKind.Keep, int.MaxValue, "B: notes")),
|
||||||
|
(taper, new BuyDecision(BuyKind.KeepUpTo, 1000, "B: tapers")),
|
||||||
|
(scarab, new BuyDecision(BuyKind.KeepUpTo, 50, "B: scarabs")), // have 60 >= 50
|
||||||
|
(packA, new BuyDecision(BuyKind.KeepUpTo, 3, "B: packs")),
|
||||||
|
(packB, new BuyDecision(BuyKind.KeepUpTo, 5, "B: bags")), // second container rule ignored
|
||||||
|
};
|
||||||
|
var wants = AutoVendorPlanner.BuildBuyWants(v, judged, n => have.TryGetValue(n, out int c) ? c : 0, c => c == AcObjectClass.Container ? 2 : 0);
|
||||||
|
|
||||||
|
Eq(wants.Count, 3, "tapers + one pack rule + notes");
|
||||||
|
Eq(wants[0].Item.Name, "Prismatic Taper", "cheapest first");
|
||||||
|
Eq(wants[0].Amount, 750, "keep # 1000 with 250 held = 750");
|
||||||
|
Eq(wants[1].Item.Name, "Pack", "first container rule");
|
||||||
|
Eq(wants[1].Amount, 1, "packs: 3 wanted, 2 containers held");
|
||||||
|
Eq(wants[2].Item.Name, "Trade Note (250,000)", "notes last");
|
||||||
|
Eq(wants[2].Amount, int.MaxValue, "keep = all");
|
||||||
|
Check(!wants.Any(w => w.Item.Name == "Mana Scarab"), "scarabs already stocked");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestPlanBuy()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- PlanNext (buy) --");
|
||||||
|
var v = Vendor(sell: 1.0f);
|
||||||
|
var taper = L(10, "Prismatic Taper", 10, value: 10, maxStack: 5000);
|
||||||
|
var want = new List<BuyWant> { new() { Item = taper, Amount = 750, RuleName = "t" } };
|
||||||
|
|
||||||
|
var p1 = AutoVendorPlanner.PlanNext(v, want, new List<SellItem>(), Pack(100_000));
|
||||||
|
Eq(p1.Kind, PlanKind.Buy, "buys");
|
||||||
|
Eq(p1.Buys.Single().Amount, 750, "all 750 affordable");
|
||||||
|
|
||||||
|
var p2 = AutoVendorPlanner.PlanNext(v, want, new List<SellItem>(), Pack(1_005));
|
||||||
|
Eq(p2.Buys.Single().Amount, 100, "funds limit: 1005 / 10 = 100");
|
||||||
|
Check(p2.Total <= 1_005, "estimated cost within funds");
|
||||||
|
|
||||||
|
var big = new List<BuyWant> { new() { Item = taper, Amount = int.MaxValue } };
|
||||||
|
var p3 = AutoVendorPlanner.PlanNext(v, big, new List<SellItem>(), Pack(10_000_000));
|
||||||
|
Eq(p3.Buys.Single().Amount, AutoVendorPlanner.MaxVendorBuyCount, "5000 per transaction");
|
||||||
|
|
||||||
|
var limited = L(20, "Rare Thing", 10, value: 10, amount: 3);
|
||||||
|
var p4 = AutoVendorPlanner.PlanNext(v, new List<BuyWant> { new() { Item = limited, Amount = 10 } }, new List<SellItem>(), Pack(1_000));
|
||||||
|
Eq(p4.Buys.Single().Amount, 3, "limited listing: only what the vendor has");
|
||||||
|
|
||||||
|
// Slots: 500 units, stacks of 100, 3 free main slots -> 100 * (3 - 2) = 100.
|
||||||
|
var arrows = L(30, "Arrow", 1, value: 1, maxStack: 100);
|
||||||
|
var p5 = AutoVendorPlanner.PlanNext(v, new List<BuyWant> { new() { Item = arrows, Amount = 500 } }, new List<SellItem>(), Pack(1_000_000, free: 3));
|
||||||
|
Eq(p5.Buys.Single().Amount, 100, "slot limit keeps two free");
|
||||||
|
|
||||||
|
var p6 = AutoVendorPlanner.PlanNext(v, new List<BuyWant> { new() { Item = arrows, Amount = 5 } }, new List<SellItem>(), Pack(1_000_000, free: 1));
|
||||||
|
Eq(p6.Kind, PlanKind.Done, "one free slot: nothing bought (UB keeps one free)");
|
||||||
|
|
||||||
|
// Partial buy stops the batch: the second item waits for the next transaction.
|
||||||
|
var a = L(40, "A", 10, value: 1);
|
||||||
|
var b = L(41, "B", 10, value: 2);
|
||||||
|
var p7 = AutoVendorPlanner.PlanNext(v, new List<BuyWant> { new() { Item = a, Amount = 50 }, new() { Item = b, Amount = 5 } }, new List<SellItem>(), Pack(300));
|
||||||
|
Eq(p7.Buys.Count, 1, "partial A ends the batch");
|
||||||
|
Eq(p7.Buys[0].Amount, 30, "A limited by funds");
|
||||||
|
|
||||||
|
// An unaffordable first item is skipped while nothing is on the list.
|
||||||
|
var dear = L(50, "Dear", 1_000, value: 1);
|
||||||
|
var cheap = L(51, "Cheap", 10, value: 5);
|
||||||
|
var p8 = AutoVendorPlanner.PlanNext(v, new List<BuyWant> { new() { Item = dear, Amount = 1 }, new() { Item = cheap, Amount = 2 } }, new List<SellItem>(), Pack(100));
|
||||||
|
Eq(p8.Buys.Single().Item.Name, "Cheap", "skips the unaffordable item");
|
||||||
|
|
||||||
|
// Packs need a container slot, not a main-pack slot.
|
||||||
|
var pack = L(60, "Pack", 100, value: 50, cls: AcObjectClass.Container, type: 0x200, packSlot: true);
|
||||||
|
var p9 = AutoVendorPlanner.PlanNext(v, new List<BuyWant> { new() { Item = pack, Amount = 5 } }, new List<SellItem>(), Pack(10_000, free: 0, freePacks: 2));
|
||||||
|
Eq(p9.Buys.Single().Amount, 2, "packs limited by container slots");
|
||||||
|
|
||||||
|
var zero = L(70, "Broken", 0, value: 0);
|
||||||
|
var p10 = AutoVendorPlanner.PlanNext(v, new List<BuyWant> { new() { Item = zero, Amount = 1 } }, new List<SellItem>(), Pack(100));
|
||||||
|
Eq(p10.Kind, PlanKind.Fatal, "no price is fatal (UB)");
|
||||||
|
Check(p10.Message.StartsWith("AutoVendor Fatal - No vendor price found", StringComparison.Ordinal), "UB fatal text");
|
||||||
|
|
||||||
|
// Buying comes before selling.
|
||||||
|
var p11 = AutoVendorPlanner.PlanNext(v, want, new List<SellItem> { S(1, "Salvage", 100) }, Pack(100_000));
|
||||||
|
Eq(p11.Kind, PlanKind.Buy, "buy first");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestPlanSell()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- PlanNext (sell) --");
|
||||||
|
var v = Vendor(buy: 1.0f);
|
||||||
|
var none = new List<BuyWant>();
|
||||||
|
|
||||||
|
var sells = Enumerable.Range(1, 120).Select(i => S((uint)i, "Salvage", 100)).ToList();
|
||||||
|
var p1 = AutoVendorPlanner.PlanNext(v, none, sells, Pack(0, free: 50));
|
||||||
|
Eq(p1.Kind, PlanKind.Sell, "sells");
|
||||||
|
Eq(p1.Sells.Count, AutoVendorPlanner.MaxSellLines, "99 items per transaction");
|
||||||
|
|
||||||
|
// Pyreal room: 3 free slots, 25000 per stack; a 100-unit stack worth 1000 each won't fit.
|
||||||
|
var p2 = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { S(1, "Gem", 100_000, stack: 100) }, Pack(0, free: 3));
|
||||||
|
Eq(p2.Kind, PlanKind.Split, "split when the pyreals won't fit");
|
||||||
|
Eq(p2.SplitAmount, 25, "(3 - 2) * 25000 / 1000 = 25");
|
||||||
|
|
||||||
|
var p3 = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { S(1, "Gem", 100_000, stack: 100) }, Pack(0, free: 2));
|
||||||
|
Eq(p3.Kind, PlanKind.Fatal, "no room at all is fatal");
|
||||||
|
Check(p3.Message.Contains("No inventory room to sell Gem"), "UB fatal text");
|
||||||
|
|
||||||
|
// Later items that won't fit wait for the next batch.
|
||||||
|
var p4 = AutoVendorPlanner.PlanNext(v, none, new List<SellItem> { S(1, "A", 20_000), S(2, "B", 20_000), S(3, "C", 20_000) }, Pack(0, free: 3));
|
||||||
|
Eq(p4.Sells.Count, 2, "stop adding when the payout stops fitting");
|
||||||
|
|
||||||
|
var p5 = AutoVendorPlanner.PlanNext(v, none, new List<SellItem>(), Pack(0));
|
||||||
|
Eq(p5.Kind, PlanKind.Done, "nothing to do");
|
||||||
|
|
||||||
|
// Payout estimate uses the vendor's buy rate (ACE floor(value * rate + 0.1)).
|
||||||
|
var half = Vendor(buy: 0.5f);
|
||||||
|
var p6 = AutoVendorPlanner.PlanNext(half, none, new List<SellItem> { S(1, "Salvage", 101) }, Pack(0));
|
||||||
|
Eq(p6.Total, 50L, "floor(101 * 0.5 + 0.1)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestPlanNotes()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- PlanNext (trade notes) --");
|
||||||
|
var v = Vendor(buy: 0.5f);
|
||||||
|
SellItem Note(uint id, int stack) => S(id, "Trade Note (100)", 100 * stack, stack, AcObjectClass.TradeNote, 0x40000);
|
||||||
|
|
||||||
|
var sorted = AutoVendorPlanner.SortSells(v, new[] { Note(1, 3), S(2, "Salvage", 5000) });
|
||||||
|
Eq(sorted[0].Name, "Salvage", "notes sort last");
|
||||||
|
|
||||||
|
// Nothing to buy: notes are never sold.
|
||||||
|
var p1 = AutoVendorPlanner.PlanNext(v, new List<BuyWant>(), new List<SellItem> { Note(1, 3) }, Pack(0));
|
||||||
|
Eq(p1.Kind, PlanKind.Done, "notes kept when nothing to buy");
|
||||||
|
|
||||||
|
var dear = new List<BuyWant> { new() { Item = L(10, "Pack", 500, value: 400), Amount = 1 } };
|
||||||
|
// Want something unaffordable: split one note off a stack...
|
||||||
|
var p2 = AutoVendorPlanner.PlanNext(v, dear, new List<SellItem> { Note(1, 3) }, Pack(0));
|
||||||
|
Eq(p2.Kind, PlanKind.Split, "split one note");
|
||||||
|
Eq(p2.SplitAmount, 1, "one note");
|
||||||
|
// ...or sell a single note already on its own.
|
||||||
|
var p3 = AutoVendorPlanner.PlanNext(v, dear, new List<SellItem> { Note(1, 3), Note(2, 1) }, Pack(0));
|
||||||
|
Eq(p3.Kind, PlanKind.Sell, "sell the single note");
|
||||||
|
Eq(p3.Sells.Single().Id, 2u, "the single one");
|
||||||
|
Eq(p3.Total, 100L, "notes sell at face value");
|
||||||
|
|
||||||
|
// Other items go first; the note waits.
|
||||||
|
var p4 = AutoVendorPlanner.PlanNext(v, dear, new List<SellItem> { S(5, "Salvage", 100), Note(2, 1) }, Pack(0));
|
||||||
|
Eq(p4.Sells.Single().Id, 5u, "regular items before notes");
|
||||||
|
|
||||||
|
// Never sell notes to buy notes.
|
||||||
|
var noteWant = new List<BuyWant> { new() { Item = L(11, "Trade Note (250,000)", 287500, 250000, cls: AcObjectClass.TradeNote, type: 0x40000), Amount = int.MaxValue } };
|
||||||
|
var p5 = AutoVendorPlanner.PlanNext(v, noteWant, new List<SellItem> { Note(2, 1) }, Pack(0));
|
||||||
|
Eq(p5.Kind, PlanKind.Done, "no notes for notes");
|
||||||
|
|
||||||
|
// An alt-currency vendor isn't paid in pyreals: selling notes can't help.
|
||||||
|
var alt = Vendor(buy: 0.5f, alt: true);
|
||||||
|
var p6 = AutoVendorPlanner.PlanNext(alt, dear, new List<SellItem> { Note(2, 1) }, Pack(0));
|
||||||
|
Eq(p6.Kind, PlanKind.Done, "alt currency: notes kept");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestPrices()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- prices --");
|
||||||
|
var v = Vendor(buy: 0.5f, sell: 1.5f);
|
||||||
|
Eq(AutoVendorPlanner.PlayerPays(v, false, 10), 15L, "ceil(10 * 1.5 - 0.1)");
|
||||||
|
Eq(AutoVendorPlanner.PlayerPays(v, true, 100), 115L, "notes cost 1.15x");
|
||||||
|
Eq(AutoVendorPlanner.PlayerPays(v, false, 0), 1L, "at least 1");
|
||||||
|
Eq(AutoVendorPlanner.VendorPays(v, false, 101), 50L, "floor(101 * 0.5 + 0.1)");
|
||||||
|
Eq(AutoVendorPlanner.VendorPays(v, true, 250000), 250000L, "notes pay face value");
|
||||||
|
|
||||||
|
var one = Vendor(sell: 1.0f);
|
||||||
|
var stackable = L(1, "Arrow", 0, value: 10, maxStack: 100);
|
||||||
|
Eq(AutoVendorPlanner.EstimateCost(one, stackable, 250), 2500L, "2 full stacks + a partial");
|
||||||
|
var limited = L(2, "Whole Lot", 0, value: 500, amount: 5);
|
||||||
|
Eq(AutoVendorPlanner.EstimateCost(one, limited, 1), 500L, "limited listing costs at least the listing");
|
||||||
|
Eq(AutoVendorPlanner.MostAffordable(one, limited, 5, 1200), 2, "most that fits 1200 at 500 each");
|
||||||
|
Eq(AutoVendorPlanner.MostAffordable(one, limited, 5, 499), 0, "can't afford one");
|
||||||
|
var lot = new Listing { Id = 9, Name = "Lot of 10", UnitPrice = 1, Value = 1000, StackSize = 10, MaxStackSize = 10, Amount = 10 };
|
||||||
|
// The per-unit price says 3 units cost 3, but ACE charges the whole listing (1000).
|
||||||
|
var p = AutoVendorPlanner.PlanNext(one, new List<BuyWant> { new() { Item = lot, Amount = 3 } }, new List<SellItem>(), Pack(500));
|
||||||
|
Eq(p.Kind, PlanKind.Done, "limited listing: whole-listing price over funds, nothing bought");
|
||||||
|
Eq(AutoVendorPlanner.UnitPrice(v, L(3, "X", 0, value: 10)), 15L, "unit price falls back to the rate");
|
||||||
|
Eq(AutoVendorPlanner.UnitPrice(v, L(4, "Y", 7, value: 10)), 7L, "engine unit price wins");
|
||||||
|
|
||||||
|
Check(AutoVendorPlanner.PyrealsFit(Pack(0, free: 2), 25_000), "one stack, two free slots");
|
||||||
|
Check(!AutoVendorPlanner.PyrealsFit(Pack(0, free: 1), 1), "one free slot is kept");
|
||||||
|
Eq(AutoVendorPlanner.SlotsFor(stackable, 250), 3, "250 arrows = 3 slots");
|
||||||
|
Eq(AutoVendorPlanner.CategoryName(0x1000), "Spell Components", "category");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestSafety()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- never-sell checks --");
|
||||||
|
var ok = new SafetyFacts { Appraised = true, Class = AcObjectClass.Salvage, Value = 100, InMainPack = true };
|
||||||
|
Eq(AutoVendorPlanner.UnsafeReason(ok, false), null, "plain item is sellable");
|
||||||
|
|
||||||
|
(SafetyFacts, string)[] cases =
|
||||||
|
{
|
||||||
|
(new SafetyFacts { Appraised = false, Value = 100 }, "not identified"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Equipped = true }, "equipped"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 0 }, "no value"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, CanBeSold = false }, "not sellable"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, IsRare = true }, "rare"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Attuned = 1 }, "attuned"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Bonded = 1 }, "bonded"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Retained = true }, "retained"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, TimesTinkered = 1 }, "tinkered"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Imbued = 1 }, "imbued"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Inscription = "mine" }, "inscribed"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Class = AcObjectClass.Container }, "container"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, HoldsItems = true }, "container"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Class = AcObjectClass.Foci }, "focus"),
|
||||||
|
(new SafetyFacts { Appraised = true, Value = 100, Class = AcObjectClass.Money }, "money"),
|
||||||
|
};
|
||||||
|
foreach (var (f, why) in cases)
|
||||||
|
Eq(AutoVendorPlanner.UnsafeReason(f, false), why, $"never sell: {why}");
|
||||||
|
|
||||||
|
var side = new SafetyFacts { Appraised = true, Class = AcObjectClass.Salvage, Value = 100, InMainPack = false };
|
||||||
|
Eq(AutoVendorPlanner.UnsafeReason(side, false), null, "side pack ok by default");
|
||||||
|
Eq(AutoVendorPlanner.UnsafeReason(side, true), "not in main pack", "OnlyFromMainPack");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestVendorWillBuy()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- VendorWillBuy --");
|
||||||
|
var v = Vendor(types: 0x40000000 | 0x40000, maxValue: 1000);
|
||||||
|
Check(AutoVendorPlanner.VendorWillBuy(v, 0x40000000, false, 500), "salvage under the cap");
|
||||||
|
Check(!AutoVendorPlanner.VendorWillBuy(v, 0x40000000, false, 1500), "over MaxValue");
|
||||||
|
Check(!AutoVendorPlanner.VendorWillBuy(v, 0x1, false, 10), "type the vendor doesn't buy");
|
||||||
|
Check(AutoVendorPlanner.VendorWillBuy(v, 0x40000, true, 250000), "notes skip the cap");
|
||||||
|
Check(!AutoVendorPlanner.VendorWillBuy(Vendor(types: 0x40000000), 0x40000, true, 100), "notes still need the vendor's type (engine rule)");
|
||||||
|
Check(!AutoVendorPlanner.VendorWillBuy(Vendor(maxValue: 0), 0x1000, false, 1), "unknown MaxValue: don't sell");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestAddSell()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- addsell split planning --");
|
||||||
|
var stacks = new List<SellItem> { S(1, "Pea", 5, 5), S(2, "Pea", 3, 3), S(3, "Pea", 10, 10) };
|
||||||
|
|
||||||
|
var (w1, m1, s1) = AutoVendorPlanner.PlanAddSell(stacks, 8);
|
||||||
|
Eq(string.Join(",", w1.Select(x => x.Id)), "1,2", "5 + 3 = 8");
|
||||||
|
Eq(m1, 0, "nothing missing");
|
||||||
|
Check(s1 == null, "no split");
|
||||||
|
|
||||||
|
var (w2, m2, s2) = AutoVendorPlanner.PlanAddSell(stacks, 7);
|
||||||
|
Eq(string.Join(",", w2.Select(x => x.Id)), "1", "take 5");
|
||||||
|
Eq(m2, 2, "2 missing");
|
||||||
|
Eq(s2?.Id, 2u, "split the smallest bigger stack (3)");
|
||||||
|
|
||||||
|
var (w3, m3, s3) = AutoVendorPlanner.PlanAddSell(stacks, 30);
|
||||||
|
Eq(w3.Count, 3, "all stacks");
|
||||||
|
Eq(m3, 12, "12 missing");
|
||||||
|
Check(s3 == null, "nothing big enough to split");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestParse()
|
||||||
|
{
|
||||||
|
Console.WriteLine("\n-- parsing --");
|
||||||
|
Eq(AutoVendorPlanner.ParseCountAndName("10 Mana Scarab"), (10, "Mana Scarab"), "count + name");
|
||||||
|
Eq(AutoVendorPlanner.ParseCountAndName("Mana Scarab"), (1, "Mana Scarab"), "name only");
|
||||||
|
Eq(AutoVendorPlanner.ParseCountAndName(" 3 Lead Pea "), (3, "Lead Pea"), "extra spaces");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Unit tests for RynthAi's AutoVendor pure logic (rule judging, buy-up-to-N math,
|
||||||
|
batch planning, stack splits). The plugin itself is a NativeAOT x86 library, so the
|
||||||
|
two dependency-free source files are compiled in here directly instead of
|
||||||
|
referencing the plugin project.
|
||||||
|
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>RynthCore.AutoVendorTests</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\Shared\RynthCore.LootSdk\RynthCore.LootSdk.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Vendor\AutoVendorRules.cs" Link="Linked\AutoVendorRules.cs" />
|
||||||
|
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Vendor\AutoVendorPlanner.cs" Link="Linked\AutoVendorPlanner.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
|
|
@ -18,7 +18,7 @@ public partial class App : Application
|
||||||
};
|
};
|
||||||
|
|
||||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||||
desktop.MainWindow = new MainWindow();
|
desktop.MainWindow = new MainWindow(desktop.Args is { Length: > 0 } a ? a[0] : null);
|
||||||
base.OnFrameworkInitializationCompleted();
|
base.OnFrameworkInitializationCompleted();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,9 @@ namespace RynthCore.LootEditor;
|
||||||
public class MainViewModel : INotifyPropertyChanged
|
public class MainViewModel : INotifyPropertyChanged
|
||||||
{
|
{
|
||||||
private const string DefaultFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
private const string DefaultFolder = @"C:\Games\RynthSuite\RynthAi\LootProfiles";
|
||||||
|
// RynthAi's AutoVendor reads <Vendor Name>.utl / default.utl from here (and from
|
||||||
|
// AutoVendor folders per server and per character, which IsAutoVendorPath also covers).
|
||||||
|
private const string AutoVendorFolder = @"C:\Games\RynthSuite\RynthAi\AutoVendor";
|
||||||
|
|
||||||
public event PropertyChangedEventHandler? PropertyChanged;
|
public event PropertyChangedEventHandler? PropertyChanged;
|
||||||
private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
|
private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
|
||||||
|
|
@ -172,6 +175,42 @@ public class MainViewModel : INotifyPropertyChanged
|
||||||
{
|
{
|
||||||
string baseName = string.IsNullOrEmpty(_filePath) ? "untitled.utl" : Path.GetFileName(_filePath);
|
string baseName = string.IsNullOrEmpty(_filePath) ? "untitled.utl" : Path.GetFileName(_filePath);
|
||||||
WindowTitle = $"RynthCore Loot Editor — {baseName}{(_dirty ? "*" : "")}";
|
WindowTitle = $"RynthCore Loot Editor — {baseName}{(_dirty ? "*" : "")}";
|
||||||
|
|
||||||
|
// The folder switch follows the open file, so Save As lands next to it.
|
||||||
|
if (!string.IsNullOrEmpty(_filePath))
|
||||||
|
UseAutoVendorFolder = IsAutoVendorPath(_filePath);
|
||||||
|
Notify(nameof(IsAutoVendorProfile));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Profile folder (Loot / AutoVendor) ───────────────────────────────────
|
||||||
|
|
||||||
|
private bool _useAutoVendorFolder;
|
||||||
|
/// <summary>Open / Save start in the AutoVendor folder instead of LootProfiles.</summary>
|
||||||
|
public bool UseAutoVendorFolder
|
||||||
|
{
|
||||||
|
get => _useAutoVendorFolder;
|
||||||
|
set
|
||||||
|
{
|
||||||
|
Set(ref _useAutoVendorFolder, value);
|
||||||
|
Notify(nameof(UseLootFolder));
|
||||||
|
Notify(nameof(ProfileFolderHint));
|
||||||
|
Notify(nameof(IsAutoVendorProfile));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public bool UseLootFolder => !_useAutoVendorFolder;
|
||||||
|
public string ProfileFolderHint => $"Open and Save start in {(_useAutoVendorFolder ? AutoVendorFolder : DefaultFolder)}";
|
||||||
|
|
||||||
|
/// <summary>An AutoVendor profile is open (or, for an unsaved one, the AutoVendor folder is picked).</summary>
|
||||||
|
public bool IsAutoVendorProfile =>
|
||||||
|
string.IsNullOrEmpty(_filePath) ? _useAutoVendorFolder : IsAutoVendorPath(_filePath);
|
||||||
|
|
||||||
|
private static bool IsAutoVendorPath(string path)
|
||||||
|
{
|
||||||
|
string? dir = Path.GetDirectoryName(Path.GetFullPath(path));
|
||||||
|
for (; !string.IsNullOrEmpty(dir); dir = Path.GetDirectoryName(dir))
|
||||||
|
if (string.Equals(Path.GetFileName(dir), "AutoVendor", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Picker option lists ──────────────────────────────────────────────────
|
// ── Picker option lists ──────────────────────────────────────────────────
|
||||||
|
|
@ -207,6 +246,7 @@ public class MainViewModel : INotifyPropertyChanged
|
||||||
public RelayCommand RuleMoveUp { get; }
|
public RelayCommand RuleMoveUp { get; }
|
||||||
public RelayCommand RuleMoveDown { get; }
|
public RelayCommand RuleMoveDown { get; }
|
||||||
public RelayCommand SetActionFilter { get; }
|
public RelayCommand SetActionFilter { get; }
|
||||||
|
public RelayCommand SetProfileFolder { get; }
|
||||||
public RelayCommand CondAdd { get; }
|
public RelayCommand CondAdd { get; }
|
||||||
public RelayCommand CondDelete { get; }
|
public RelayCommand CondDelete { get; }
|
||||||
public RelayCommand CondMoveUp { get; }
|
public RelayCommand CondMoveUp { get; }
|
||||||
|
|
@ -239,6 +279,8 @@ public class MainViewModel : INotifyPropertyChanged
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
SetProfileFolder = new RelayCommand(arg =>
|
||||||
|
UseAutoVendorFolder = string.Equals(arg as string, "AutoVendor", StringComparison.OrdinalIgnoreCase));
|
||||||
CondAdd = new RelayCommand(_ => DoCondAdd());
|
CondAdd = new RelayCommand(_ => DoCondAdd());
|
||||||
CondDelete = new RelayCommand(_ => DoCondDelete(), _ => _selectedCondition != null);
|
CondDelete = new RelayCommand(_ => DoCondDelete(), _ => _selectedCondition != null);
|
||||||
CondMoveUp = new RelayCommand(_ => DoCondMove(-1), _ => CanMoveCond(-1));
|
CondMoveUp = new RelayCommand(_ => DoCondMove(-1), _ => CanMoveCond(-1));
|
||||||
|
|
@ -273,6 +315,40 @@ public class MainViewModel : INotifyPropertyChanged
|
||||||
LoadProfile(new VTankLootProfile());
|
LoadProfile(new VTankLootProfile());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Opens the profile named on the command line (RynthAi's dashboard Edit button passes
|
||||||
|
/// the loot profile in use, or the open vendor's AutoVendor profile). A path that doesn't
|
||||||
|
/// exist yet starts an empty profile that saves there - how a vendor gets its first one.
|
||||||
|
/// </summary>
|
||||||
|
public void OpenFromCommandLine(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
path = Path.GetFullPath(path);
|
||||||
|
if (File.Exists(path))
|
||||||
|
{
|
||||||
|
VTankLootProfile loaded = path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
|
||||||
|
? ConvertFromJson(path)
|
||||||
|
: VTankLootParser.Load(path);
|
||||||
|
_filePath = path;
|
||||||
|
SearchText = "";
|
||||||
|
LoadProfile(loaded);
|
||||||
|
Status($"Opened {Path.GetFileName(path)} ({loaded.Rules.Count} rules)");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_filePath = path;
|
||||||
|
SearchText = "";
|
||||||
|
LoadProfile(new VTankLootProfile());
|
||||||
|
Status($"New profile - Save writes {path}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Status($"Could not open {path}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async Task DoOpenAsync()
|
private async Task DoOpenAsync()
|
||||||
{
|
{
|
||||||
if (!ConfirmDiscard()) return;
|
if (!ConfirmDiscard()) return;
|
||||||
|
|
@ -685,8 +761,13 @@ public class MainViewModel : INotifyPropertyChanged
|
||||||
|
|
||||||
private async Task<IStorageFolder?> GetFolderAsync()
|
private async Task<IStorageFolder?> GetFolderAsync()
|
||||||
{
|
{
|
||||||
if (Directory.Exists(DefaultFolder))
|
string folder = _useAutoVendorFolder ? AutoVendorFolder : DefaultFolder;
|
||||||
return await _window.StorageProvider.TryGetFolderFromPathAsync(DefaultFolder);
|
if (_useAutoVendorFolder && !Directory.Exists(folder))
|
||||||
|
{
|
||||||
|
try { Directory.CreateDirectory(folder); } catch { }
|
||||||
|
}
|
||||||
|
if (Directory.Exists(folder))
|
||||||
|
return await _window.StorageProvider.TryGetFolderFromPathAsync(folder);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,31 @@
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
</Menu>
|
</Menu>
|
||||||
|
|
||||||
|
<!-- Profile folder switch: which folder Open / Save start in. Follows the open file. -->
|
||||||
|
<Border DockPanel.Dock="Top" Background="#080C10" Padding="8,4">
|
||||||
|
<StackPanel Orientation="Horizontal" Spacing="4">
|
||||||
|
<TextBlock Text="Profiles:" VerticalAlignment="Center" Margin="0,0,4,0"
|
||||||
|
Foreground="{StaticResource FgMuted}" FontSize="11"/>
|
||||||
|
<ToggleButton Content="Loot"
|
||||||
|
IsChecked="{Binding UseLootFolder, Mode=OneWay}"
|
||||||
|
Command="{Binding SetProfileFolder}" CommandParameter="Loot"
|
||||||
|
Padding="8,2"/>
|
||||||
|
<ToggleButton Content="AutoVendor"
|
||||||
|
IsChecked="{Binding UseAutoVendorFolder, Mode=OneWay}"
|
||||||
|
Command="{Binding SetProfileFolder}" CommandParameter="AutoVendor"
|
||||||
|
Padding="8,2"/>
|
||||||
|
<TextBlock Text="{Binding ProfileFolderHint}" VerticalAlignment="Center" Margin="8,0,0,0"
|
||||||
|
Foreground="{StaticResource FgMuted}" FontSize="11"/>
|
||||||
|
</StackPanel>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Shown while an AutoVendor profile is open: the same actions mean buy/sell here. -->
|
||||||
|
<Border DockPanel.Dock="Top" Background="#1A2A1A" BorderBrush="#2E4A2E" BorderThickness="0,0,0,1"
|
||||||
|
Padding="8,4" IsVisible="{Binding IsAutoVendorProfile}">
|
||||||
|
<TextBlock TextWrapping="Wrap" FontSize="11" Foreground="#CFE8CF"
|
||||||
|
Text="AutoVendor profile: Keep = buy all it can afford · Keep # = buy until you have N · Sell = sell matching items from your pack. Name the file after the vendor (exactly as shown in game), or default.utl for any vendor without its own profile."/>
|
||||||
|
</Border>
|
||||||
|
|
||||||
<!-- Keyboard shortcuts -->
|
<!-- Keyboard shortcuts -->
|
||||||
<DockPanel.KeyBindings>
|
<DockPanel.KeyBindings>
|
||||||
<KeyBinding Gesture="Ctrl+N" Command="{Binding FileNew}"/>
|
<KeyBinding Gesture="Ctrl+N" Command="{Binding FileNew}"/>
|
||||||
|
|
|
||||||
|
|
@ -8,11 +8,16 @@ public partial class MainWindow : Window
|
||||||
private readonly MainViewModel _vm;
|
private readonly MainViewModel _vm;
|
||||||
private bool _forceClose;
|
private bool _forceClose;
|
||||||
|
|
||||||
public MainWindow()
|
public MainWindow() : this(null) { }
|
||||||
|
|
||||||
|
/// <param name="openPath">A profile to open at startup (from the command line), or null.</param>
|
||||||
|
public MainWindow(string? openPath)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
_vm = new MainViewModel(this);
|
_vm = new MainViewModel(this);
|
||||||
DataContext = _vm;
|
DataContext = _vm;
|
||||||
|
if (!string.IsNullOrWhiteSpace(openPath))
|
||||||
|
_vm.OpenFromCommandLine(openPath);
|
||||||
|
|
||||||
// (Confirm-on-close was disabled when the dirty-flag was made private during
|
// (Confirm-on-close was disabled when the dirty-flag was made private during
|
||||||
// the VTank model migration. Re-add via a public IsDirty later if desired.)
|
// the VTank model migration. Re-add via a public IsDirty later if desired.)
|
||||||
|
|
|
||||||
193
Tools/RynthCore.MissileArcTests/Program.cs
Normal file
193
Tools/RynthCore.MissileArcTests/Program.cs
Normal file
|
|
@ -0,0 +1,193 @@
|
||||||
|
using System;
|
||||||
|
using RynthCore.Plugin.RynthAi.Raycasting;
|
||||||
|
|
||||||
|
namespace RynthCore.MissileArcTests;
|
||||||
|
|
||||||
|
// Tests for the missile arc math combat's LOS uses (MissileBallistics): the low ballistic
|
||||||
|
// solution passes through the aim point, rises with distance and falls with launch speed,
|
||||||
|
// goes out of reach past v²/g, and the clearance bump leaves both ends in place.
|
||||||
|
// Self-contained; fails on zero assertions.
|
||||||
|
//
|
||||||
|
// Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||||
|
internal static class Program
|
||||||
|
{
|
||||||
|
private static int _asserts;
|
||||||
|
private static int _fails;
|
||||||
|
|
||||||
|
private static void Check(bool cond, string msg)
|
||||||
|
{
|
||||||
|
_asserts++;
|
||||||
|
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Near(double actual, double expected, double tol, string msg)
|
||||||
|
{
|
||||||
|
_asserts++;
|
||||||
|
if (double.IsNaN(actual) || Math.Abs(actual - expected) > tol)
|
||||||
|
{ _fails++; Console.WriteLine($" [FAIL] {msg}: expected {expected:0.####} ±{tol}, got {actual:0.####}"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Main()
|
||||||
|
{
|
||||||
|
Console.WriteLine("=== Missile arc tests ===");
|
||||||
|
TestFlatShot();
|
||||||
|
TestPassesThroughAimPoint();
|
||||||
|
TestRiseGrowsWithDistance();
|
||||||
|
TestFasterIsFlatter();
|
||||||
|
TestOutOfReach();
|
||||||
|
TestUphillAndDownhill();
|
||||||
|
TestShortShotIsALine();
|
||||||
|
TestVerticalShot();
|
||||||
|
TestClearanceBump();
|
||||||
|
TestDungeonCeiling();
|
||||||
|
TestSegmentCount();
|
||||||
|
TestBadInput();
|
||||||
|
|
||||||
|
Console.WriteLine($"\n{_asserts} assertions, {_fails} failed.");
|
||||||
|
if (_asserts == 0) { Console.WriteLine("ABORT: zero assertions ran."); return 1; }
|
||||||
|
Console.WriteLine(_fails == 0 ? "ALL MISSILE ARC TESTS PASSED." : $"{_fails} FAILURE(S).");
|
||||||
|
return _fails == 0 ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MissileArc Flat(float d, float v) => MissileBallistics.Solve(0, 0, 1, d, 0, 1, v);
|
||||||
|
|
||||||
|
// 40 m on the level at 25 m/s: low solution tanθ = (v² − √(v⁴ − g²d²))/(g·d) ≈ 0.3526
|
||||||
|
// (19.4°), apex at mid-flight, d·tanθ/4 ≈ 3.53 m above the launch point.
|
||||||
|
private static void TestFlatShot()
|
||||||
|
{
|
||||||
|
var a = Flat(40, 25);
|
||||||
|
Check(a.Valid, "40 m at 25 m/s is in reach");
|
||||||
|
Near(a.TanTheta, 0.35259, 0.0005, "tanθ, 40 m at 25 m/s");
|
||||||
|
Check(a.TanTheta < 1f, "the LOW solution is used (under 45°)");
|
||||||
|
Near(a.ApexAboveLaunch, 40 * a.TanTheta / 4, 0.01, "flat apex = d·tanθ/4");
|
||||||
|
Near(a.ApexAboveLaunch, 3.526, 0.01, "apex, 40 m at 25 m/s");
|
||||||
|
Near(a.MaxRiseAboveChord, a.ApexAboveLaunch, 0.01, "on the level the rise above the line is the apex");
|
||||||
|
Near(a.HeightAt(0.5f), a.ApexAboveLaunch, 0.01, "apex at mid-flight");
|
||||||
|
Near(a.HeightAt(0.25f), a.HeightAt(0.75f), 0.001, "symmetric on the level");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestPassesThroughAimPoint()
|
||||||
|
{
|
||||||
|
var a = MissileBallistics.Solve(10, 20, 5, 40, -10, 7.5f, 30);
|
||||||
|
Check(a.Valid, "diagonal shot in reach");
|
||||||
|
a.PointAt(1f, 0f, out float x, out float y, out float z);
|
||||||
|
Near(x, 40, 0.001, "end x");
|
||||||
|
Near(y, -10, 0.001, "end y");
|
||||||
|
Near(z, 7.5, 0.01, "end z (aim point)");
|
||||||
|
a.PointAt(0f, 0f, out x, out y, out z);
|
||||||
|
Near(x, 10, 0.001, "start x");
|
||||||
|
Near(y, 20, 0.001, "start y");
|
||||||
|
Near(z, 5, 0.001, "start z (launch point)");
|
||||||
|
a.PointAt(0.5f, 0f, out x, out y, out _);
|
||||||
|
Near(x, 25, 0.001, "mid x on the horizontal line");
|
||||||
|
Near(y, 5, 0.001, "mid y on the horizontal line");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestRiseGrowsWithDistance()
|
||||||
|
{
|
||||||
|
float r10 = Flat(10, 25).MaxRiseAboveChord;
|
||||||
|
float r20 = Flat(20, 25).MaxRiseAboveChord;
|
||||||
|
float r40 = Flat(40, 25).MaxRiseAboveChord;
|
||||||
|
float r55 = Flat(55, 25).MaxRiseAboveChord;
|
||||||
|
Check(r10 < r20 && r20 < r40 && r40 < r55, $"rise grows with distance ({r10:0.00} < {r20:0.00} < {r40:0.00} < {r55:0.00})");
|
||||||
|
Check(r10 < 0.25f, $"10 m is nearly flat ({r10:0.000} m)");
|
||||||
|
Check(r55 > 5f, $"55 m rises past 5 m at 25 m/s ({r55:0.00} m)");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestFasterIsFlatter()
|
||||||
|
{
|
||||||
|
float slow = Flat(40, 22).MaxRiseAboveChord;
|
||||||
|
float mid = Flat(40, 25).MaxRiseAboveChord;
|
||||||
|
float fast = Flat(40, 40).MaxRiseAboveChord;
|
||||||
|
Check(slow > mid && mid > fast, $"faster launch = flatter arc ({slow:0.00} > {mid:0.00} > {fast:0.00})");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestOutOfReach()
|
||||||
|
{
|
||||||
|
float v = 25f, g = MissileBallistics.AcGravity;
|
||||||
|
float maxRange = v * v / g; // 63.8 m on the level, at 45°
|
||||||
|
Check(Flat(maxRange - 0.5f, v).Valid, "just inside v²/g is in reach");
|
||||||
|
Check(!Flat(maxRange + 0.5f, v).Valid, "past v²/g is out of reach");
|
||||||
|
var edge = Flat(maxRange * 0.9999f, v);
|
||||||
|
Check(edge.Valid && Math.Abs(edge.TanTheta - 1f) < 0.05f, "maximum range is flown at 45°");
|
||||||
|
Check(!MissileBallistics.Solve(0, 0, 0, 5, 0, 40, 20).Valid, "40 m straight up a 5 m slope at 20 m/s is out of reach");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestUphillAndDownhill()
|
||||||
|
{
|
||||||
|
var up = MissileBallistics.Solve(0, 0, 1, 30, 0, 9, 25);
|
||||||
|
var down = MissileBallistics.Solve(0, 0, 9, 30, 0, 1, 25);
|
||||||
|
Check(up.Valid && down.Valid, "8 m up / down over 30 m in reach");
|
||||||
|
Near(up.HeightAt(1f), 8, 0.01, "uphill arc ends at the aim point");
|
||||||
|
Near(down.HeightAt(1f), -8, 0.01, "downhill arc ends at the aim point");
|
||||||
|
Check(up.TanTheta > Flat(30, 25).TanTheta, "uphill launches steeper than level");
|
||||||
|
Check(down.TanTheta < Flat(30, 25).TanTheta, "downhill launches flatter than level");
|
||||||
|
Check(up.MaxRiseAboveChord > 0f && down.MaxRiseAboveChord > 0f, "both still bow above the straight line");
|
||||||
|
Check(up.ApexAboveLaunch >= 8f, "uphill apex is at least the aim point");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestShortShotIsALine()
|
||||||
|
{
|
||||||
|
var a = Flat(5, 25);
|
||||||
|
Check(a.Valid, "5 m in reach");
|
||||||
|
Check(a.MaxRiseAboveChord < 0.06f, $"5 m at 25 m/s rises under 6 cm ({a.MaxRiseAboveChord:0.000})");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestVerticalShot()
|
||||||
|
{
|
||||||
|
var a = MissileBallistics.Solve(3, 3, 0, 3.01f, 3, 6, 25);
|
||||||
|
Check(a.Valid && a.Vertical, "near-vertical shot is flown as a line");
|
||||||
|
Near(a.HeightAt(0.5f), 3, 0.001, "vertical shot mid height");
|
||||||
|
Near(a.MaxRiseAboveChord, 0, 0.0001, "vertical shot has no rise above the line");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestClearanceBump()
|
||||||
|
{
|
||||||
|
Near(MissileBallistics.ClearanceBump(0f, 0.5f), 0, 1e-6, "bump 0 at launch");
|
||||||
|
Near(MissileBallistics.ClearanceBump(1f, 0.5f), 0, 1e-6, "bump 0 at the aim point");
|
||||||
|
Near(MissileBallistics.ClearanceBump(0.5f, 0.5f), 0.5, 1e-6, "bump = clearance at mid-flight");
|
||||||
|
Near(MissileBallistics.ClearanceBump(0.5f, 0f), 0, 1e-6, "no clearance, no bump");
|
||||||
|
Near(MissileBallistics.ClearanceBump(0.5f, -1f), 0, 1e-6, "negative clearance ignored");
|
||||||
|
var a = Flat(40, 25);
|
||||||
|
a.PointAt(0.5f, 0.5f, out _, out _, out float zWith);
|
||||||
|
a.PointAt(0.5f, 0f, out _, out _, out float zWithout);
|
||||||
|
Near(zWith - zWithout, 0.5, 1e-4, "PointAt applies the bump");
|
||||||
|
a.PointAt(1f, 2f, out _, out _, out float zEnd);
|
||||||
|
Near(zEnd, 1, 1e-3, "the bump never moves the aim point");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A 4 m high corridor, launching from chest height (1 m above the floor): the straight
|
||||||
|
// line to a target 40 m away clears, the 25 m/s arrow (apex ≈ 4.5 m) doesn't.
|
||||||
|
private static void TestDungeonCeiling()
|
||||||
|
{
|
||||||
|
const float ceiling = 4f;
|
||||||
|
var far = Flat(40, 25);
|
||||||
|
var near = Flat(15, 25);
|
||||||
|
float farTop = MissileBallistics.MaxPathZ(far, 0f);
|
||||||
|
float nearTop = MissileBallistics.MaxPathZ(near, 0.5f);
|
||||||
|
Check(farTop > ceiling, $"40 m shot hits a 4 m ceiling (top {farTop:0.00} m)");
|
||||||
|
Check(nearTop < ceiling, $"15 m shot clears it even with 0.5 m clearance (top {nearTop:0.00} m)");
|
||||||
|
Check(MissileBallistics.MaxPathZ(near, 3f) > MissileBallistics.MaxPathZ(near, 0f) + 2.9f, "clearance raises the tested top");
|
||||||
|
Check(float.IsNaN(MissileBallistics.MaxPathZ(Flat(100, 25), 0f)), "out of reach has no path");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestSegmentCount()
|
||||||
|
{
|
||||||
|
Check(MissileBallistics.SegmentCount(0f) == 6, "minimum 6 segments");
|
||||||
|
Check(MissileBallistics.SegmentCount(5f) == 6, "5 m → 6 segments");
|
||||||
|
Check(MissileBallistics.SegmentCount(25f) == 10, "25 m → 10 segments");
|
||||||
|
Check(MissileBallistics.SegmentCount(50f) == 20, "50 m → 20 segments");
|
||||||
|
Check(MissileBallistics.SegmentCount(500f) == 24, "capped at 24 segments");
|
||||||
|
Check(MissileBallistics.SegmentCount(float.NaN) == 6, "NaN → minimum");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void TestBadInput()
|
||||||
|
{
|
||||||
|
Check(!MissileBallistics.Solve(0, 0, 0, 10, 0, 0, 0f).Valid, "zero speed is out of reach");
|
||||||
|
Check(!MissileBallistics.Solve(0, 0, 0, 10, 0, 0, -5f).Valid, "negative speed is out of reach");
|
||||||
|
Check(!MissileBallistics.Solve(0, 0, 0, float.NaN, 0, 0, 25f).Valid, "NaN position is not a shot");
|
||||||
|
var bad = MissileBallistics.Solve(0, 0, 0, 10, 0, 0, 0f);
|
||||||
|
Near(bad.MaxRiseAboveChord, 0, 0, "invalid arc has no rise");
|
||||||
|
Near(bad.ApexAboveLaunch, 0, 0, "invalid arc has no apex");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Unit tests for RynthAi's missile arc math (MissileBallistics: the low ballistic arc a
|
||||||
|
missile flies, its rise above the straight line, the ceiling clearance bump). The plugin
|
||||||
|
itself is a NativeAOT x86 library, so the dependency-free source file is compiled in
|
||||||
|
here directly instead of referencing the plugin project.
|
||||||
|
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>RynthCore.MissileArcTests</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthAi\Raycasting\MissileBallistics.cs" Link="Linked\MissileBallistics.cs" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
Loading…
Reference in a new issue