RynthServers/Plugins/RynthCore.Plugin.RynthILT/Hub/IltInventory.cs

391 lines
20 KiB
C#

// IltInventory.cs — Shared item / player-property helper for every ILT Hub feature.
// Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. Items come
// from RynthILT's host-backed IltObjects instead of RynthAi's WorldObjectCache.
//
// One place for: WCID lookups (cached — the engine call is cheap but not free), stack
// counting, "is it equipped", appraisal requests (throttled), charm ON/OFF status from the
// appraisal Use text, and player int/bool/quad reads. Features never talk to the cache or
// the host for item facts directly, so behaviour (and its edge cases) stays consistent.
// Pump-thread only.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Loot;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthILT.Hub;
/// <summary>
/// Registered ACECustom charm (CharmAbilityRegistry): display name, every known WCID (base +
/// tier variants), the player PropertyBool the server sets while the ability is active (0 when
/// it is kept in memory only, like Auto-Rebuff) and a one-line effect summary.
/// </summary>
internal sealed record IltCharmDef(string Name, uint[] Wcids, uint PlayerFlag = 0, string Effect = "");
internal sealed class IltInventory
{
// ── Well-known WCIDs (ACECustom content) ────────────────────────────────
public const uint WcidPyreal = 273;
public const uint WcidEnlightenedCoin = 300004;
public const uint WcidEnlToken = 300000;
public const uint WcidEnlMedallion = 90000217;
public const uint WcidEnlSigil = 300101189;
public const uint WcidEnlCrest = 98769999;
public const uint WcidEncapsulatedSpirit = 49485;
public const uint WcidRuneOfDispel = 30133;
public const uint WcidSummonRefillCharm = 78780030;
public const uint WcidUniversalMasteryCharm = 78780031;
public static readonly uint[] WcidInfiniteCastingStone = { 777700019, 777700055 };
// Aetheria (ACECustom Aetheria.cs / PlayerCommands /clap). The Coalesced WCIDs stay the same once
// revealed (name "Aetheria", equipment set given), and /clap takes only unrevealed level 1-3 ones.
public const uint WcidBlueCoalescedAetheria = 42635;
public const uint WcidRedCoalescedAetheria = 42636;
public const uint WcidYellowCoalescedAetheria = 42637;
public const uint WcidRedAetheriaChunk = 310147;
public const uint WcidBlueAetheriaChunk = 310149;
public const uint WcidYellowAetheriaChunk = 310150;
public const uint WcidRedAetheriaPowder = 42644;
public const uint WcidBlueAetheriaPowder = 300019;
public const uint WcidEmpyreanTrinket = 34276;
public const uint WcidFalatacotTrinket = 34277;
// ── Property ids used by several features ───────────────────────────────
public const uint IntStackSize = 12;
public const uint IntValidLocations = 9;
public const uint IntLevel = 25;
public const uint IntMaxStructure = 91;
public const uint IntStructure = 92;
public const uint IntNumTimesTinkered = 171;
public const uint IntImbuedEffect = 179;
public const uint IntCleaving = 292;
// Corrupted-weapon chunk rules (ub-IT Leaftide.IsValidCorruptedWep / CorruptedChunkGuard).
/// <summary>ACE PropertyInt.Damage — a weapon's max damage.</summary>
public const uint IntDamage = 44;
/// <summary>ACE PropertyInt.AttackType — 2 = thrust; 160 / 166 / 486 are the multi-strike masks.</summary>
public const uint IntAttackType = 47;
/// <summary>ACE PropertyInt.ItemWorkmanship — loot-gen Craft (salvage-bag workmanship is not on weapons).</summary>
public const uint IntItemWorkmanship = 105;
/// <summary>ACE PropertyInt.WieldSkillType — 41 (Two Handed Combat) for two-handed weapons.</summary>
public const uint IntWieldSkillType = 159;
/// <summary>ACE PropertyInt.SlayerCreatureType.</summary>
public const uint IntSlayerCreatureType = 166;
/// <summary>ACE PropertyInt.ElementalDamageBonus.</summary>
public const uint IntElementalDamageBonus = 204;
/// <summary>ACE PropertyInt.WeaponType — 11 = TwoHanded.</summary>
public const uint IntWeaponType = 353;
/// <summary>ACE PropertyFloat.CriticalMultiplier — Biting Strike.</summary>
public const uint FloatCriticalMultiplier = 136;
/// <summary>ACE PropertyFloat.CriticalFrequency — Crushing Blow.</summary>
public const uint FloatCriticalFrequency = 147;
/// <summary>ACE PropertyFloat.IgnoreArmor — Armor Cleaving.</summary>
public const uint FloatIgnoreArmor = 155;
public const uint IntItemMaxLevel = 319;
/// <summary>Highest aetheria level on Infinite Leaftide (ACECustom AetheriaChance rolls up to 10; retail stops at 5).</summary>
public const int AetheriaMaxLevel = 10;
/// <summary>Gear ratings ILT aetheria can carry: C, CD and CDR (PropertyInt GearCrit / GearCritDamage / GearCritDamageResist).</summary>
public const uint IntGearCrit = 372;
public const uint IntGearCritDamage = 374;
public const uint IntGearCritDamageResist = 375;
public const uint IntSummoningMastery = 362;
public const uint IntEnlightenment = 390;
public const uint IntSplitArrowCount = 9031;
public const uint IntMaterialType = 131;
public const uint IntUses = 92;
/// <summary>ACECustom charm item: current tier (PropertyInt.CharmLevel).</summary>
public const uint IntCharmLevel = 50005;
/// <summary>ACECustom charm item: highest tier for this charm line (PropertyInt.CharmMaxLevel).</summary>
public const uint IntCharmMaxLevel = 50006;
public const uint StrUse = 14;
public const uint QuadTotalXp = 1;
public const uint QuadAvailableXp = 2;
public const uint QuadItemTotalXp = 4;
/// <summary>ACECustom PropertyInt64.BankedLuminance (sent with each XP batch).</summary>
public const uint QuadBankedLuminance = 9005;
public const uint BoolNeverChunk = 9030;
public const uint BoolPyrealRefillActive = 9049;
public const uint BoolUniversalMasteryActive = 50038;
/// <summary>
/// Every charm in ACECustom's CharmAbilityRegistry (WCIDs and player flags match the server's
/// WCIDToAbilityId map and PropertyBool ids). Guardian Hand is not a registry charm and has no
/// published WCID — see IltGear.
/// </summary>
public static readonly IltCharmDef[] Charms =
{
new("Mana Barrier", new uint[] { 777700001, 777700054, 777710004, 777720004 }, 50010,
"Mana absorbs incoming damage (better ratio at higher tiers)."),
new("Infinite Casting", WcidInfiniteCastingStone, 50028,
"Infinite Casting Stone: spells cast without consuming components."),
new("Asheron's Favor", new uint[] { 777700020, 777710002, 777720002 }, 50030,
"+10 / 15 / 20% health and +50 / 100 / 250 natural armor."),
new("Artisan's", new uint[] { 777700021, 777710003, 777720003 }, 50031,
"Imbue success chance +4 / 8 / 12%."),
new("Shrapnel", new uint[] { 777700022 }, 50032,
"Tectonic Rifts cast as Rocky Shrapnel (Rocky Shrapnel must be learned)."),
new("Agony", new uint[] { 777700023 }, 50033,
"Tectonic Rifts I casts as Ring of Unspeakable Agony (the spell must be learned)."),
new("Split Cast", new uint[] { 777700024 }, 50035,
"Streak, Arc and Bolt spells split to several nearby targets."),
new("Explosive Arrow", new uint[] { 777700025, 777710005, 777720005 }, 50036,
"Arrow hits detonate an elemental ring at the target."),
new("Omni Strike", new uint[] { 777700026 }, 50037,
"Melee hits use the damage type the target is weakest to."),
new("Fork", new uint[] { 777700027, 777710007, 777720007 }, 50039,
"Streak, Arc and Bolt projectiles fork to nearby enemies (50 / 75 / 100% damage)."),
new("Auto-Rebuff", new uint[] { 777700300 }, 0,
"Keeps your buffs up automatically."),
new("Summon Essence Refill", new uint[] { WcidSummonRefillCharm }, BoolPyrealRefillActive,
"Refills an empty pet essence from banked pyreals when you summon."),
new("Universal Summoning Mastery", new uint[] { WcidUniversalMasteryCharm }, BoolUniversalMasteryActive,
"Use pet essences of any summoning mastery."),
};
private readonly RynthCoreHost _host;
private readonly IltObjects _cache;
/// <summary>AC's CM_Combat value for peace mode (RynthAi's CombatMode.NonCombat).</summary>
private const int CombatModeNonCombat = 1;
private readonly Dictionary<int, uint> _wcidCache = new();
private readonly Dictionary<int, long> _lastIdRequest = new();
/// <summary>Don't re-request appraisal for the same object more often than this.</summary>
private const long IdRequestThrottleMs = 30_000;
public IltInventory(RynthCoreHost host, IltObjects cache)
{
_host = host;
_cache = cache;
}
public RynthCoreHost Host => _host;
public IltObjects Cache => _cache;
public uint PlayerId => _host.GetPlayerId();
// ── Player state ────────────────────────────────────────────────────────
/// <summary>The client busy hourglass is up (an action is in progress).</summary>
public bool IsBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
/// <summary>Player is in peace mode (combat mode NonCombat). True when the engine can't tell.</summary>
public bool InPeaceMode => !_host.HasGetCurrentCombatMode || _host.GetCurrentCombatMode() == CombatModeNonCombat;
public int PlayerInt(uint stype, int fallback = 0)
=> _host.HasGetObjectIntProperty && _host.TryGetObjectIntProperty(PlayerId, stype, out int v) ? v : fallback;
public bool PlayerBool(uint stype)
=> _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(PlayerId, stype, out bool v) && v;
public long PlayerQuad(uint stype)
=> _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(PlayerId, stype, out long v) ? v : 0;
/// <summary>Current/max health from the engine vitals read (0/0 when unavailable).</summary>
public (uint Cur, uint Max) PlayerHealth()
{
if (_host.HasGetPlayerVitals && _host.TryGetPlayerVitals(out uint h, out uint mh, out _, out _, out _, out _))
return (h, mh);
return (0, 0);
}
// ── Item facts ──────────────────────────────────────────────────────────
/// <summary>All items the player carries or wears (snapshot).</summary>
public IEnumerable<WorldObject> Items() => _cache.GetInventory();
/// <summary>Weenie class id, cached per object (0 when unknown).</summary>
public uint Wcid(WorldObject wo)
{
if (_wcidCache.TryGetValue(wo.Id, out uint w) && w != 0) return w;
if (_host.HasGetObjectWcid && _host.TryGetObjectWcid(unchecked((uint)wo.Id), out w))
_wcidCache[wo.Id] = w;
return w;
}
public int Int(WorldObject wo, uint stype, int fallback = 0) => wo.Values(unchecked((int)stype), fallback);
public bool Bool(WorldObject wo, uint stype)
=> _host.HasGetObjectBoolProperty && _host.TryGetObjectBoolProperty(unchecked((uint)wo.Id), stype, out bool v) && v;
public long Quad(WorldObject wo, uint stype)
=> _host.HasGetObjectQuadProperty && _host.TryGetObjectQuadProperty(unchecked((uint)wo.Id), stype, out long v) ? v : 0;
/// <summary>A float (PropertyFloat) value; 0 when the host cannot read it or the item has none.</summary>
public double Double(WorldObject wo, uint stype)
=> _host.HasGetObjectDoubleProperty && _host.TryGetObjectDoubleProperty(unchecked((uint)wo.Id), stype, out double v) ? v : 0;
/// <summary>The spell ids on an item (empty when none or the host cannot read them).</summary>
public IReadOnlyList<int> SpellIds(WorldObject wo)
{
if (!_host.HasGetObjectSpellIds) return Array.Empty<int>();
var buf = new uint[64];
int n = _host.GetObjectSpellIds(unchecked((uint)wo.Id), buf, buf.Length);
if (n <= 0) return Array.Empty<int>();
var ids = new int[Math.Min(n, buf.Length)];
for (int i = 0; i < ids.Length; i++) ids[i] = unchecked((int)buf[i]);
return ids;
}
public string Str(WorldObject wo, uint stype)
=> _host.HasGetObjectStringProperty && _host.TryGetObjectStringProperty(unchecked((uint)wo.Id), stype, out string v) ? v ?? string.Empty : string.Empty;
/// <summary>Stack size (1 for non-stackables).</summary>
public int StackSize(WorldObject wo) => Math.Max(1, Int(wo, IntStackSize, 1));
/// <summary>Remaining uses on a structure item (essences, kits, salvage bags).</summary>
public int Uses(WorldObject wo) => Int(wo, IntStructure, 0);
public bool IsEquipped(WorldObject wo)
=> wo.WieldedLocation > 0 || (wo.Wielder != 0 && unchecked((uint)wo.Wielder) == PlayerId);
public bool HasAppraisal(WorldObject wo)
=> !_host.HasHasAppraisalData || _host.HasAppraisalData(unchecked((uint)wo.Id));
/// <summary>
/// Why an item's property reads cannot be trusted (null = they can). Every property read here
/// answers 0 / false both for "the item has none" and for "the host cannot read it", so a chunk
/// rule that acts on a 0 must first know the read was real: the host must expose the readers
/// and confirm the item's appraisal arrived. <paramref name="quads"/> adds the 64-bit reads
/// (item XP), <paramref name="doubles"/> the float reads and <paramref name="spells"/> the
/// spell list, for the rules that use them.
/// </summary>
public string? ReadGap(WorldObject wo, bool quads = false, bool doubles = false, bool spells = false)
{
if (!_host.HasGetObjectIntProperty) return "int properties";
if (!_host.HasGetObjectBoolProperty) return "bool properties";
if (quads && !_host.HasGetObjectQuadProperty) return "item XP";
if (doubles && !_host.HasGetObjectDoubleProperty) return "float properties";
if (spells && !_host.HasGetObjectSpellIds) return "spells";
if (!_host.HasHasAppraisalData || !_host.HasAppraisalData(unchecked((uint)wo.Id))) return "appraisal";
return null;
}
/// <summary>Requests appraisal data, throttled per object. Returns true if a request was sent.</summary>
public bool RequestAppraisal(WorldObject wo)
{
if (!_host.HasRequestId) return false;
long now = Environment.TickCount64;
if (_lastIdRequest.TryGetValue(wo.Id, out long last) && now - last < IdRequestThrottleMs) return false;
_lastIdRequest[wo.Id] = now;
return _host.RequestId(unchecked((uint)wo.Id));
}
// ── Finders / counters ──────────────────────────────────────────────────
public WorldObject? FindByWcid(params uint[] wcids)
=> Items().FirstOrDefault(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
public IEnumerable<WorldObject> AllByWcid(params uint[] wcids)
=> Items().Where(wo => Array.IndexOf(wcids, Wcid(wo)) >= 0);
public WorldObject? FindByName(Func<string, bool> predicate)
=> Items().FirstOrDefault(wo => predicate(wo.Name));
/// <summary>Total stack count of items with any of the given WCIDs.</summary>
public long CountByWcid(params uint[] wcids)
=> AllByWcid(wcids).Sum(wo => (long)StackSize(wo));
/// <summary>Total stack count of items whose name matches exactly (case-insensitive).</summary>
public long CountByName(string name)
=> Items().Where(wo => wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Sum(wo => (long)StackSize(wo));
/// <summary>Total stack count of a sigil-chain item (singular or plural stack name; see IltSigilChain.NameIs).</summary>
public long CountByChainName(string chainName)
=> Items().Where(wo => IltSigilChain.NameIs(wo.Name, chainName)).Sum(wo => (long)StackSize(wo));
/// <summary>
/// True when the player carries spell components or an Infinite Casting Stone that isn't
/// known to be switched OFF (an OFF stone doesn't waive components).
/// </summary>
public bool HasCastingSupplies()
=> AllByWcid(WcidInfiniteCastingStone).Any(stone => CharmStatus(stone) != IltTri.Off)
|| Items().Any(wo => wo.ObjectClass == AcObjectClass.SpellComponent);
/// <summary>Free main-pack slots (best effort: capacity minus direct children; -1 when unknown).</summary>
public int FreeMainPackSlots()
{
var cache = _cache;
int player = unchecked((int)PlayerId);
int capacity = PlayerInt(IltObjects.IntItemsCapacity, 102);
int used = cache.GetDirectInventory()
.Count(wo => wo.Container == player && wo.WieldedLocation <= 0 && wo.ObjectClass != AcObjectClass.Container);
return Math.Max(0, capacity - used);
}
// ── Charms ──────────────────────────────────────────────────────────────
/// <summary>
/// ON/OFF/Unknown from the appraisal Use text ("... Status: ON"). Requests appraisal
/// (throttled) when the text isn't loaded yet.
/// </summary>
public IltTri CharmStatus(WorldObject charm)
{
string use = Str(charm, StrUse);
if (use.Length == 0)
{
RequestAppraisal(charm);
return IltTri.Unknown;
}
if (use.Contains("Status: ON", StringComparison.OrdinalIgnoreCase)) return IltTri.On;
if (use.Contains("Status: OFF", StringComparison.OrdinalIgnoreCase)) return IltTri.Off;
return IltTri.Unknown;
}
/// <summary>
/// Charm tier and max tier from the item's CharmLevel / CharmMaxLevel ints, else parsed from
/// the appraisal Use text ("Charm [Tier 2/3]"). (0, 0) until the appraisal is loaded.
/// </summary>
public (int Tier, int MaxTier) CharmTier(WorldObject charm)
{
int tier = Int(charm, IntCharmLevel, 0), max = Int(charm, IntCharmMaxLevel, 0);
if (tier > 0) return (tier, max);
var m = CharmTierText.Match(Str(charm, StrUse));
if (!m.Success) return (0, 0);
int.TryParse(m.Groups[1].Value, out tier);
if (m.Groups[2].Success) int.TryParse(m.Groups[2].Value, out max);
return (tier, max);
}
private static readonly System.Text.RegularExpressions.Regex CharmTierText =
new(@"Charm \[Tier (\d+)(?:/(\d+))?\]", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>Charm definition for an item (by WCID), or null.</summary>
public IltCharmDef? CharmDefFor(WorldObject wo)
{
uint w = Wcid(wo);
if (w == 0) return null;
return Charms.FirstOrDefault(c => Array.IndexOf(c.Wcids, w) >= 0);
}
/// <summary>
/// Every charm the player carries: registered WCIDs plus anything whose Use text starts
/// with "Charm [Tier" (generic ACECustom charm format, catches charms added later).
/// </summary>
public List<WorldObject> CarriedCharms()
{
var list = new List<WorldObject>();
foreach (var wo in Items())
{
if (CharmDefFor(wo) != null) { list.Add(wo); continue; }
if (wo.ObjectClass is AcObjectClass.MeleeWeapon or AcObjectClass.MissileWeapon or AcObjectClass.Armor
or AcObjectClass.Clothing or AcObjectClass.Container or AcObjectClass.Corpse)
continue;
if (Str(wo, StrUse).StartsWith("Charm [Tier", StringComparison.OrdinalIgnoreCase)
|| wo.Name.EndsWith(" Charm", StringComparison.OrdinalIgnoreCase))
list.Add(wo);
}
return list;
}
// ── Actions ─────────────────────────────────────────────────────────────
public bool Use(WorldObject wo) => _host.HasUseObject && _host.UseObject(unchecked((uint)wo.Id));
public bool UseOn(WorldObject source, uint targetId)
=> _host.HasUseObjectOn && _host.UseObjectOn(unchecked((uint)source.Id), targetId);
/// <summary>Forgets cached WCIDs / appraisal throttles (logout).</summary>
public void Reset()
{
_wcidCache.Clear();
_lastIdRequest.Clear();
_cache.Clear();
}
}