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

XFEWarframe

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

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

namespace XFEWarframe.Core.Services;

public static class WorldClock
{
    private sealed record Constraint(Func<long, bool> Valid, Func<long, long> Before);
    private const double EidolonEpoch = 1391990400, Cycle = 24 / 0.0026670000515878, Hour = Cycle / 24;
    private const long VallisEpoch = 1541837628;

    public static long ReportedTime(long now, JObject settings)
    {
        var constraints = new List<Constraint>();
        if (settings.Value<string>("eidolonOverride") is string eidolon && eidolon is "day" or "night")
        {
            var daytime = eidolon == "day";
            double Start(long time) => EidolonEpoch + Math.Truncate((time - EidolonEpoch) / Cycle) * Cycle;
            bool Valid(long time)
            {
                var start = Start(time); var hour = 24 * ((time - EidolonEpoch) % Cycle / Cycle);
                return daytime ? hour > 5 && time + 300 <= start + 21.9 * Hour : hour > 5 ? time >= start + 21.9 * Hour : time + 300 <= start + 5 * Hour;
            }
            long Before(long time)
            {
                var start = Start(time); var target = start + (daytime ? 5 : 21.9) * Hour;
                if (target >= time) target -= Cycle;
                return (long)target;
            }
            constraints.Add(new(Valid, Before));
        }
        if (settings.Value<string>("vallisOverride") is string vallis && vallis is "cold" or "warm")
        {
            var cold = vallis == "cold"; long Start(long time) => VallisEpoch + (time - VallisEpoch) / 1600 * 1600;
            constraints.Add(new(time => cold ? time >= Start(time) + 400 && time + 300 <= Start(time) + 1600 : time + 300 <= Start(time) + 400,
                time => { var target = Start(time) + (cold ? 400 : 0); return target > time ? target - 1600 : target; }));
        }
        var mood = Array.IndexOf(new[] { "sorrow", "fear", "joy", "anger", "envy" }, settings.Value<string>("duviriOverride"));
        if (mood >= 0) constraints.Add(new(time => time / 7200 % 5 == mood, time => (time / 7200 - (time / 7200 % 5 - mood + 5) % 5) * 7200));
        var seconds = now / 1000;
        // Match upstream's backwards search and one-minute compromise, with a finite guard.
        for (var iteration = 0; iteration < 10000; iteration++)
        {
            var failed = constraints.FirstOrDefault(x => !x.Valid(seconds));
            if (failed is null) return seconds * 1000;
            var previous = seconds; var suggestion = failed.Before(seconds); seconds = suggestion;
            do
            {
                seconds += 60;
                if (seconds >= previous || !failed.Valid(seconds)) { seconds = suggestion; break; }
            } while (!constraints.All(x => x.Valid(seconds)));
        }
        throw new ApiException(400, "世界循环约束无法同时满足,请调整循环选项。");
    }
}