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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public static class WorldClassicAlerts
{
    private static readonly Lazy<JObject> Data = new(() => (JObject)Assets.Json("editor/world-events.json")["classic"]!);
    private const long Interval = 25 * 60000;
    private static readonly string[] MissionTypes = ["MT_SURVIVAL", "MT_DEFENSE", "MT_RESCUE", "MT_CAPTURE", "MT_EXTERMINATION", "MT_SABOTAGE", "MT_MOBILE_DEFENSE", "MT_INTEL"];
    private static readonly (string Match, string Version)[] HelmetVersions = [("BardAlt", "20.0.0"), ("NidusAlt", "19.5.3"), ("FairyAlt", "19.0.1"), ("WukongAlt", "18.0.2"), ("BrawlerAlt", "17.7.1"), ("SandmanAlt", "18.5.0"), ("NezhaAlt", "18.0.2"), ("RangerAlt", "18.0.2"), ("AnimaAlt", "17.7.1"), ("ChromaAlt", "16.0.2"), ("DragonAlt", "16.0.2"), ("MesaAlt", "15.5.0"), ("CowgirlAlt", "15.5.0"), ("LimboAlt", "15.0.0"), ("LimboAristeas", "15.0.0"), ("HarlequinAlt", "14.0.0"), ("MirageAlt", "14.0.0"), ("PirateAlt", "13.0.0"), ("Zephyr", "12.1.2"), ("Oberon", "11.1.3"), ("Valkyr", "11.1.3"), ("V2", "9.0.0"), ("Vauban", "8.0.0"), ("Excalibur", "7.7.1"), ("Nyx", "7.7.1"), ("Frost", "7.7.1"), ("Saryn", "7.7.1"), ("Banshee", "7.7.1")];

    private static bool Arch(JObject node) => (node.Value<string>("name") ?? "").Contains("Archwing", StringComparison.Ordinal) || node.Value<string>("missionType") == "MT_RACE";
    private static string[] Pool(string name) => Data.Value[name]!.Values<string>().OfType<string>().ToArray();
    private static string Helmet(string path, long build)
    {
        path = GameData.ItemType(path);
        var candidate = build < GameVersion.Of("13.2.3") ? path.Replace("Statless", "", StringComparison.Ordinal) : path.Contains("Statless", StringComparison.Ordinal) ? path : path.Replace("/Helmets/", "/Helmets/Statless", StringComparison.Ordinal);
        return GameData.Find("Recipes", candidate) is not null ? candidate : path;
    }
    private static string LegacyReward(string item, long build)
    {
        if (build >= GameVersion.Of("14.0.0")) return item;
        var filename = item.Split('/').Last();
        if (filename == "FormaBlueprint") return "/Lotus/Types/Recipes/Components/FormaBlueprintStoreItem";
        if (filename == "OrokinReactorBlueprint") return build < GameVersion.Of("13.0.0") ? "/Lotus/Types/StoreItems/Recipes/OrokinReactorBlueprintStoreItem" : "/Lotus/Types/Recipes/Components/OrokinReactorBlueprintStoreItem";
        if (filename == "OrokinCatalystBlueprint") return "/Lotus/Types/StoreItems/Recipes/OrokinCatalystBlueprintStoreItem";
        if (item.StartsWith("/Lotus/StoreItems/Recipes/WarframeRecipes/", StringComparison.Ordinal)) return "/Lotus/Types/Recipes/WarframeRecipes/" + filename + "StoreItem";
        if (item.EndsWith("Blueprint", StringComparison.Ordinal)) return "/Lotus/Types/StoreItems/Recipes/" + filename + "StoreItem";
        if (item.EndsWith("Buff", StringComparison.Ordinal)) return "/Lotus/Types/StoreItems/Cards/" + filename + "StoreItem";
        return item;
    }
    public static JObject Generate(int index, long build)
    {
        if (index < 0 || index > 0xffffff) throw new ApiException(400, "Invalid alert index");
        bool Since(string version) => build >= GameVersion.Of(version);
        var seed = new SeededRng(index * 2654435761L).Int(0, 100000); var rng = new SeededRng(seed); var regions = GameData.Table("Regions");
        var validTypes = MissionTypes.Concat(["MT_EXCAVATE", "MT_TERRITORY", "MT_PURSUIT", "MT_RACE"]).ToHashSet();
        var nodes = regions.Properties().Where(x => (x.Name.StartsWith("SolNode", StringComparison.Ordinal) || x.Name.StartsWith("SettlementNode", StringComparison.Ordinal)) && x.Value.Value<int>("nodeType") == 0
            && validTypes.Contains(x.Value.Value<string>("missionType")!) && new[] { "FC_GRINEER", "FC_CORPUS", "FC_INFESTATION", "FC_OROKIN" }.Contains(x.Value.Value<string>("faction"))
            && x.Value.Value<int>("systemIndex") is not 16 and <= 18 && GameVersion.RegionAvailable(x.Name, (JObject)x.Value, build)).Select(x => x.Name).ToArray();
        var node = SeededRng.Sequential(nodes, index, 10, 569354); var nodeData = (JObject)regions[node]!; var arch = Arch(nodeData); var old = !Since("14.0.0");
        var faction = rng.Int(0, 9) < 7 ? nodeData.Value<string>("faction")! : rng.Element(arch ? new[] { "FC_GRINEER", "FC_CORPUS" } : new[] { "FC_GRINEER", "FC_CORPUS", "FC_INFESTATION" });
        var missionType = old || rng.Int(0, 9) < 7 ? nodeData.Value<string>("missionType")! : rng.Element(MissionTypes);
        var level = nodeData.Value<string>("levelOverride"); var enemy = nodeData.Value<string>("enemySpec"); var extra = nodeData.Value<string>("extraEnemySpec");
        if (missionType != nodeData.Value<string>("missionType")) level = null;
        if (arch) missionType = rng.Element(faction == "FC_GRINEER" ? new[] { "MT_EXTERMINATION", "MT_MOBILE_DEFENSE", "MT_TERRITORY", "MT_PURSUIT" } : new[] { "MT_EXTERMINATION", "MT_MOBILE_DEFENSE", "MT_SABOTAGE", "MT_RACE" });
        if (missionType != nodeData.Value<string>("missionType") || faction != nodeData.Value<string>("faction"))
        {
            string? found = null, foundExtra = null;
            if (arch && GameData.Table("Tilesets")[faction == "FC_GRINEER" ? "ArchwingGrineerSpaceTileset" : "ArchwingCorpusTrenchrunTileset"]?["missions"]?[missionType]?["enemySpecs"] is JArray { Count: > 0 } specs) found = rng.Element(specs.ToArray()).ToString();
            if (found is null)
            {
                var alternatives = regions.Properties().Select(x => (JObject)x.Value).Where(x => x.Value<string>("faction") == faction && x.Value<string>("enemySpec") is not null).ToArray();
                var chosen = alternatives.FirstOrDefault(x => x.Value<string>("missionType") == missionType) ?? alternatives.First(); found = chosen.Value<string>("enemySpec"); foundExtra = chosen.Value<string>("extraEnemySpec");
            }
            enemy = found; extra = foundExtra;
        }
        var difficulty = rng.Int(10, 99) / 100d; var minLevel = 10 + (int)Math.Floor(difficulty * 20 + .5); var maxLevel = minLevel + rng.Int(5, 10);
        var credits = 2000 + (int)Math.Floor(difficulty * 18000 + .5); var standard = Data.Value["alertStandardResources"]!.OfType<JObject>().Select(x => (x.Value<string>("path")!, x.Value<int>("qty"))).ToList();
        var special = new List<(string, int)>(); var blueprints = Pool("alertOrokinBP").ToList();
        if (Since("14.0.0")) { standard.Add(("/Lotus/Types/Items/MiscItems/ArgonCrystal", 1)); special.Add(("/Lotus/Types/Game/KubrowPet/Eggs/KubrowEgg", 1)); }
        if (Since("10.8.0")) standard.Add(("/Lotus/Types/Items/MiscItems/OxiumAlloy", 300));
        if (Since("15.5.0")) standard.Add(("/Lotus/Types/Items/MiscItems/Tellurium", 1));
        if (Since("18.5.0")) special.Add(("/Lotus/Types/Game/CatbrowPet/CatbrowGeneticSignature", 5));
        if (Since("14.0.0")) special.Add(("/Lotus/Types/Items/MiscItems/Eventium", 5));
        if (Since("17.12.0")) special.Add(("/Lotus/Types/Items/MiscItems/Alertium", 1));
        if (Since("18.13.3")) special.Add(("/Lotus/Types/Items/MiscItems/VoidTearDrop", 20));
        if (Since("13.0.0")) blueprints.Add("/Lotus/Types/Recipes/Components/FormaBlueprint");
        var categories = new List<(string Name, int Weight)> { ("CREDITS", 60), ("STANDARD_RESOURCES", 120), ("ENDO", 40), ("ALT_HELMETS", 80), ("WEAPONS", 35), ("AURAS", 18), ("OROKIN_BP", 4) };
        if (Since("7.11.0")) categories.Add(("VAUBAN_PARTS", 7)); if (Since("9.1.0")) categories.Add(("NIGHTMARE_MODS", 30)); if (Since("14.0.0")) categories.Add(("SPECIAL_RESOURCES", 10));
        var roll = rng.Int(0, categories.Sum(x => x.Weight) * 100) / 100d; var category = "STANDARD_RESOURCES";
        foreach (var choice in categories) { if (roll < choice.Weight) { category = choice.Name; break; } roll -= choice.Weight; }
        string? rewardItem = null; (string Path, int Count)? resource = null; var nightmare = false;
        switch (category)
        {
            case "CREDITS": credits = 5000 + (int)Math.Floor(difficulty * 15000 + .5); break;
            case "STANDARD_RESOURCES": resource = rng.Element(standard); break;
            case "SPECIAL_RESOURCES": resource = rng.Element(special); break;
            case "ENDO":
                var endo = rng.Int(0, 99); rewardItem = Since("19.0.1") ? "/Lotus/Upgrades/Mods/FusionBundles/AlertFusionBundle" + (endo < 60 ? "Small" : endo < 90 ? "Medium" : "Large") : "/Lotus/Upgrades/Mods/FusionCores/CoreClass" + (endo < 60 ? "CommonThree" : endo < 90 ? "UncommonFive" : "RareFive"); break;
            case "AURAS": rewardItem = rng.Element(Pool("alertAuras")); if (!Since("9.0.0")) rewardItem = rewardItem.Replace("/Lotus/Upgrades/Mods/Aura/", "/Lotus/Types/Cards/", StringComparison.Ordinal).Replace("AuraMod", "Buff", StringComparison.Ordinal); break;
            case "ALT_HELMETS":
                var helmets = Pool("alertHelmets").Where(x => HelmetVersions.FirstOrDefault(v => x.Contains(v.Match, StringComparison.Ordinal)).Version is not string minimum || Since(minimum)).ToArray(); rewardItem = Helmet(rng.Element(helmets), build); break;
            case "WEAPONS": rewardItem = rng.Element(Pool("alertWeapons").Where(x => x.Contains("DaggerAxe", StringComparison.Ordinal) || x.Contains("Grn", StringComparison.Ordinal) ? Since("7.7.1") : !x.Contains("Glaive", StringComparison.Ordinal) || Since("7.9.0")).ToArray()); break;
            case "VAUBAN_PARTS": rewardItem = rng.Element(Pool("alertVaubanParts")); break;
            case "NIGHTMARE_MODS": rewardItem = rng.Element(Pool("alertNightmareMods")); nightmare = true; break;
            case "OROKIN_BP": rewardItem = rng.Element(blueprints); break;
        }
        var multiplier = Data.Value["durationMultipliers"]?.Value<double>(GameData.ItemType(rewardItem ?? resource?.Path ?? "")) ?? 1;
        if (multiplier == 0) multiplier = 1;
        var duration = (long)Math.Floor((40 + rng.Int(0, 40)) * 60000 * multiplier + .5); var start = Epoch + index * Interval;
        var result = Window(start, start + duration, Id(start, "a1e4" + seed.ToString("x5")[..5] + (index & 0xffffff).ToString("x7")), build);
        var info = new JObject { ["location"] = node, ["missionType"] = missionType, ["faction"] = faction, ["difficulty"] = difficulty, ["minEnemyLevel"] = minLevel, ["maxEnemyLevel"] = maxLevel };
        var rewards = new JObject { ["credits"] = credits }; info["missionReward"] = rewards;
        if (rewardItem is not null) rewards["items"] = new JArray(LegacyReward(GameData.StoreType(rewardItem), build));
        if (resource is { } res) rewards["countedItems"] = new JArray(new JObject { ["ItemType"] = res.Path, ["ItemCount"] = res.Count });
        foreach (var (key, value) in new[] { ("levelOverride", level), ("enemySpec", enemy), ("extraEnemySpec", extra) }) if (value is not null) info[key] = value;
        if (old && Data.Value["alertDescTexts"]?[missionType] is JArray { Count: > 0 } descriptions) info["descText"] = rng.Element(descriptions.ToArray()).DeepClone();
        if (nightmare) info["nightmare"] = true; if (arch) info["archwingRequired"] = true; result["MissionInfo"] = info; return result;
    }
    public static void Append(JObject world, JObject settings, long now, long build)
    {
        if (!(settings.Value<bool?>("classicAlerts") ?? build >= GameVersion.Of("5.1.0") && build < GameVersion.Of("24.3.0"))) return;
        var current = (int)((now - Epoch) / Interval);
        for (var index = Math.Max(0, current - 8); index <= current + 1; index++)
        { var alert = Generate(index, build); if (Wire.DateMs(alert["Activation"]) <= now && Wire.DateMs(alert["Expiry"]) > now) world.Array("Alerts").Add(alert); }
    }
    public static JObject? Find(string id, string? label, long now)
    {
        if (id.Length != 24 || id.Substring(8, 4) != "a1e4" || !int.TryParse(id.AsSpan(17), System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out var index)) return null;
        var alert = Generate(index, GameVersion.Parse(label));
        return Wire.Id(alert["_id"]) == id && Wire.DateMs(alert["Activation"]) <= now && Wire.DateMs(alert["Expiry"]) > now - Day ? alert : null;
    }
}