XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json.Nodes;
using XFEWarframe.Client;
using static XFEWarframe.Bridge.GameTestLua;

namespace XFEWarframe.Bridge;

internal static unsafe partial class ExperimentalAbilityRuntime
{
    private const string WheelKey = "XFEAbilityWheels";
    private const string WheelMovie = "/Lotus/Interface/PowerSuitCustomHuds/BrokenFrameCustomHud.swf";
    private const string SelectorScript = "/Lotus/Interface/PowerSuitCustomHuds/AbilitySelector.lua";
    private static readonly string[] BrokenCallbacks = ["BROKEN_SetHudSwitchProp", "BROKEN_SetActiveHudIcon",
        "BROKEN_SetHudTimer", "BROKEN_PauseTimer", "BROKEN_UpdateHudTimers", "BROKEN_GetHudLocTag"];
    private static nint hudSuit, hudMovieIdentity;
    private static BankState? hudBank;
    private static long hudNextUpdate, hudNextLayout;
    private static int hudFailures;

    // The profile update hook runs on the original engine thread in production too.
    // Creating UI from SuitInitialize would race HUD loading and remote avatar updates.
    internal static void UpdateHud()
    {
        if (!Available || Environment.TickCount64 < hudNextUpdate) return;
        hudNextUpdate = Environment.TickCount64 + 33;
        try
        {
            using var lua = new Scope();
            var globals = lua.Global("_T");
            if (lua.Kind(globals) != 7) return;
            var root = lua.Field(globals, WheelKey);
            var region = lua.Global("gRegion");
            var avatar = lua.Method(region, "GetLocalPlayerAvatar");
            if (lua.Object(avatar) == 0) { ClearWheels(lua, globals, root); return; }
            var controller = lua.Method(avatar, "InventoryControl");
            var suit = lua.Method(controller, "GetActivePowerSuit");
            var instance = lua.Object(suit);
            var bank = instance == 0 ? null : State(instance);
            if (bank?.Plan.Banks is null || !bank.Plan.Banks.Any(b => b.Length > 1))
            { ClearWheels(lua, globals, root); return; }
            var callback = lua.Field(globals, "SetAbilityDotsDeltaY");
            if (lua.Kind(callback) != 8) return;
            var environment = lua.Call(lua.Global("getfenv"), callback);
            var mainMovie = lua.Field(environment, "mMovie");
            var mainIdentity = lua.Object(mainMovie);
            if (mainIdentity == 0 || hudMovieIdentity != mainIdentity && !ClipExists(lua, mainMovie, "AbilityPanel")) return;

            if (hudSuit != instance || hudBank != bank || hudMovieIdentity != mainIdentity || lua.Kind(root) != 7)
            {
                ClearWheels(lua, globals, root);
                root = lua.Table(0, 16); lua.Set(globals, WheelKey, root);
                lua.Set(root, "mainMovie", mainMovie);
                var saved = lua.Table(0, BrokenCallbacks.Length); lua.Set(root, "callbacks", saved);
                foreach (var name in BrokenCallbacks) lua.Set(saved, name, lua.Field(globals, name));
                lua.Set(root, "selectorScript", lua.Load(SelectorScript));
                var movieType = lua.Load(WheelMovie); lua.Set(root, "movieType", movieType);
                var movie = lua.Method(lua.Global("gFlashMgr"), "0x297A9947", movieType);
                lua.Set(root, "movie", movie);
                lua.Set(root, "selectors", lua.Table(4));
                hudSuit = instance; hudBank = bank; hudMovieIdentity = mainIdentity;
                if (trace) log("Ability wheels: opened original Xaku HUD graphics for the local ability banks.");
            }
            var wheelMovie = lua.Field(root, "movie");
            if (lua.Object(wheelMovie) == 0) { ClearWheels(lua, globals, root); return; }
            var isReady = lua.Boolean(lua.Field(root, "ready"));
            if (!isReady && !ClipExists(lua, wheelMovie, "Container.Ability1.Icon")) return;
            // The graphics movie's original script installs Xaku callbacks at startup.
            // Retain the original callbacks (including a native Xaku's own HUD) and only
            // undo callbacks belonging to our extra movie; never take over its skills.
            if (!lua.Boolean(lua.Field(root, "callbacksRestored"))) RestoreBrokenCallbacks(lua, globals, root, wheelMovie);
            var selectors = lua.Field(root, "selectors");
            if (!isReady) BuildWheels(lua, root, wheelMovie, selectors, bank);
            RefreshWheels(lua, root, mainMovie, wheelMovie, selectors, instance, bank);
            hudFailures = 0;
        }
        catch (Exception ex)
        {
            hudNextUpdate = Environment.TickCount64 + 1000;
            if (++hudFailures <= 3) log("Ability wheels: " + ex.Message);
        }
    }

