using System.Text.Json.Nodes;
using XFEWarframe.Mods;
using static XFEWarframe.Bridge.GameTestLua;
namespace XFEWarframe.Bridge;
/// Uses the original local Fetch trigger; no remote pickup grants or resource-template edits.
internal static unsafe class PetFetchRuntime
{
private const string Root = "XFEFetchOverdriveTriggers";
private sealed record Lease(nint Pointer, FetchRadiusLease Radius);
private static readonly Dictionary Leases = new(StringComparer.Ordinal);
private static long nextTick;
private static long nextOwnershipCheck;
private static int scanIndex;
private static string selection = "", message = "等待宠物配装";
private static string stage = "initialization";
private static bool equipped;
private static int failures;
internal static JsonObject Snapshot() => new() { ["equipped"] = equipped, ["radius"] = PetFetchMod.Radius,
["triggers"] = Leases.Count, ["message"] = message };
internal static void Update()
{
if (!GameAbi.Current.FetchAvailable || Environment.TickCount64 < nextTick) return;
nextTick = Environment.TickCount64 + 250;
try
{
using var lua = new Scope();
var globals = lua.Global("_T");
if (lua.Kind(globals) != 7) return;
stage = "local avatar";
var region = lua.Global("gRegion");
if (lua.Object(region) == 0) return;
var avatar = lua.Method(region, "GetLocalPlayerAvatar");
var root = lua.Field(globals, Root);
if (lua.Kind(root) != 7) { root = lua.Table(fields: 8); lua.Set(globals, Root, root); }
if (lua.Object(avatar) == 0)
{
ClearSelection(lua, root, "等待游戏登录"); return;
}
var data = lua.Global("gGameData");
if (lua.Object(data) == 0) { ClearSelection(lua, root, "等待游戏资料"); return; }
stage = "selected companion";
var loadout = lua.Method(data, "GetLoadOut");
// SENTINEL group 1, suit slot 0 includes the selected beast companion.
var selected = lua.Method(loadout, "0xB2A2BA51", 1, 0);
// GetItem returns a LoadOutItem wrapper. The owned item is mItem;
// mItemId belongs to that item, not to the wrapper.
var petId = ItemId(lua, lua.Field(selected, "mItem"));
var config = lua.Number(lua.Field(selected, "mModSlot"));
if (petId.Length != 24 || petId == new string('0', 24) || config is < 0 or > 5 || config != MathF.Truncate(config))
{ ClearSelection(lua, root, "未选择宠物"); return; }
stage = "owned companion";
var inventory = lua.Method(data, "GetInventory");
var petGetter = lua.KnownMethod(inventory, "GetKubrowPets", 0x1B46520)
?? throw new InvalidDataException("Fetch pet inventory ABI changed.");
var pets = lua.Call(petGetter, inventory);
Ref? pet = null; var mark = lua.Count;
for (var i = 1; i <= 4096; i++)
{
var candidate = lua.Raw(pets, i); if (lua.Kind(candidate) == 0) break;
if (ItemId(lua, candidate) == petId) { pet = candidate; break; }
lua.Rewind(mark);
}
if (pet is null)
{ ClearSelection(lua, root, "当前伙伴不是适用宠物"); return; }
stage = "installed companion mods";
var slots = lua.Method(pet.Value, "0xBFBBF8CE", (int)config, false);
var ids = new HashSet(StringComparer.Ordinal); mark = lua.Count;
for (var i = 1; i <= 10; i++)
{
var slot = lua.Raw(slots, i); if (lua.Kind(slot) == 0) break;
var id = lua.Text(lua.Field(lua.Field(slot, "mId"), "mId"));
if (id is { Length: 24 } && id != new string('0', 24)) ids.Add(id);
lua.Rewind(mark);
}
var key = $"{lua.Object(avatar):X}:" + petId + ":" + config + ":" + string.Join(',', ids.Order(StringComparer.Ordinal));
if (selection != key)
{
Restore(lua, root);
equipped = false; scanIndex = 0; nextOwnershipCheck = 0;
selection = key;
}
if (scanIndex == 0 && Environment.TickCount64 >= nextOwnershipCheck)
{
nextOwnershipCheck = Environment.TickCount64 + 10000;
lua.Set(root, "ownedScan", ids.Count == 0 ? null : lua.Method(inventory, "GetUpgrades"));
scanIndex = ids.Count == 0 ? 0 : 1;
if (ids.Count == 0) equipped = false;
}
stage = "owned Fetch card";
if (scanIndex > 0 && ScanInstalledCard(lua, root, ids) is { } found) equipped = found;
if (!equipped)
{
Restore(lua, root);
message = scanIndex > 0 ? "正在读取宠物 MOD" : "当前宠物配置未装备吸回·超域";
return;
}
stage = "native Fetch trigger";
var triggers = lua.Field(globals, "gSuckTriggers");
if (lua.Kind(triggers) != 7) { Restore(lua, root); message = "等待原版吸回触发器"; return; }
// WarframeSuckAbility creates these only for its locally controlled master.
// Ignore the Sentinel/Mag triggers sharing this table and disabled old pets.
var table = lua.Identity(triggers); var bits = *(byte*)(table + 6);
if (bits > 8) throw new InvalidDataException("Unexpected Fetch trigger table.");
var nodes = *(nint*)(table + 0x20); var seen = new HashSet(StringComparer.Ordinal);
mark = lua.Count;
for (var i = 0; nodes != 0 && i < 1 << bits; i++)
{
var node = nodes + i * 32;
if (*(int*)(node + 12) != 9 || *(int*)(node + 28) != 6) continue;
var name = lua.Text(lua.RawValue(node + 16));
if (name is null || !name.Contains("PetAvatar", StringComparison.Ordinal)) { lua.Rewind(mark); continue; }
var trigger = lua.RawValue(node); var pointer = lua.Object(trigger);
if (pointer == 0 || !lua.Boolean(lua.Method(trigger, "IsEnabled"))) { lua.Rewind(mark); continue; }
var get = lua.KnownMethod(trigger, "GetRadius", 0x19CAEC0);
var set = lua.KnownMethod(trigger, "SetRadius", 0x19CB3E0);
if (get is null || set is null) throw new InvalidDataException("Fetch radius ABI changed.");
var radius = lua.Number(lua.Call(get.Value, trigger));
if (!Leases.TryGetValue(name, out var lease) || lease.Pointer != pointer)
{
if (Leases.ContainsKey(name)) RestoreOne(lua, root, name);
if (radius == PetFetchMod.Radius) { lua.Rewind(mark); continue; }
lease = new(pointer, FetchRadiusLease.Capture(radius));
Leases[name] = lease; lua.Set(root, name, trigger);
}
else Leases[name] = lease with { Radius = lease.Radius.Observe(radius) };
if (radius != PetFetchMod.Radius) lua.Call(set.Value, trigger, PetFetchMod.Radius);
if (lua.Number(lua.Call(get.Value, trigger)) != PetFetchMod.Radius)
throw new InvalidOperationException("Native Fetch radius did not accept 300 metres.");
seen.Add(name); lua.Rewind(mark);
}
foreach (var stale in Leases.Keys.Where(x => !seen.Contains(x)).ToArray()) RestoreOne(lua, root, stale);
message = Leases.Count > 0 ? "300 米原版拾取触发器已启用" : "等待原版宠物吸回触发器";
failures = 0;
}
catch (Exception ex)
{
selection = ""; equipped = false; scanIndex = 0; nextOwnershipCheck = 0; message = stage + ": " + ex.Message;
nextTick = Environment.TickCount64 + 2000;
try
{
using var cleanup = new Scope(); var root = cleanup.Field(cleanup.Global("_T"), Root);
Restore(cleanup, root);
if (cleanup.Kind(root) == 7) cleanup.Set(root, "ownedScan", null);
}
catch { /* Retry cleanup before applying a new selection on the next engine tick. */ }
if (++failures <= 3) Bootstrap.Log("Fetch Overdrive: " + message);
}
}
private static string ItemId(Scope lua, Ref item)
{
if (lua.Kind(item) != 9) return "";
var id = lua.Field(item, "mItemId");
return lua.Kind(id) == 9 ? lua.Text(lua.Field(id, "mId")) ?? "" : "";
}
private static bool? ScanInstalledCard(Scope lua, Ref root, HashSet ids)
{
var cards = lua.Field(root, "ownedScan"); var mark = lua.Count;
if (lua.Kind(cards) != 7) { scanIndex = 0; return false; }
// A large imported inventory must not monopolize an engine frame.
for (var count = 0; count < 512; count++, scanIndex++)
{
if (scanIndex > 65536)
{ scanIndex = 0; lua.Set(root, "ownedScan", null); return false; }
var card = lua.Raw(cards, scanIndex);
if (lua.Kind(card) == 0)
{ scanIndex = 0; lua.Set(root, "ownedScan", null); return false; }
if (ids.Contains(ItemId(lua, card)) && PetFetchMod.HasMarker(lua.Text(lua.Field(card, "mUpgradeFingerprint"))) &&
lua.Text(lua.Method(lua.Field(card, "mItemType"), "GetFullName")) == PetFetchMod.Carrier)
{ scanIndex = 0; lua.Set(root, "ownedScan", null); return true; }
lua.Rewind(mark);
}
return null;
}
private static void ClearSelection(Scope lua, Ref root, string status)
{
Restore(lua, root); lua.Set(root, "ownedScan", null);
selection = ""; equipped = false; scanIndex = 0; nextOwnershipCheck = 0; message = status;
}
private static void Restore(Scope lua, Ref root)
{
foreach (var name in Leases.Keys.ToArray()) RestoreOne(lua, root, name);
}
private static void RestoreOne(Scope lua, Ref root, string name)
{
if (!Leases.TryGetValue(name, out var lease)) return;
if (lua.Kind(root) == 7)
{
var trigger = lua.Field(root, name);
if (lua.Object(trigger) == lease.Pointer)
{
var get = lua.KnownMethod(trigger, "GetRadius", 0x19CAEC0);
var set = lua.KnownMethod(trigger, "SetRadius", 0x19CB3E0);
if (get is null || set is null) throw new InvalidDataException("Fetch cleanup ABI changed.");
if (lease.Radius.Restore(lua.Number(lua.Call(get.Value, trigger))) is { } radius) lua.Call(set.Value, trigger, radius);
}
lua.Set(root, name, null);
}
Leases.Remove(name);
}
}