using System.Text.Json.Nodes; using static XFEWarframe.Bridge.GameTestLua; namespace XFEWarframe.Bridge; internal static unsafe partial class ExperimentalAbilityRuntime { private sealed record ExaltedMod(string Id, string Type, string Fingerprint); private sealed class ExaltedRequest(nint ability, string type, int config, ExaltedMod[] mods) { internal nint Ability { get; } = ability; internal string Type { get; } = type; internal int Config { get; } = config; internal ExaltedMod[] Mods { get; } = mods; internal float Delay { get; set; } internal long RetryAfter { get; set; } internal int Failures { get; set; } } private sealed record ExaltedLease(nint Suit, nint Weapon, string Type, int Config, int Mods, string Key); private static readonly Dictionary> ExaltedRequests = []; private static readonly Dictionary ExaltedLeases = []; private const string ExaltedRoot = "XFEExaltedEquipment"; private static readonly System.Collections.Concurrent.ConcurrentQueue ForgottenExalted = []; private static void ForgetExaltedEquipment(nint suit) { ExaltedRequests.Remove(suit); foreach (var lease in ExaltedLeases.Values.Where(x => x.Suit == suit).ToArray()) { if (ForgottenExalted.Count < 256) ForgottenExalted.Enqueue(lease.Key); ExaltedLeases.Remove(lease.Weapon); } } internal static void DrainForgottenExalted() { if (ForgottenExalted.Count == 0) return; try { using var lua = new Scope(); var globals = lua.Global("_T"); if (lua.Kind(globals) != 7) return; var root = lua.Field(globals, ExaltedRoot); if (lua.Kind(root) == 7) while (ForgottenExalted.TryPeek(out var key)) { lua.Set(root, key, null); ForgottenExalted.TryDequeue(out _); } else ForgottenExalted.Clear(); } catch (InvalidOperationException) { /* Wait until the next valid game VM tick. */ } catch (Exception ex) { ReportBankFailure(ex); } } // Called while the donor's actual SpecialItem descriptor is on the Lua stack. // Read the local profile, never a remote avatar's or a donor suit's inventory. private static void QueueExaltedEquipment(nint state, nint suit, nint ability) { using var lua = new Scope(state); var descriptor = lua.At(lua.Count); var type = lua.Text(lua.Method(lua.Field(descriptor, "mItemType"), "GetFullName")); if (string.IsNullOrEmpty(type)) return; if (ExaltedRequests.TryGetValue(suit, out var pending) && pending.Any(x => x.Ability == ability && x.Type == type)) return; var region = lua.Global("gRegion"); var avatar = lua.Method(region, "GetLocalPlayerAvatar"); if (lua.Kind(avatar) != 9) return; var controller = lua.Method(avatar, "InventoryControl"); if (lua.Object(lua.Method(controller, "GetActivePowerSuit")) != suit) return; var data = lua.Global("gGameData"); var loadout = lua.Method(data, "GetLoadOut"); var selected = lua.Method(loadout, "0xB2A2BA51", 0, 0); var index = lua.Number(lua.Field(selected, "mModSlot")); if (!float.IsFinite(index) || index != MathF.Truncate(index) || index is < 0 or > 5) return; var mods = ReadExaltedMods(lua, data, type, (int)index); if (mods is null) return; // Missing owned weapon is not an implicit grant. pending ??= []; if (pending.Count >= 12 || ExaltedRequests.Count >= 16) return; pending.Add(new(ability, type, (int)index, mods)); ExaltedRequests[suit] = pending; if (trace) log($"Exalted equipment: queued {type}, config {index}, {mods.Length} owned MODs."); } private static ExaltedMod[]? ReadExaltedMods(Scope lua, Ref data, string type, int index) { var inventory = lua.Method(data, "GetInventory"); var specials = lua.Method(inventory, "GetSpecialItems"); Ref? weapon = null; var mark = lua.Count; for (var i = 1; i <= 4096; i++) { var candidate = lua.Raw(specials, i); if (lua.Kind(candidate) == 0) break; var candidateType = lua.Field(candidate, "mItemType"); if (lua.Kind(candidateType) == 9 && lua.Text(lua.Method(candidateType, "GetFullName")) == type) { weapon = candidate; break; } lua.Rewind(mark); } if (weapon is null) return null; // The native ItemInfo getter at RVA 0x1B8AAA0 returns the selected config's // UpgradeSlotInfo array (+0x28 of Config), preserving empty MOD positions. var ids = lua.Method(weapon.Value, "0xBFBBF8CE", index, false); var requested = new List(8); mark = lua.Count; for (var i = 1; i <= 8; i++) { var slot = lua.Raw(ids, i); if (lua.Kind(slot) == 0) break; var id = lua.Text(lua.Field(lua.Field(slot, "mId"), "mId")); if (!string.IsNullOrEmpty(id) && id != "000000000000000000000000") requested.Add(id); lua.Rewind(mark); } if (requested.Count == 0) return []; var upgrades = lua.Method(inventory, "GetUpgrades"); var found = new Dictionary(StringComparer.Ordinal); mark = lua.Count; for (var i = 1; i <= 65536 && found.Count < requested.Distinct().Count(); i++) { var upgrade = lua.Raw(upgrades, i); if (lua.Kind(upgrade) == 0) break; var id = lua.Text(lua.Field(lua.Field(upgrade, "mItemId"), "mId")); if (id is not null && requested.Contains(id)) { var itemType = lua.Field(upgrade, "mItemType"); var path = lua.Text(lua.Method(itemType, "GetFullName")); var fingerprint = lua.Text(lua.Field(upgrade, "mUpgradeFingerprint")); if (path is not null && fingerprint is { Length: <= 2048 }) found[id] = new(id, path, fingerprint); } lua.Rewind(mark); } if (requested.Any(x => !found.ContainsKey(x))) throw new InvalidDataException("An exalted MOD was not found in the local owned inventory."); return requested.Distinct().Select(x => found[x]).ToArray(); } private static Ref ExaltedTable(Scope lua) { var globals = lua.Global("_T"); var root = lua.Field(globals, ExaltedRoot); if (lua.Kind(root) == 7) return root; root = lua.Table(fields: 16); lua.Set(globals, ExaltedRoot, root); return root; } private static void UpdateExaltedEquipment(nint suit, float seconds) { if (!ExaltedRequests.TryGetValue(suit, out var pending)) return; foreach (var dead in pending.Where(x => !HasAbility(suit, x.Ability) || *(byte*)(x.Ability + 0x678) == 0).ToArray()) { ReleaseExaltedEquipment(suit, dead.Type); pending.Remove(dead); } if (pending.Count == 0) { ExaltedRequests.Remove(suit); return; } foreach (var request in pending) request.Delay -= Math.Clamp(seconds, 0, .1f); var now = Environment.TickCount64; if (!pending.Any(x => x.Delay <= 0 && x.RetryAfter <= now && !ExaltedLeases.Values.Any(lease => lease.Suit == suit && lease.Type == x.Type && lease.Config == x.Config))) return; foreach (var request in pending) request.Delay = 0.1f; using var lua = new Scope(); var region = lua.Global("gRegion"); var avatar = lua.Method(region, "GetLocalPlayerAvatar"); if (lua.Kind(avatar) != 9) return; var controller = lua.Method(avatar, "InventoryControl"); if (lua.Object(lua.Method(controller, "GetActivePowerSuit")) != suit) return; var root = ExaltedTable(lua); var mark = lua.Count; for (var slot = 0; slot <= 13; slot++) { var weapon = lua.Method(controller, "GetWeaponInSlot", slot); var pointer = lua.Object(weapon); if (pointer != 0 && !ExaltedLeases.ContainsKey(pointer)) { var path = TypePath(*(nint*)(pointer + 8)); var request = pending.FirstOrDefault(x => x.Type == path && x.RetryAfter <= now); if (request is not null && ExaltedLeases.Count < 24) { try { ApplyExaltedMods(lua, region, root, weapon, pointer, suit, request); request.Failures = 0; } catch (Exception ex) { request.RetryAfter = now + Math.Min(5000, ++request.Failures * 1000); ReportBankFailure(ex); } } } lua.Rewind(mark); } } private static void ApplyExaltedMods(Scope lua, Ref region, Ref root, Ref weapon, nint pointer, nint suit, ExaltedRequest request) { var key = $"{suit:X}:{pointer:X}"; var retained = lua.Table(array: 9); lua.Set(root, key, retained); lua.Set(retained, 1, weapon); // Root each upgrade before attaching. A failed attachment can then be rolled // back through the same native RemoveUpgrade API, without clearing the // weapon's built-in upgrades, ability strength or channel modifiers. var count = 0; ExaltedLeases[pointer] = new(suit, pointer, request.Type, request.Config, 0, key); try { foreach (var mod in request.Mods) { var resource = lua.Load(mod.Type); var upgrade = lua.Method(region, "0x71D23C7E", resource, weapon); lua.Method(upgrade, "0x02D5AC03", mod.Fingerprint); lua.Set(retained, ++count + 1, upgrade); ExaltedLeases[pointer] = new(suit, pointer, request.Type, request.Config, count, key); lua.Method(weapon, "AddUpgrade", upgrade); } if (trace) log($"Exalted equipment: applied {count} MODs to {request.Type}, config {request.Config}."); } catch { RemoveExaltedLease(lua, root, ExaltedLeases[pointer]); throw; } } private static void RemoveExaltedLease(Scope lua, Ref root, ExaltedLease lease) { var retained = lua.Field(root, lease.Key); if (lua.Kind(retained) == 7) { var weapon = lua.Raw(retained, 1); if (lua.Object(weapon) == lease.Weapon) for (var i = 2; i <= lease.Mods + 1; i++) lua.Method(weapon, "RemoveUpgrade", lua.Raw(retained, i)); lua.Set(root, lease.Key, null); } ExaltedLeases.Remove(lease.Weapon); } private static void ReleaseExaltedEquipment(nint suit, string? type = null) { var leases = ExaltedLeases.Values.Where(x => x.Suit == suit && (type is null || x.Type == type)).ToArray(); if (leases.Length > 0) try { using var lua = new Scope(); var root = ExaltedTable(lua); foreach (var lease in leases) RemoveExaltedLease(lua, root, lease); } catch (Exception ex) { log("Exalted equipment cleanup: " + ex.GetType().Name); } if (type is null) ExaltedRequests.Remove(suit); } private static JsonObject ExaltedSnapshot() => new() { ["weapons"] = new JsonArray(ExaltedLeases.Values.Select(x => (JsonNode)new JsonObject { ["type"] = x.Type, ["config"] = x.Config, ["mods"] = x.Mods, ["weapon"] = $"0x{x.Weapon:X}" }).ToArray()), ["pending"] = ExaltedRequests.Values.Sum(x => x.Count) }; }