    private static string Clip(int slot) => "XFEAbilityBank" + (slot + 1);
    private static bool ClipExists(Scope lua, Ref movie, string clip) => lua.Boolean(lua.Method(movie, "0x1DD8A236", clip));
    private static float GetNumber(Scope lua, Ref movie, string clip, int property) => lua.Number(lua.Method(movie, "0xCCE29FC2", clip, property));
    private static void SetNumber(Scope lua, Ref movie, string clip, int property, float value) => lua.Method(movie, "0x9AAB81BF", clip, property, value);
    private static void SetVisible(Scope lua, Ref movie, string clip, bool value) => lua.Method(movie, "0xD9713943", clip, 13, value);
    private static void Flash(Scope lua, Ref movie, string function, params object?[] arguments)
    {
        var library = lua.Require("EE.Interface.Utilities");
        lua.Call(lua.Field(library, "0x5D5FD020", false), [movie, function, .. arguments]);
    }

    private static void RestoreBrokenCallbacks(Scope lua, Ref globals, Ref root, Ref movie)
    {
        var saved = lua.Field(root, "callbacks");
        if (lua.Kind(saved) != 7) return;
        var ownsCallbacks = false;
        foreach (var name in BrokenCallbacks)
        {
            var callback = lua.Field(globals, name);
            if (lua.Kind(callback) != 8) continue;
            var environment = lua.Call(lua.Global("getfenv"), callback);
            if (lua.Object(lua.Field(environment, "mMovie")) == lua.Object(movie))
                ownsCallbacks = true;
        }
        // GetHudLocTag is a selector closure with no mMovie in its environment.
        // Initialization assigns all six callbacks together: restore the whole group
        // when its movie owns the handlers, including this pure selector function.
        if (ownsCallbacks)
        {
            foreach (var name in BrokenCallbacks) lua.Set(globals, name, lua.Field(saved, name));
            lua.Set(root, "callbacksRestored", true);
        }
    }
    private static void ClearWheels(Scope lua, Ref globals, Ref root)
    {
        if (lua.Kind(root) == 7)
        {
            var movie = lua.Field(root, "movie");
            if (lua.Object(movie) != 0)
            {
                RestoreBrokenCallbacks(lua, globals, root, movie);
                // Its original Shutdown clears the callbacks unconditionally. Restore
                // the current callbacks after Close as well, preserving other HUDs.
                var callbacks = lua.Table(0, BrokenCallbacks.Length);
                foreach (var name in BrokenCallbacks) lua.Set(callbacks, name, lua.Field(globals, name));
                lua.Method(movie, "Close");
                foreach (var name in BrokenCallbacks) lua.Set(globals, name, lua.Field(callbacks, name));
            }
            lua.Set(globals, WheelKey, null);
        }
        hudSuit = hudMovieIdentity = 0; hudBank = null; hudNextLayout = 0;
    }
    private static void BuildWheels(Scope lua, Ref root, Ref movie, Ref selectors, BankState bank)
    {
        var factory = lua.Field(lua.Require("Lotus.Interface.PowerSuitCustomHuds.AbilitySelector"), "Create");
        for (var slot = 0; slot < 4; slot++)
        {
            var choices = bank.Plan.Banks![slot];
            if (choices.Length < 2) continue;
            var clip = Clip(slot);
            Flash(lua, movie, "Container.duplicateMovieClip", clip, (1100 + slot).ToString(System.Globalization.CultureInfo.InvariantCulture));
            var selector = lua.Call(factory, movie, clip, slot, "");
            lua.Set(selectors, slot + 1, selector);
            lua.Set(selector, "MAX_ABILITIES", choices.Length);
            lua.Set(selector, "mPowerSuitAbilityLevelCheck", false);
            var icons = lua.Table(choices.Length); lua.Set(selector, "mAbilityIcons", icons);
            var names = lua.Table(choices.Length); lua.Set(selector, "XFEAbilityNames", names);
            for (var choice = 0; choice < choices.Length; choice++)
            {
                var path = TypePath(choices[choice]);
                if (!AbilityHudCatalog.Entries.TryGetValue(path, out var info))
                    throw new InvalidDataException("No wheel icon for " + path);
                lua.Set(icons, choice + 1, lua.Load(info.Icon));
                lua.Set(names, choice + 1, info.Name);
            }
            // Initializers are module methods; selection/progress functions below
            // are closures over this selector and must not receive an implicit self.
            lua.Method(selector, "InitializeAbilities");
            lua.Method(selector, "InitializeAbilityTimers");
            var properties = lua.Field(selector, "mAbilityProperties");
            for (var choice = 0; choice < choices.Length; choice++)
            {
                var property = lua.Raw(properties, choice + 1);
                // The original selector expects a localization Symbol, not a string.
                lua.Set(property, "Name", lua.Call(lua.Global("Symbol"), lua.Raw(names, choice + 1)));
            }
            for (var choice = choices.Length; choice < 4; choice++) SetVisible(lua, movie, clip + ".Ability" + (choice + 1), false);
            SetNumber(lua, movie, clip + ".Progress.Front", 12, 0);
            lua.Set(selector, "XFESelected", -1);
            lua.Set(selector, "XFEProgress", -1);
            if (trace) log($"Ability wheels: slot {slot + 1} has {choices.Length} original ability icons.");
        }
        SetVisible(lua, movie, "Container", false);
        lua.Set(root, "ready", true);
    }
    private static void RefreshWheels(Scope lua, Ref root, Ref mainMovie, Ref movie, Ref selectors, nint suit, BankState bank)
    {
        // Follow the original movie's anchored position and HUD scale instead of desktop
        // pixels. Each wheel has its own icons, tween state and hold progress.
        var positioned = lua.Boolean(lua.Field(root, "positioned"));
        var x = lua.Number(lua.Field(root, "x")); var y = lua.Number(lua.Field(root, "y"));
        var sx = lua.Number(lua.Field(root, "sx")); var sy = lua.Number(lua.Field(root, "sy"));
        var layoutChanged = !positioned;
        // Reading Flash properties synchronizes its render job. Keep idle wheels on
        // queued writes, and poll only occasionally for resolution/HUD scale changes.
        if (!positioned || Environment.TickCount64 >= hudNextLayout)
        {
            hudNextLayout = Environment.TickCount64 + 500;
            var nx = GetNumber(lua, movie, "Container", 0); var ny = GetNumber(lua, movie, "Container", 1);
            var nsx = GetNumber(lua, movie, "Container", 5); var nsy = GetNumber(lua, movie, "Container", 6);
            layoutChanged |= x != nx || y != ny || sx != nsx || sy != nsy;
            x = nx; y = ny; sx = nsx; sy = nsy;
        }
        for (var slot = 0; slot < 4; slot++)
        {
            var selector = lua.Raw(selectors, slot + 1);
            if (lua.Kind(selector) != 7) continue;
            var clip = Clip(slot);
            if (layoutChanged)
            {
                SetNumber(lua, movie, clip, 0, x - (3 - slot) * 135 * sx / 100 - 30 * sx / 100);
                SetNumber(lua, movie, clip, 1, y - 35 * sy / 100);
                SetNumber(lua, movie, clip, 5, sx * .7f); SetNumber(lua, movie, clip, 6, sy * .7f);
                SetNumber(lua, movie, clip, 12, 100); SetVisible(lua, movie, clip, true);
            }
            var selected = bank.Selected[slot];
            var selectionChanged = lua.Number(lua.Field(selector, "XFESelected")) != selected;
            if (selectionChanged)
            {
                lua.Call(lua.Field(selector, "SetActiveAbility"), selected + 1);
                lua.Set(selector, "XFESelected", selected);
                var icons = lua.Field(selector, "mAbilityIcons");
                lua.Method(mainMovie, "0x206E7B0D", "AbilityPanel.Ability" + (slot + 1) + ".Icon", lua.Raw(icons, selected + 1));
            }
            var progress = (float)bank.Gestures[slot].HoldProgress;
            if (selectionChanged || lua.Number(lua.Field(selector, "XFEProgress")) != progress)
            {
                lua.Call(lua.Field(selector, "SetAbilitySwitchProp"), progress);
                lua.Set(selector, "XFEProgress", progress);
                var iconNames = lua.Field(selector, "XFEAbilityNames");
                var name = lua.Text(lua.Raw(iconNames, selected + 1))!;
                var title = name.StartsWith("/Lotus/Language/", StringComparison.Ordinal)
                    ? lua.Text(lua.Method(movie, "0x433F610A", name, false)) : name;
                lua.Method(movie, "0xD8A2BED1", clip + ".Label", 36, (slot + 1) + " · " + title);
            }
        }
        if (layoutChanged)
        {
            lua.Set(root, "x", x); lua.Set(root, "y", y);
            lua.Set(root, "sx", sx); lua.Set(root, "sy", sy); lua.Set(root, "positioned", true);
        }
    }

