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

XFEWarframe

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

公开
关注 0 Fork 0 Star 0
UTF-8
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
using XFEWarframe.Loadouts;

namespace XFEWarframe.Core.Services;

public sealed partial class AccountEditor
{
    private static bool HasModding(string category, JObject item) => category is "Suits" or "LongGuns" or "Pistols" or "Melee" or "KubrowPets" ||
        category == "SpecialItems" && ExaltedModFamily(item.RequiredString("ItemType")) is not null;

    private void AddModdingActions(JArray actions, string category, JObject item)
    {
        if (!HasModding(category, item)) return;
        for (var index = 0; index < 3 + Math.Clamp(item.Value<int>("ModSlotPurchases"), 0, 3); index++)
        {
            var config = (item["Configs"] as JArray)?.ElementAtOrDefault(index) as JObject;
            var fields = ModSlots(category, item).Select(slot => Text("mod" + slot.Index, "MOD 槽 " + slot.Index,
                config?["Upgrades"]?.ElementAtOrDefault(slot.Index)?.ToString() ?? "")).ToArray();
            var action = Action("loadout.mods." + index, "配置 " + (char)('A' + index),
                [Text("name", "配装名称", config?.Value<string>("Name") ?? ""), .. fields]);
            action["description"] = "拖动卡片安装、交换或卸下。仅使用当前账号持有的兼容 MOD,保存后重新登录游戏加载。";
            actions.Add(action);
        }
    }

    private static ModSlot[] ModSlots(string category, JObject gear, JObject? inventory = null)
    {
        var features = gear.Value<int>("Features");
        var exilusLocked = (features & 2) == 0 && inventory?.Value<bool>("unlockExilusEverywhere") != true;
        var arcaneLocked = (features & 32) == 0 && inventory?.Value<bool>("unlockArcanesEverywhere") != true;
        var slots = Enumerable.Range(0, category == "KubrowPets" ? 10 : 8).Select(i => new ModSlot(i, ModSlotKind.Normal, Polarity(i))).ToList();
        if (category == "Suits")
        {
            slots.Add(new(8, ModSlotKind.Aura, Polarity(8)));
            slots.Add(new(9, ModSlotKind.Exilus, Polarity(9), exilusLocked));
            slots.Add(new(10, ModSlotKind.Arcane, "")); slots.Add(new(11, ModSlotKind.Arcane, ""));
        }
        if (category is "LongGuns" or "Pistols")
        {
            slots.Add(new(8, ModSlotKind.Exilus, Polarity(8), exilusLocked));
            slots.Add(new(9, ModSlotKind.Arcane, "", arcaneLocked));
        }
        if (category == "Melee")
        {
            slots.Add(new(8, ModSlotKind.Stance, Polarity(8)));
            slots.Add(new(9, ModSlotKind.Exilus, Polarity(9), exilusLocked));
            slots.Add(new(10, ModSlotKind.Arcane, "", arcaneLocked));
        }
        return slots.ToArray();
        string Polarity(int index) => (gear["Polarity"] as JArray ?? []).OfType<JObject>()
            .FirstOrDefault(x => x.Value<int>("Slot") == index)?.Value<string>("Value") ?? "AP_UNIVERSAL";
    }

