using System.Runtime.InteropServices;
namespace XFEWarframe.Bridge;
internal static unsafe partial class ExperimentalAbilityRuntime
{
// These abilities read their owner's SPECIAL_A/B/C item descriptions. A host suit's
// descriptions are not interchangeable with the donor's (Jade, for example, reads
// SPECIAL_A before building Glory). Read the donor's actual resource properties,
// including all three slots, rather than guessing weapon categories or offsets.
private static readonly Dictionary<string, string> WeaponDonors = new(StringComparer.Ordinal)
{
["ChoirEruptAbility"] = "Choir/Choir",
["SwordOfDoomAbility"] = "Excalibur/Excalibur",
["LastStandAbility"] = "Berserker/Berserker",
["GunFuAbility"] = "Cowgirl/Cowgirl",
["RangerBowAbility"] = "Ranger/Ranger",
["MonkeyStaffAbility"] = "MonkeyKing/MonkeyKing",
["FairyFlightAbility"] = "Fairy/Fairy",
["PacifistFistAbility"] = "Pacifist/Pacifist",
["IronFrameBlastAbility"] = "IronFrame/IronFrame",
["IronFrameEruptionAbility"] = "IronFrame/IronFrame",
["PagemasterBookAbility"] = "Pagemaster/Pagemaster",
["TempleGuitarAbility"] = "Temple/Temple",
["FrumentariusSniperAbility"] = "Frumentarius/Frumentarius",
["BrawlerPunchAbility"] = "Brawler/Brawler",
["GlassShankAbility"] = "Glass/Glass",
["KhoraCrackAbility"] = "Khora/Khora",
["NinjaStormAbility"] = "Ninja/Ninja"
};
private static nint specialItemLua, pushSpecialItem, specialItem, specialItemMetadata, atomText;
private static readonly Dictionary<nint, string?> DonorsByType = [];
private sealed record AnimationLease(nint Avatar, nint Ability, nint OriginalReference, nint OriginalType, nint DonorType)
{
public double StartupRemaining { get; set; } = 2.2;
public double EndingRemaining { get; set; } = 1.5;
}
private static readonly Dictionary<nint, AnimationLease> AnimationLeases = [];
private static void AdvanceDependencyStartup(nint suit, float seconds)
{
// ChoirErupt's child script waits for AbilityCast and EruptStartDone with
// two one-second timeouts before enabling Glory firing. Keep its ability
// alive across that startup, including a tap immediately after a hold.
if (float.IsFinite(seconds) && seconds > 0 && AnimationLeases.TryGetValue(suit, out var lease))
{
lease.StartupRemaining = Math.Max(0, lease.StartupRemaining - seconds);
if (HasAbility(suit, lease.Ability))
lease.EndingRemaining = *(byte*)(lease.Ability + 0x678) != 0 ? 1.5 : Math.Max(0, lease.EndingRemaining - seconds);
}
}
private static bool DependencyStartupPending(nint suit, nint ability) =>
AnimationLeases.TryGetValue(suit, out var lease) && lease.Ability == ability && lease.StartupRemaining > 0;
internal static string? DescribeResource(nint type) => Available && type != 0 ? TypePath(type) : null;
private static string TypePath(nint type)
{
var parent = *(nint*)(type + 0x10);
var name = Marshal.PtrToStringUTF8(((delegate* unmanaged<nint, nint>)atomText)(type + 0x2C));
var directory = parent == 0 ? "" : Marshal.PtrToStringUTF8(((delegate* unmanaged<nint, nint>)atomText)(parent));
return directory + name;
}
private static nint Owner(nint suit)
{
var reference = *(nint*)(suit + 0xF8);
return reference == 0 ? 0 : *(nint*)reference;
}
private static nint AnimationController(nint avatar) =>
((delegate* unmanaged<nint, nint>)Virtual(avatar, GameAbi.Current.AnimationGetVirtual))(avatar);
private static void SetAnimationController(nint avatar, nint reference, nint type)
{
// The game's Lua setter (RVA 0x19EB8E0) calls this virtual with a strong
// resource/type pair. It rebuilds the graph and inherits the current state.
nint* resource = stackalloc nint[2] { reference, type };
((delegate* unmanaged<nint, nint*, byte, void>)Virtual(avatar, GameAbi.Current.AnimationSetVirtual))(avatar, resource, 0);
}
private static void UseDonorAnimations(nint state, nint suit, nint ability, nint template, string donor)
{
// Jade's sustained flight is part of ChoirAnimController, not her ability's
// start/end animation clips. Other donors retain their existing graph until
// their controller dependencies have also been audited.
if (donor != "/Lotus/Powersuits/Choir/Choir" || AnimationLeases.ContainsKey(suit)) return;
var avatar = Owner(suit); if (avatar == 0) return;
var controller = AnimationController(avatar); if (controller == 0) return;
var donorReference = *(nint*)(template + SuitField(0x37D0));
var donorController = donorReference == 0 ? 0 : *(nint*)donorReference;
if (donorController == 0) return;
var originalType = *(nint*)(controller + 8); var donorType = *(nint*)(donorController + 8);
if (originalType == donorType) return;
var originalReference = GameTestLua.RetainResourceReference(state, TypePath(originalType));
AnimationLeases.Add(suit, new(avatar, ability, originalReference, originalType, donorType));
SetAnimationController(avatar, donorReference, donorType);
if (trace) log("Ability animation: temporary " + TypePath(donorType) + ".");
}
private static void RestoreDonorAnimations(nint suit, bool force = false)
{
if (!AnimationLeases.TryGetValue(suit, out var lease)) return;
// The engine clears IsActive before Choir's end animation/script finishes.
// Rebuilding its graph in that interval cancels the native completion event
// and leaves a retained bank candidate unable to cast a second time.
if (!force && HasAbility(suit, lease.Ability) &&
(*(byte*)(lease.Ability + 0x678) != 0 || lease.EndingRemaining > 0)) return;
AnimationLeases.Remove(suit);
var avatar = Owner(suit);
if (avatar != lease.Avatar || avatar == 0) return;
var controller = AnimationController(avatar);
// A death/transference/cutscene can install a different controller itself.
// Only undo the controller installed by this lease.
if (controller == 0 || *(nint*)(controller + 8) != lease.DonorType) return;
SetAnimationController(avatar, lease.OriginalReference, lease.OriginalType);
if (trace) log("Ability animation: restored " + TypePath(lease.OriginalType) + ".");
}
private static void PrepareDependencies(nint image, Func<string, nint> address, Func<string, nint, nint> hook)
{
GameTestLua.Prepare(image);
specialItemMetadata = image + GameAbi.Current.SpecialItemMetadata;
pushSpecialItem = address("PushSpecialItem"); specialItem = address("SpecialItem"); atomText = address("AtomText");
specialItemLua = hook("SpecialItemLua", (nint)(delegate* unmanaged<nint, int>)&SpecialItemLua);
}
private static string? WeaponDonor(nint suit, int slot, nint instance)
{
if (instance == 0) return null;
var type = *(nint*)(instance + 8);
var defaults = *(nint*)(suit + SuitField(0x3418));
if (defaults == 0 || *(uint*)(suit + SuitField(0x3420)) < (slot + 1) * 16 || *(nint*)(defaults + slot * 16 + 8) == type) return null;
if (DonorsByType.TryGetValue(type, out var donor)) return donor;
var name = Marshal.PtrToStringUTF8(((delegate* unmanaged<nint, nint>)atomText)(type + 0x2C));
donor = name is not null && WeaponDonors.TryGetValue(name, out var path) ? "/Lotus/Powersuits/" + path : null;
if (DonorsByType.Count < 4096) DonorsByType[type] = donor;
return donor;
}
[UnmanagedCallersOnly] private static int SpecialItemLua(nint state)
{
try
{
if (GameTestLua.TrySuitAndSlot(state, out var suit, out var requested) && requested is >= 5 and <= 7)
{
for (var slot = 0; slot < 4; slot++)
{
var candidates = new List<nint> { Instance(suit, slot) };
if (BankStates.TryGetValue(suit, out var bank)) candidates.AddRange(bank.References[slot].Where(r => r != 0).Select(r => *(nint*)r));
foreach (var ability in candidates.Distinct())
{
if (ability == 0 || *(byte*)(ability + 0x678) == 0 || WeaponDonor(suit, slot, ability) is not { } donor) continue;
var template = GameTestLua.RetainResource(state, donor);
var item = ((delegate* unmanaged<nint, byte, nint>)specialItem)(template, (byte)requested);
if (*(nint*)item == 0) continue;
UseDonorAnimations(state, suit, ability, template, donor);
((delegate* unmanaged<nint, nint, nint, void>)pushSpecialItem)(state, *(nint*)specialItemMetadata, item);
try { QueueExaltedEquipment(state, suit, ability); }
catch (Exception ex) { log("Exalted equipment unavailable: " + ex.Message); }
if (trace) log($"Ability dependency: slot {slot + 1} uses {donor}, special slot {requested}.");
return 1;
}
}
}
}
catch (Exception ex) { log("Ability dependency unavailable: " + ex.GetType().Name); }
return ((delegate* unmanaged<nint, int>)specialItemLua)(state);
}
}
using System.Runtime.InteropServices;
namespace XFEWarframe.Bridge;
internal static unsafe partial class ExperimentalAbilityRuntime
{
// These abilities read their owner's SPECIAL_A/B/C item descriptions. A host suit's
// descriptions are not interchangeable with the donor's (Jade, for example, reads
// SPECIAL_A before building Glory). Read the donor's actual resource properties,
// including all three slots, rather than guessing weapon categories or offsets.
private static readonly Dictionary<string, string> WeaponDonors = new(StringComparer.Ordinal)
{
["ChoirEruptAbility"] = "Choir/Choir",
["SwordOfDoomAbility"] = "Excalibur/Excalibur",
["LastStandAbility"] = "Berserker/Berserker",
["GunFuAbility"] = "Cowgirl/Cowgirl",
["RangerBowAbility"] = "Ranger/Ranger",
["MonkeyStaffAbility"] = "MonkeyKing/MonkeyKing",
["FairyFlightAbility"] = "Fairy/Fairy",
["PacifistFistAbility"] = "Pacifist/Pacifist",
["IronFrameBlastAbility"] = "IronFrame/IronFrame",
["IronFrameEruptionAbility"] = "IronFrame/IronFrame",
["PagemasterBookAbility"] = "Pagemaster/Pagemaster",
["TempleGuitarAbility"] = "Temple/Temple",
["FrumentariusSniperAbility"] = "Frumentarius/Frumentarius",
["BrawlerPunchAbility"] = "Brawler/Brawler",
["GlassShankAbility"] = "Glass/Glass",
["KhoraCrackAbility"] = "Khora/Khora",
["NinjaStormAbility"] = "Ninja/Ninja"
};
private static nint specialItemLua, pushSpecialItem, specialItem, specialItemMetadata, atomText;
private static readonly Dictionary<nint, string?> DonorsByType = [];
private sealed record AnimationLease(nint Avatar, nint Ability, nint OriginalReference, nint OriginalType, nint DonorType)
{
public double StartupRemaining { get; set; } = 2.2;
public double EndingRemaining { get; set; } = 1.5;
}
private static readonly Dictionary<nint, AnimationLease> AnimationLeases = [];
private static void AdvanceDependencyStartup(nint suit, float seconds)
{
// ChoirErupt's child script waits for AbilityCast and EruptStartDone with
// two one-second timeouts before enabling Glory firing. Keep its ability
// alive across that startup, including a tap immediately after a hold.
if (float.IsFinite(seconds) && seconds > 0 && AnimationLeases.TryGetValue(suit, out var lease))
{
lease.StartupRemaining = Math.Max(0, lease.StartupRemaining - seconds);
if (HasAbility(suit, lease.Ability))
lease.EndingRemaining = *(byte*)(lease.Ability + 0x678) != 0 ? 1.5 : Math.Max(0, lease.EndingRemaining - seconds);
}
}
private static bool DependencyStartupPending(nint suit, nint ability) =>
AnimationLeases.TryGetValue(suit, out var lease) && lease.Ability == ability && lease.StartupRemaining > 0;
internal static string? DescribeResource(nint type) => Available && type != 0 ? TypePath(type) : null;
private static string TypePath(nint type)
{
var parent = *(nint*)(type + 0x10);
var name = Marshal.PtrToStringUTF8(((delegate* unmanaged<nint, nint>)atomText)(type + 0x2C));
var directory = parent == 0 ? "" : Marshal.PtrToStringUTF8(((delegate* unmanaged<nint, nint>)atomText)(parent));
return directory + name;
}
private static nint Owner(nint suit)
{
var reference = *(nint*)(suit + 0xF8);
return reference == 0 ? 0 : *(nint*)reference;
}
private static nint AnimationController(nint avatar) =>
((delegate* unmanaged<nint, nint>)Virtual(avatar, GameAbi.Current.AnimationGetVirtual))(avatar);
private static void SetAnimationController(nint avatar, nint reference, nint type)
{
// The game's Lua setter (RVA 0x19EB8E0) calls this virtual with a strong
// resource/type pair. It rebuilds the graph and inherits the current state.
nint* resource = stackalloc nint[2] { reference, type };
((delegate* unmanaged<nint, nint*, byte, void>)Virtual(avatar, GameAbi.Current.AnimationSetVirtual))(avatar, resource, 0);
}
private static void UseDonorAnimations(nint state, nint suit, nint ability, nint template, string donor)
{
// Jade's sustained flight is part of ChoirAnimController, not her ability's
// start/end animation clips. Other donors retain their existing graph until
// their controller dependencies have also been audited.
if (donor != "/Lotus/Powersuits/Choir/Choir" || AnimationLeases.ContainsKey(suit)) return;
var avatar = Owner(suit); if (avatar == 0) return;
var controller = AnimationController(avatar); if (controller == 0) return;
var donorReference = *(nint*)(template + SuitField(0x37D0));
var donorController = donorReference == 0 ? 0 : *(nint*)donorReference;
if (donorController == 0) return;
var originalType = *(nint*)(controller + 8); var donorType = *(nint*)(donorController + 8);
if (originalType == donorType) return;
var originalReference = GameTestLua.RetainResourceReference(state, TypePath(originalType));
AnimationLeases.Add(suit, new(avatar, ability, originalReference, originalType, donorType));
SetAnimationController(avatar, donorReference, donorType);
if (trace) log("Ability animation: temporary " + TypePath(donorType) + ".");
}
private static void RestoreDonorAnimations(nint suit, bool force = false)
{
if (!AnimationLeases.TryGetValue(suit, out var lease)) return;
// The engine clears IsActive before Choir's end animation/script finishes.
// Rebuilding its graph in that interval cancels the native completion event
// and leaves a retained bank candidate unable to cast a second time.
if (!force && HasAbility(suit, lease.Ability) &&
(*(byte*)(lease.Ability + 0x678) != 0 || lease.EndingRemaining > 0)) return;
AnimationLeases.Remove(suit);
var avatar = Owner(suit);
if (avatar != lease.Avatar || avatar == 0) return;
var controller = AnimationController(avatar);
// A death/transference/cutscene can install a different controller itself.
// Only undo the controller installed by this lease.
if (controller == 0 || *(nint*)(controller + 8) != lease.DonorType) return;
SetAnimationController(avatar, lease.OriginalReference, lease.OriginalType);
if (trace) log("Ability animation: restored " + TypePath(lease.OriginalType) + ".");
}
private static void PrepareDependencies(nint image, Func<string, nint> address, Func<string, nint, nint> hook)
{
GameTestLua.Prepare(image);
specialItemMetadata = image + GameAbi.Current.SpecialItemMetadata;
pushSpecialItem = address("PushSpecialItem"); specialItem = address("SpecialItem"); atomText = address("AtomText");
specialItemLua = hook("SpecialItemLua", (nint)(delegate* unmanaged<nint, int>)&SpecialItemLua);
}
private static string? WeaponDonor(nint suit, int slot, nint instance)
{
if (instance == 0) return null;
var type = *(nint*)(instance + 8);
var defaults = *(nint*)(suit + SuitField(0x3418));
if (defaults == 0 || *(uint*)(suit + SuitField(0x3420)) < (slot + 1) * 16 || *(nint*)(defaults + slot * 16 + 8) == type) return null;
if (DonorsByType.TryGetValue(type, out var donor)) return donor;
var name = Marshal.PtrToStringUTF8(((delegate* unmanaged<nint, nint>)atomText)(type + 0x2C));
donor = name is not null && WeaponDonors.TryGetValue(name, out var path) ? "/Lotus/Powersuits/" + path : null;
if (DonorsByType.Count < 4096) DonorsByType[type] = donor;
return donor;
}
[UnmanagedCallersOnly] private static int SpecialItemLua(nint state)
{
try
{
if (GameTestLua.TrySuitAndSlot(state, out var suit, out var requested) && requested is >= 5 and <= 7)
{
for (var slot = 0; slot < 4; slot++)
{
var candidates = new List<nint> { Instance(suit, slot) };
if (BankStates.TryGetValue(suit, out var bank)) candidates.AddRange(bank.References[slot].Where(r => r != 0).Select(r => *(nint*)r));
foreach (var ability in candidates.Distinct())
{
if (ability == 0 || *(byte*)(ability + 0x678) == 0 || WeaponDonor(suit, slot, ability) is not { } donor) continue;
var template = GameTestLua.RetainResource(state, donor);
var item = ((delegate* unmanaged<nint, byte, nint>)specialItem)(template, (byte)requested);
if (*(nint*)item == 0) continue;
UseDonorAnimations(state, suit, ability, template, donor);
((delegate* unmanaged<nint, nint, nint, void>)pushSpecialItem)(state, *(nint*)specialItemMetadata, item);
try { QueueExaltedEquipment(state, suit, ability); }
catch (Exception ex) { log("Exalted equipment unavailable: " + ex.Message); }
if (trace) log($"Ability dependency: slot {slot + 1} uses {donor}, special slot {requested}.");
return 1;
}
}
}
}
catch (Exception ex) { log("Ability dependency unavailable: " + ex.GetType().Name); }
return ((delegate* unmanaged<nint, int>)specialItemLua)(state);
}
}