    internal static JsonObject HudSnapshot()
    {
        using var lua = new Scope();
        var root = lua.Field(lua.Global("_T"), WheelKey);
        var slots = new JsonArray();
        if (lua.Kind(root) != 7) return new() { ["ready"] = false, ["slots"] = slots };
        var movie = lua.Field(root, "movie");
        var selectors = lua.Field(root, "selectors");
        var ready = lua.Boolean(lua.Field(root, "ready")) && lua.Object(movie) != 0;
        if (ready)
            for (var slot = 0; slot < 4; slot++)
            {
                var selector = lua.Raw(selectors, slot + 1);
                if (lua.Kind(selector) != 7) continue;
                var count = (int)lua.Number(lua.Field(selector, "MAX_ABILITIES"));
                var icons = lua.Field(selector, "mAbilityIcons");
                var candidates = new JsonArray();
                for (var index = 0; index < count; index++)
                {
                    var clip = Clip(slot) + ".Ability" + (index + 1);
                    var textureType = lua.ResourceType(lua.Raw(icons, index + 1));
                    candidates.Add((JsonNode)new JsonObject { ["icon"] = textureType == 0 ? null : TypePath(textureType),
                        ["exists"] = ClipExists(lua, movie, clip + ".Icon"), ["x"] = GetNumber(lua, movie, clip, 0),
                        ["y"] = GetNumber(lua, movie, clip, 1), ["scale"] = GetNumber(lua, movie, clip, 5) });
                }
                slots.Add((JsonNode)new JsonObject { ["slot"] = slot, ["selected"] = lua.Number(lua.Field(selector, "XFESelected")),
                    ["progress"] = lua.Number(lua.Field(selector, "mAbilitySwitchProp")), ["candidates"] = candidates,
                    ["visible"] = GetNumber(lua, movie, Clip(slot), 13) != 0,
                    ["x"] = GetNumber(lua, movie, Clip(slot), 0), ["y"] = GetNumber(lua, movie, Clip(slot), 1),
                    ["scale"] = GetNumber(lua, movie, Clip(slot), 5) });
            }
        return new() { ["ready"] = ready, ["movie"] = $"0x{lua.Object(movie):X}", ["slots"] = slots };
    }
}