    private static bool CompatibleMod(string category, JObject gear, JObject mod, ModSlotKind kind)
    {
        var type = mod.RequiredString("ItemType"); var arcane = GameData.Find("Arcanes", type);
        if (kind == ModSlotKind.Arcane)
        {
            if (arcane is null) return false;
            // The export does not contain arcane ancestry. Use the exported equipment families;
            // classic frame enhancers have Defensive/Offensive/Utility paths, weapon arcanes are named by family.
            var family = type.Split('/').Last();
            if (category == "LongGuns") return family.StartsWith("Primary", StringComparison.Ordinal);
            if (category == "Pistols") return family.StartsWith("Secondary", StringComparison.Ordinal) || family is "ExtraProcOnProc";
            if (category == "Melee") return family.StartsWith("Melee", StringComparison.Ordinal);
            return category == "Suits" && !family.StartsWith("Primary", StringComparison.Ordinal) && !family.StartsWith("Secondary", StringComparison.Ordinal) &&
                !family.StartsWith("Melee", StringComparison.Ordinal) && !type.Contains("/Operator", StringComparison.Ordinal) &&
                !type.Contains("/Amp", StringComparison.Ordinal) && family is not "ExtraProcOnProc" &&
                (type.Contains("/Defensive/", StringComparison.Ordinal) || type.Contains("/Offensive/", StringComparison.Ordinal) || type.Contains("/Utility/", StringComparison.Ordinal));
        }
        if (arcane is not null) return false;
        var meta = ModMetadata(type); if (meta is null) return false;
        var modFamily = meta.Value<string>("type");
        if (kind == ModSlotKind.Aura && modFamily != "AURA" || kind != ModSlotKind.Aura && modFamily == "AURA") return false;
        if (kind == ModSlotKind.Stance && modFamily != "STANCE" || kind != ModSlotKind.Stance && modFamily == "STANCE") return false;
        if (kind == ModSlotKind.Exilus && !meta.Value<bool>("isUtility")) return false;
        if (category == "SpecialItems") return kind == ModSlotKind.Normal && ExaltedModCompatible(gear.RequiredString("ItemType"), mod);
        var compatibility = meta.Value<string>("compat");
        if (category == "KubrowPets" && compatibility == "/Lotus/Types/Game/Pets/PetPowerSuit") return true;
        if (category == "Suits" && compatibility == "/Lotus/Types/Game/PowerSuits/PlayerPowerSuit") return true;
        var seen = new HashSet<string>(); var current = gear.RequiredString("ItemType");
        while (seen.Add(current))
        {
            if (current == compatibility) return true;
            var parent = (GameData.Find("Weapons", current) ?? GameData.Find("Warframes", current))?.Value<string>("parentName");
            if (string.IsNullOrEmpty(parent)) break; current = parent;
        }
        // Generic roots are omitted from the public export's parent table.
        return category switch
        {
            "Pistols" => compatibility == "/Lotus/Weapons/Tenno/Pistol/LotusPistol",
            "Melee" when kind != ModSlotKind.Stance => compatibility == "/Lotus/Weapons/Tenno/Melee/PlayerMeleeWeapon",
            "LongGuns" when !seen.Contains("/Lotus/Weapons/Tenno/Shotgun/LotusShotgun") => compatibility is "/Lotus/Weapons/Tenno/Rifle/LotusRifle" or "/Lotus/Weapons/Tenno/LotusLongGun",
            _ => false
        };
    }

    private ModLoadout ModdingLayout(string category, JObject gear, JObject inv)
    {
        var slots = ModSlots(category, gear, inv); var cards = new List<ModCard>();
        var equipped = (gear["Configs"] as JArray ?? []).SelectMany(x => x["Upgrades"] as JArray ?? []).Select(x => x.ToString()).ToHashSet(StringComparer.Ordinal);
        foreach (var entry in inv.Array("Upgrades").OfType<JObject>().Concat(inv.Array("RawUpgrades").OfType<JObject>().Where(x => x.Value<int>("ItemCount") > 0)))
        {
            var type = entry.RequiredString("ItemType"); var meta = ModMetadata(type) ?? GameData.Find("Arcanes", type);
            if (meta is null) continue;
            var raw = entry["ItemId"] is null; var key = raw ? "raw:" + type : Wire.Id(entry["ItemId"]);
            var compatible = slots.Where(x => CompatibleMod(category, gear, entry, x.Kind)).Select(x => x.Index).ToArray();
            if (compatible.Length == 0 && !equipped.Contains(key)) continue;
            var fingerprint = entry.Value<string>("UpgradeFingerprint") ?? "{\"lvl\":0}";
            int rank; try { rank = JObject.Parse(fingerprint).Value<int>("lvl"); } catch { rank = 0; }
            var baseDrain = meta.Value<int>("baseDrain"); var drain = baseDrain < 0 ? baseDrain - rank : baseDrain + rank;
            var searchable = ModSearchText.For(entry, meta, catalog);
            cards.Add(new(key, type, Name(entry), meta.Value<string>("type") ?? "ARCANE", meta.Value<string>("baseUpgrade") ?? type,
                rank, meta.Value<int>("fusionLimit"), drain, meta.Value<string>("polarity") ?? "AP_UNIVERSAL", meta.Value<string>("rarity") ?? "",
                meta.Value<string>("icon") ?? "", fingerprint, raw ? entry.Value<int>("ItemCount") : 1, compatible, searchable.Text, searchable.Elements));
        }
        var frame = category is "Suits" or "KubrowPets";
        var metaGear = GameData.Find(category == "Suits" ? "Warframes" : category == "KubrowPets" ? "Sentinels" : "Weapons", gear.RequiredString("ItemType"));
        var rankMaximum = metaGear?.Value<int?>("maxLevelCap") ?? 30;
        var gearRank = Math.Min(rankMaximum, (int)Math.Sqrt(Math.Max(0, gear.Value<long>("XP")) / (frame ? 1000d : 500d)));
        var mastery = Math.Clamp(inv.Value<int>("PlayerLevel"), 0, rankMaximum);
        var capacity = Math.Max(gearRank, mastery) * (((gear.Value<int>("Features") & 1) != 0 || inv.Value<bool>("unlockDoubleCapacityPotatoesEverywhere")) ? 2 : 1);
        // Innate polarities are not part of PublicExport. Explicit inventory polarities permit an exact check;
        // otherwise display the conservative estimate without rejecting a legitimate native loadout.
        var known = slots.Where(x => x.Kind != ModSlotKind.Arcane).All(x => (gear["Polarity"] as JArray ?? []).Any(p => p.Value<int>("Slot") == x.Index));
        return new(capacity, known, slots, cards.ToArray());
    }

