using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
/// <summary>C# port of warframe-riven-info 0.1.2. Reference coefficients are pinned, not fetched at runtime.</summary>
public static partial class RivenCalculator
{
public const long Scale = 0x3fffffff;
public const string Prefix = "/Lotus/Upgrades/Mods/Randomized/";
private static readonly double[] BuffAttenuation = [0, 1, .66000003, .5, .40000001, .34999999];
private static readonly double[] CurseAttenuation = [0, 1, .33000001, .5, 1.25, 1.5];
private static readonly Lazy<JObject> Tags = new(() => (JObject)Assets.Json("editor/riven-tags.json"));
public static IEnumerable<string> Families => Tags.Value.Properties().Select(x => x.Name);
public static string Family(string type) => type.StartsWith(Prefix, StringComparison.Ordinal) ? type[Prefix.Length..] : type;
public static JArray Entries(string type) => Tags.Value[Family(type)] as JArray ?? throw new ApiException(400, "未知紫卡类型。");
public static double Roll(long value) => value >= 0 && value <= Scale ? value / (double)Scale : 0;
private static double Round(double value) => Math.Floor(value + .5); // JavaScript Math.round, including negative ties.
public static long ToInteger(double value)
{
if (!double.IsFinite(value) || value < 0 || value > 1) throw new ApiException(400, "词条品质必须为 9000–11000。");
return checked((long)Round(value * Scale));
}
public static string Grade(double value)
{
var percentage = -10 + 20 * value;
return percentage is < -11.5 or > 11.5 || !double.IsFinite(percentage) ? "X" : percentage switch
{ >= 9.5 => "S", >= 7.5 => "A+", >= 5.5 => "A", >= 3.5 => "A-", >= 1.5 => "B+", >= -1.5 => "B", >= -3.5 => "B-", >= -5.5 => "C+", >= -7.5 => "C", >= -9.5 => "C-", _ => "F" };
}
private static bool Faction(string tag) => tag.Contains("FactionDamage", StringComparison.Ordinal);
private static bool Flat(string tag) => tag is "WeaponMeleeComboInitialBonusMod" or "ComboDurationMod" or "WeaponMeleeRangeIncMod";
public static double Display(string tag, double value) => Faction(tag) ? Round(value * 100) / 100 : Flat(tag) ? Round(value * 10) / 10 : Round(value * 1000) / 10;
public static double FromDisplay(string tag, double value) => Faction(tag) || Flat(tag) ? value : value / 100;
private static JObject Entry(string type, string tag) => Entries(type).OfType<JObject>().FirstOrDefault(x => x.Value<string>("tag") == tag) ?? throw new ApiException(400, "该类紫卡不支持词条 " + tag);
private static double Factor(string type, string tag, double disposition, int level, int buffs, int curses, bool negative)
{
if (!double.IsFinite(disposition) || disposition <= 0 || disposition > 10 || level is < 0 or > 8 || buffs is < 1 or > 128 || curses is < 0 or > 128 || negative && curses == 0)
throw new ApiException(400, "紫卡倾向性、等级或词条数量无效。");
var value = Entry(type, tag).Value<double>("value") * 1.5 * disposition * 10;
return negative ? -value * CurseAttenuation[Math.Min(buffs, 5)] * BuffAttenuation[Math.Min(curses, 5)] * (level + 1)
: value * Math.Pow(1.25, curses) * BuffAttenuation[Math.Min(buffs, 5)] * (level + 1);
}
public static double Inverse(string type, string tag, double disposition, int level, int buffs, int curses, bool negative, double actual)
{
if (!double.IsFinite(actual)) throw new ApiException(400, "词条数值必须为有限数值。");
return (actual / Factor(type, tag, disposition, level, buffs, curses, negative) - .9) / .2;
}
public static JObject Parse(string type, JObject fingerprint, double disposition)
{
Entries(type);
if (fingerprint["challenge"] is not null) return ParseVeiled(type, fingerprint);
var buffs = fingerprint["buffs"] as JArray ?? throw new ApiException(400, "缺少正面词条。");
var curses = fingerprint["curses"] as JArray ?? [];
var level = (int)fingerprint.Integer("lvl", 0, 8);
var stats = new JArray(); var maximum = new Dictionary<string, long>();
foreach (var (rows, negative) in new[] { (buffs, false), (curses, true) })
{
if (rows.Any(x => x is not JObject)) throw new ApiException(400, "词条必须为对象。");
foreach (var row in rows.OfType<JObject>())
{
var tag = row.RequiredString("Tag"); var encoded = row.Integer("Value", 0, uint.MaxValue);
var roll = Roll(encoded); var actual = Factor(type, tag, disposition, level, buffs.Count, curses.Count, negative) * (.9 + .2 * roll);
if (!double.IsFinite(actual)) throw new ApiException(400, "词条数值溢出。");
stats.Add(new JObject { ["tag"] = tag, ["negative"] = negative, ["value"] = actual, ["displayValue"] = Display(tag, actual), ["roll"] = 9000 + 2000 * roll, ["grade"] = Grade(roll) });
if (!negative) maximum[tag] = Math.Max(maximum.GetValueOrDefault(tag), encoded);
}
}
if (buffs.Count == 0) throw new ApiException(400, "至少需要一个正面词条。");
var sorted = buffs.OfType<JObject>().OrderByDescending(x => maximum[x.RequiredString("Tag")]).ThenBy(x => Entry(type, x.RequiredString("Tag")).Value<double>("value")).ToArray();
var first = sorted[0].RequiredString("Tag"); var last = sorted[^1].RequiredString("Tag"); var name = "";
foreach (var row in sorted)
{
var tag = row.RequiredString("Tag"); var entry = Entry(type, tag);
if (tag == last) name += entry.Value<string>("suffix") ?? "";
else if (tag == first) { var prefix = entry.Value<string>("prefix") ?? ""; name += prefix.Length == 0 ? "" : char.ToUpperInvariant(prefix[0]) + prefix[1..]; }
else name += "-" + (entry.Value<string>("prefix") ?? "");
}
return new JObject { ["name"] = name, ["stats"] = stats, ["fingerprint"] = fingerprint.DeepClone() };
}
public static JObject Decode(JToken? token)
{
for (var i = 0; i < 2 && token?.Type == JTokenType.String; i++)
{
var value = token.Value<string>()!; if (value.Length > 100000) throw new ApiException(400, "指纹过大。");
try { token = JToken.Parse(value); } catch (Newtonsoft.Json.JsonException) { throw new ApiException(400, "指纹不是有效 JSON。"); }
}
return token as JObject ?? throw new ApiException(400, "指纹必须为 JSON 对象或包含该对象的字符串。");
}
public static JObject Calculate(JObject request)
{
var type = request.RequiredString("type"); var disposition = request.Value<double?>("disposition") ?? 1;
if (request["fingerprint"] is JToken input) return Parse(type, Decode(input), disposition);
if (request.Value<string>("mode") == "veiled") return BuildVeiled(type, request);
var rows = request["rows"] as JArray ?? throw new ApiException(400, "缺少词条。");
if (rows.Count > 256 || rows.Any(x => x is not JObject)) throw new ApiException(400, "词条数量或格式无效。");
var buffs = rows.Count(x => !x.Value<bool>("negative")); var curses = rows.Count - buffs;
var level = (int)request.Integer("level", 0, 8);
var fingerprint = request["baseFingerprint"] is { Type: not JTokenType.Null } original ? (JObject)Decode(original).DeepClone() : new JObject { ["lim"] = 0 };
fingerprint.Remove("challenge");
fingerprint["compat"] = request.RequiredString("weapon"); fingerprint["pol"] = request.RequiredString("polarity"); fingerprint["lvl"] = level;
fingerprint["lvlReq"] = request.Integer("mastery", 0, 1000); fingerprint["rerolls"] = request.Integer("rerolls", 0, int.MaxValue);
fingerprint["buffs"] = new JArray(); fingerprint["curses"] = new JArray();
foreach (var row in rows.OfType<JObject>())
{
var tag = row.RequiredString("tag"); var negative = row.Value<bool>("negative");
var encoded = row["encodedValue"]?.Type is JTokenType.Integer ? row.Integer("encodedValue", 0, uint.MaxValue) : (long?)null;
var roll = encoded is long retained ? Roll(retained) : row.Value<string>("mode") == "stat" ? Inverse(type, tag, disposition, level, buffs, curses, negative, FromDisplay(tag, row.Value<double>("value"))) : (row.Value<double>("value") - 9000) / 2000;
if (roll is < -0.00000001 or > 1.00000001 || !double.IsFinite(roll)) throw new ApiException(400, "词条数值超出当前倾向性与组合的可用范围。");
var stat = row["originalRow"] is JObject oldRow ? (JObject)oldRow.DeepClone() : new JObject();
stat["Tag"] = tag; stat["Value"] = encoded ?? ToInteger(Math.Clamp(roll, 0, 1));
fingerprint.Array(negative ? "curses" : "buffs").Add(stat);
}
return Parse(type, fingerprint, disposition);
}
public static JObject Catalog(ItemCatalog catalog, string? family)
{
family ??= Families.First(); Entries(family);
var meta = RivenApi.Metadata(Prefix + family);
var dictionary = (JObject)Assets.Json("export/dict.zh.json"); dictionary.Merge(Assets.Json("fixed_responses/supplementalDict/zh.json"));
return new JObject
{
["challenges"] = ChallengeCatalog(meta, dictionary),
["families"] = new JArray(Families.Select(x => new JObject { ["key"] = x, ["label"] = catalog.Name(RivenApi.Metadata(Prefix + x), x) })),
["tags"] = new JArray(Entries(family).OfType<JObject>().Select(x =>
{
return StatPresentation(catalog, family, x.RequiredString("tag"));
})),
["weapons"] = new JArray((meta["compatibleItems"] as JArray ?? []).Select(x =>
{
var weapon = GameData.Find("Weapons", x.ToString()) ?? new JObject();
return new JObject { ["key"] = x.ToString(), ["label"] = catalog.Name(weapon, x.ToString()), ["disposition"] = weapon.Value<double?>("omegaAttenuation") ?? 1 };
}).OrderBy(x => x.Value<string>("label")))
};
}
public static void ValidateForSave(string type, JObject fingerprint)
{
var meta = RivenApi.Metadata(Prefix + Family(type)); Entries(type);
if (fingerprint["challenge"] is not null) { ParseVeiled(type, fingerprint); return; }
var weapon = fingerprint.RequiredString("compat");
if (!(meta["compatibleItems"] as JArray ?? []).Any(x => x.ToString() == weapon)) throw new ApiException(400, "该武器与紫卡类型不兼容。");
if (!new[] { "AP_UNIVERSAL", "AP_ANY", "AP_ATTACK", "AP_DEFENSE", "AP_TACTIC", "AP_POWER", "AP_WARD", "AP_PRECEPT", "AP_UMBRA" }.Contains(fingerprint.RequiredString("pol"))) throw new ApiException(400, "未知极性。");
fingerprint.Integer("lvlReq", 0, 1000); if (fingerprint["rerolls"] is not null) fingerprint.Integer("rerolls", 0, int.MaxValue);
Parse(type, fingerprint, GameData.Find("Weapons", weapon)?.Value<double?>("omegaAttenuation") ?? 1);
}
}
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;
namespace XFEWarframe.Core.Services;
/// <summary>C# port of warframe-riven-info 0.1.2. Reference coefficients are pinned, not fetched at runtime.</summary>
public static partial class RivenCalculator
{
public const long Scale = 0x3fffffff;
public const string Prefix = "/Lotus/Upgrades/Mods/Randomized/";
private static readonly double[] BuffAttenuation = [0, 1, .66000003, .5, .40000001, .34999999];
private static readonly double[] CurseAttenuation = [0, 1, .33000001, .5, 1.25, 1.5];
private static readonly Lazy<JObject> Tags = new(() => (JObject)Assets.Json("editor/riven-tags.json"));
public static IEnumerable<string> Families => Tags.Value.Properties().Select(x => x.Name);
public static string Family(string type) => type.StartsWith(Prefix, StringComparison.Ordinal) ? type[Prefix.Length..] : type;
public static JArray Entries(string type) => Tags.Value[Family(type)] as JArray ?? throw new ApiException(400, "未知紫卡类型。");
public static double Roll(long value) => value >= 0 && value <= Scale ? value / (double)Scale : 0;
private static double Round(double value) => Math.Floor(value + .5); // JavaScript Math.round, including negative ties.
public static long ToInteger(double value)
{
if (!double.IsFinite(value) || value < 0 || value > 1) throw new ApiException(400, "词条品质必须为 9000–11000。");
return checked((long)Round(value * Scale));
}
public static string Grade(double value)
{
var percentage = -10 + 20 * value;
return percentage is < -11.5 or > 11.5 || !double.IsFinite(percentage) ? "X" : percentage switch
{ >= 9.5 => "S", >= 7.5 => "A+", >= 5.5 => "A", >= 3.5 => "A-", >= 1.5 => "B+", >= -1.5 => "B", >= -3.5 => "B-", >= -5.5 => "C+", >= -7.5 => "C", >= -9.5 => "C-", _ => "F" };
}
private static bool Faction(string tag) => tag.Contains("FactionDamage", StringComparison.Ordinal);
private static bool Flat(string tag) => tag is "WeaponMeleeComboInitialBonusMod" or "ComboDurationMod" or "WeaponMeleeRangeIncMod";
public static double Display(string tag, double value) => Faction(tag) ? Round(value * 100) / 100 : Flat(tag) ? Round(value * 10) / 10 : Round(value * 1000) / 10;
public static double FromDisplay(string tag, double value) => Faction(tag) || Flat(tag) ? value : value / 100;
private static JObject Entry(string type, string tag) => Entries(type).OfType<JObject>().FirstOrDefault(x => x.Value<string>("tag") == tag) ?? throw new ApiException(400, "该类紫卡不支持词条 " + tag);
private static double Factor(string type, string tag, double disposition, int level, int buffs, int curses, bool negative)
{
if (!double.IsFinite(disposition) || disposition <= 0 || disposition > 10 || level is < 0 or > 8 || buffs is < 1 or > 128 || curses is < 0 or > 128 || negative && curses == 0)
throw new ApiException(400, "紫卡倾向性、等级或词条数量无效。");
var value = Entry(type, tag).Value<double>("value") * 1.5 * disposition * 10;
return negative ? -value * CurseAttenuation[Math.Min(buffs, 5)] * BuffAttenuation[Math.Min(curses, 5)] * (level + 1)
: value * Math.Pow(1.25, curses) * BuffAttenuation[Math.Min(buffs, 5)] * (level + 1);
}
public static double Inverse(string type, string tag, double disposition, int level, int buffs, int curses, bool negative, double actual)
{
if (!double.IsFinite(actual)) throw new ApiException(400, "词条数值必须为有限数值。");
return (actual / Factor(type, tag, disposition, level, buffs, curses, negative) - .9) / .2;
}
public static JObject Parse(string type, JObject fingerprint, double disposition)
{
Entries(type);
if (fingerprint["challenge"] is not null) return ParseVeiled(type, fingerprint);
var buffs = fingerprint["buffs"] as JArray ?? throw new ApiException(400, "缺少正面词条。");
var curses = fingerprint["curses"] as JArray ?? [];
var level = (int)fingerprint.Integer("lvl", 0, 8);
var stats = new JArray(); var maximum = new Dictionary<string, long>();
foreach (var (rows, negative) in new[] { (buffs, false), (curses, true) })
{
if (rows.Any(x => x is not JObject)) throw new ApiException(400, "词条必须为对象。");
foreach (var row in rows.OfType<JObject>())
{
var tag = row.RequiredString("Tag"); var encoded = row.Integer("Value", 0, uint.MaxValue);
var roll = Roll(encoded); var actual = Factor(type, tag, disposition, level, buffs.Count, curses.Count, negative) * (.9 + .2 * roll);
if (!double.IsFinite(actual)) throw new ApiException(400, "词条数值溢出。");
stats.Add(new JObject { ["tag"] = tag, ["negative"] = negative, ["value"] = actual, ["displayValue"] = Display(tag, actual), ["roll"] = 9000 + 2000 * roll, ["grade"] = Grade(roll) });
if (!negative) maximum[tag] = Math.Max(maximum.GetValueOrDefault(tag), encoded);
}
}
if (buffs.Count == 0) throw new ApiException(400, "至少需要一个正面词条。");
var sorted = buffs.OfType<JObject>().OrderByDescending(x => maximum[x.RequiredString("Tag")]).ThenBy(x => Entry(type, x.RequiredString("Tag")).Value<double>("value")).ToArray();
var first = sorted[0].RequiredString("Tag"); var last = sorted[^1].RequiredString("Tag"); var name = "";
foreach (var row in sorted)
{
var tag = row.RequiredString("Tag"); var entry = Entry(type, tag);
if (tag == last) name += entry.Value<string>("suffix") ?? "";
else if (tag == first) { var prefix = entry.Value<string>("prefix") ?? ""; name += prefix.Length == 0 ? "" : char.ToUpperInvariant(prefix[0]) + prefix[1..]; }
else name += "-" + (entry.Value<string>("prefix") ?? "");
}
return new JObject { ["name"] = name, ["stats"] = stats, ["fingerprint"] = fingerprint.DeepClone() };
}
public static JObject Decode(JToken? token)
{
for (var i = 0; i < 2 && token?.Type == JTokenType.String; i++)
{
var value = token.Value<string>()!; if (value.Length > 100000) throw new ApiException(400, "指纹过大。");
try { token = JToken.Parse(value); } catch (Newtonsoft.Json.JsonException) { throw new ApiException(400, "指纹不是有效 JSON。"); }
}
return token as JObject ?? throw new ApiException(400, "指纹必须为 JSON 对象或包含该对象的字符串。");
}
public static JObject Calculate(JObject request)
{
var type = request.RequiredString("type"); var disposition = request.Value<double?>("disposition") ?? 1;
if (request["fingerprint"] is JToken input) return Parse(type, Decode(input), disposition);
if (request.Value<string>("mode") == "veiled") return BuildVeiled(type, request);
var rows = request["rows"] as JArray ?? throw new ApiException(400, "缺少词条。");
if (rows.Count > 256 || rows.Any(x => x is not JObject)) throw new ApiException(400, "词条数量或格式无效。");
var buffs = rows.Count(x => !x.Value<bool>("negative")); var curses = rows.Count - buffs;
var level = (int)request.Integer("level", 0, 8);
var fingerprint = request["baseFingerprint"] is { Type: not JTokenType.Null } original ? (JObject)Decode(original).DeepClone() : new JObject { ["lim"] = 0 };
fingerprint.Remove("challenge");
fingerprint["compat"] = request.RequiredString("weapon"); fingerprint["pol"] = request.RequiredString("polarity"); fingerprint["lvl"] = level;
fingerprint["lvlReq"] = request.Integer("mastery", 0, 1000); fingerprint["rerolls"] = request.Integer("rerolls", 0, int.MaxValue);
fingerprint["buffs"] = new JArray(); fingerprint["curses"] = new JArray();
foreach (var row in rows.OfType<JObject>())
{
var tag = row.RequiredString("tag"); var negative = row.Value<bool>("negative");
var encoded = row["encodedValue"]?.Type is JTokenType.Integer ? row.Integer("encodedValue", 0, uint.MaxValue) : (long?)null;
var roll = encoded is long retained ? Roll(retained) : row.Value<string>("mode") == "stat" ? Inverse(type, tag, disposition, level, buffs, curses, negative, FromDisplay(tag, row.Value<double>("value"))) : (row.Value<double>("value") - 9000) / 2000;
if (roll is < -0.00000001 or > 1.00000001 || !double.IsFinite(roll)) throw new ApiException(400, "词条数值超出当前倾向性与组合的可用范围。");
var stat = row["originalRow"] is JObject oldRow ? (JObject)oldRow.DeepClone() : new JObject();
stat["Tag"] = tag; stat["Value"] = encoded ?? ToInteger(Math.Clamp(roll, 0, 1));
fingerprint.Array(negative ? "curses" : "buffs").Add(stat);
}
return Parse(type, fingerprint, disposition);
}
public static JObject Catalog(ItemCatalog catalog, string? family)
{
family ??= Families.First(); Entries(family);
var meta = RivenApi.Metadata(Prefix + family);
var dictionary = (JObject)Assets.Json("export/dict.zh.json"); dictionary.Merge(Assets.Json("fixed_responses/supplementalDict/zh.json"));
return new JObject
{
["challenges"] = ChallengeCatalog(meta, dictionary),
["families"] = new JArray(Families.Select(x => new JObject { ["key"] = x, ["label"] = catalog.Name(RivenApi.Metadata(Prefix + x), x) })),
["tags"] = new JArray(Entries(family).OfType<JObject>().Select(x =>
{
return StatPresentation(catalog, family, x.RequiredString("tag"));
})),
["weapons"] = new JArray((meta["compatibleItems"] as JArray ?? []).Select(x =>
{
var weapon = GameData.Find("Weapons", x.ToString()) ?? new JObject();
return new JObject { ["key"] = x.ToString(), ["label"] = catalog.Name(weapon, x.ToString()), ["disposition"] = weapon.Value<double?>("omegaAttenuation") ?? 1 };
}).OrderBy(x => x.Value<string>("label")))
};
}
public static void ValidateForSave(string type, JObject fingerprint)
{
var meta = RivenApi.Metadata(Prefix + Family(type)); Entries(type);
if (fingerprint["challenge"] is not null) { ParseVeiled(type, fingerprint); return; }
var weapon = fingerprint.RequiredString("compat");
if (!(meta["compatibleItems"] as JArray ?? []).Any(x => x.ToString() == weapon)) throw new ApiException(400, "该武器与紫卡类型不兼容。");
if (!new[] { "AP_UNIVERSAL", "AP_ANY", "AP_ATTACK", "AP_DEFENSE", "AP_TACTIC", "AP_POWER", "AP_WARD", "AP_PRECEPT", "AP_UMBRA" }.Contains(fingerprint.RequiredString("pol"))) throw new ApiException(400, "未知极性。");
fingerprint.Integer("lvlReq", 0, 1000); if (fingerprint["rerolls"] is not null) fingerprint.Integer("rerolls", 0, int.MaxValue);
Parse(type, fingerprint, GameData.Find("Weapons", weapon)?.Value<double?>("omegaAttenuation") ?? 1);
}
}