    private JObject ModdingView(string category, JObject gear, JObject inv)
    {
        var layout = ModdingLayout(category, gear, inv);
        var result = JObject.FromObject(layout, JsonSerializer.Create(new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }));
        foreach (var slot in result.Array("slots")) slot["kind"] = layout.Slots.Single(x => x.Index == slot.Value<int>("index")).Kind.ToString();
        result["configurations"] = new JArray(Enumerable.Range(0, 3 + Math.Clamp(gear.Value<int>("ModSlotPurchases"), 0, 3)).Select(i => new JObject {
            ["index"] = i, ["name"] = (gear["Configs"] as JArray)?.ElementAtOrDefault(i)?.Value<string>("Name") ?? ""
        }));
        return result;
    }

    private void SaveModding(string category, JObject gear, JObject inv, int index, JObject values)
    {
        var layout = ModdingLayout(category, gear, inv);
        var config = (gear["Configs"] as JArray)?.ElementAtOrDefault(index) as JObject;
        var original = layout.Slots.ToDictionary(x => x.Index, x => config?["Upgrades"]?.ElementAtOrDefault(x.Index)?.ToString() ?? "");
        var selected = layout.Slots.ToDictionary(x => x.Index, x => values.Value<string>("mod" + x.Index)!);
        var name = values.Value<string>("name")!.Trim();
        if (name.Length > 100 || name.Any(char.IsControl)) throw new ApiException(400, "配装名称无效。");
        if (ModLoadoutRules.Validate(layout, selected, original) is { } error) throw new ApiException(400, error);
        // Resolve all choices and verify counts before any mutation; a raw card becomes one owned UID.
        var resolved = new Dictionary<int, string>(selected);
        foreach (var (slot, key) in selected.Where(x => x.Value.StartsWith("raw:", StringComparison.Ordinal)))
        {
            var type = key[4..]; var raw = inv.Array("RawUpgrades").FirstOrDefault(x => x.Value<string>("ItemType") == type);
            if (raw?.Value<int>("ItemCount") is not > 0) throw new ApiException(400, "未升级 MOD 数量不足。");
            resolved[slot] = Wire.NewId();
        }
        foreach (var (slot, key) in selected.Where(x => x.Value.StartsWith("raw:", StringComparison.Ordinal)))
        {
            Inventory.AddCount(inv, "RawUpgrades", key[4..], -1);
            inv.Array("Upgrades").Add(new JObject { ["ItemId"] = Wire.Oid(resolved[slot]), ["ItemType"] = key[4..], ["UpgradeFingerprint"] = "{\"lvl\":0}" });
        }
        var configs = gear.Array("Configs"); while (configs.Count <= index) configs.Add(new JObject());
        config = (JObject)configs[index]; var upgrades = config.Array("Upgrades");
        foreach (var (slot, key) in resolved) { while (upgrades.Count <= slot) upgrades.Add(""); upgrades[slot] = key; }
        config["Name"] = name;
    }
}