using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using BepInEx;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using Globals;
using HarmonyLib;
using MTFO.API;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DynamicThreatLevel")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DynamicThreatLevel")]
[assembly: AssemblyTitle("DynamicThreatLevel")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
internal sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte P_0)
{
NullableFlags = new byte[1] { P_0 };
}
public NullableAttribute(byte[] P_0)
{
NullableFlags = P_0;
}
}
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
internal sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte P_0)
{
Flag = P_0;
}
}
}
namespace DynamicThreatLevel
{
[BepInPlugin("A3D.DynamicThreatLevel", "DynamicThreatLevel", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class DynamicThreatCore : BasePlugin
{
internal static DynamicThreatCore Instance = null;
internal static ThreatConfig ThreatConfig = new ThreatConfig();
internal static Dictionary<string, ThreatSave> Saves = new Dictionary<string, ThreatSave>();
internal static string ConfigPath = "";
internal static string SavePath = "";
internal static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
WriteIndented = true,
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
private static DateTime _configWrite;
private static double _nextCheck;
internal static bool Loaded;
internal static int CurrentRundown => (int)Global.RundownIdToLoad;
public override void Load()
{
//IL_000d: Unknown result type (might be due to invalid IL or missing references)
Instance = this;
try
{
new Harmony("A3D.DynamicThreatLevel").PatchAll();
((BasePlugin)this).Log.LogInfo((object)"DynamicThreatLevel loaded");
}
catch (Exception ex)
{
((BasePlugin)this).Log.LogError((object)ex);
}
}
internal static void EnsureLoaded()
{
if (!MTFOPathAPI.HasCustomPath)
{
return;
}
string text = Path.Combine(MTFOPathAPI.CustomPath, "DynamicThreatLevel");
string text2 = Path.Combine(text, "DynamicThreatLevel.jsonc");
if (!Loaded || !(text2 == ConfigPath))
{
Directory.CreateDirectory(text);
ConfigPath = text2;
SavePath = Path.Combine(Paths.ConfigPath, "DynamicThreatLevel", SafeName(MTFOPathAPI.CustomPath) + ".json");
Directory.CreateDirectory(Path.GetDirectoryName(SavePath));
if (!File.Exists(text2))
{
string contents = "{\n \"GlobalSettings\": {\n \"QuickThreatText\": \"EST THREAT LEVEL <color=orange>[DisplayedThreat]%</color>\",\n \"LongThreatText\": \"ESTIMATED THREAT LEVEL <color=orange>[DisplayedThreat]%</color>, CURRENT EXPECTED SURVIVAL CHANCE <color=orange>[SurvivalText]</color>%\",\n \"SurvivalTexts\": [\n {\n \"DisplayedThreatMin\": 0.00,\n \"DisplayedThreatMax\": 30.00,\n \"SurvivalText\": \"GOOD\"\n },\n {\n \"DisplayedThreatMin\": 30.01,\n \"DisplayedThreatMax\": 55.00,\n \"SurvivalText\": \"PLAUSIBLE\"\n },\n {\n \"DisplayedThreatMin\": 55.01,\n \"DisplayedThreatMax\": 70.00,\n \"SurvivalText\": \"UNLIKELY\"\n },\n {\n \"DisplayedThreatMin\": 70.01,\n \"DisplayedThreatMax\": 85.00,\n \"SurvivalText\": \"DOUBTFUL\"\n },\n {\n \"DisplayedThreatMin\": 85.01,\n \"DisplayedThreatMax\": 95.00,\n \"SurvivalText\": \"NULL\"\n },\n {\n \"DisplayedThreatMin\": 95.01,\n \"DisplayedThreatMax\": 100.00,\n \"SurvivalText\": \"://ERROR\"\n }\n ]\n },\n \"Rundowns\": [\n {\n \"RundownID\": 1,\n \"Tier1\": [\n {\n \"StartingThreat\": 37.50, \n \"MaxThreat\": 45.00, \n \"MinThreat\": 20.00, \n \"Deviation\": 2.00,\n \"ThreatChangeIncrease\": 3.50,\n \"ThreatChangeDecrease\": -3.50,\n \"ChangeDeviation\": 1.25\n }\n ],\n \"Tier2\": [],\n \"Tier3\": [],\n \"Tier4\": [],\n \"Tier5\": []\n }\n ]\n}";
File.WriteAllText(text2, contents);
}
LoadConfig();
LoadSaves();
Loaded = true;
}
}
private static string SafeName(string s)
{
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(s).ToLowerInvariant()))).Substring(0, 20);
}
internal static void Tick()
{
EnsureLoaded();
if (Loaded && !((double)Environment.TickCount64 < _nextCheck))
{
_nextCheck = Environment.TickCount64 + 1000;
if (File.Exists(ConfigPath) && File.GetLastWriteTimeUtc(ConfigPath) != _configWrite)
{
LoadConfig();
}
}
}
private static void LoadConfig()
{
try
{
ThreatConfig = JsonSerializer.Deserialize<ThreatConfig>(File.ReadAllText(ConfigPath), JsonOptions) ?? new ThreatConfig();
_configWrite = File.GetLastWriteTimeUtc(ConfigPath);
ThreatLevelMath.InvalidateDisplay();
((BasePlugin)Instance).Log.LogInfo((object)"DynamicThreatLevel settings loaded");
}
catch (Exception ex)
{
((BasePlugin)Instance).Log.LogError((object)("Invalid DynamicThreatLevel.jsonc; keeping previous settings: " + ex));
}
}
private static void LoadSaves()
{
try
{
Saves = (File.Exists(SavePath) ? (JsonSerializer.Deserialize<Dictionary<string, ThreatSave>>(File.ReadAllText(SavePath), JsonOptions) ?? new Dictionary<string, ThreatSave>()) : new Dictionary<string, ThreatSave>());
}
catch (Exception ex)
{
((BasePlugin)Instance).Log.LogError((object)("Could not read threat saves: " + ex));
Saves = new Dictionary<string, ThreatSave>();
}
}
internal static void Save()
{
try
{
string text = SavePath + ".tmp";
File.WriteAllText(text, JsonSerializer.Serialize(Saves, JsonOptions));
File.Move(text, SavePath, overwrite: true);
}
catch (Exception ex)
{
((BasePlugin)Instance).Log.LogError((object)("Could not save threat: " + ex));
}
}
internal static string Key(int rundown, int tier, int index)
{
return rundown + ":" + tier + ":" + index;
}
}
public sealed class ThreatConfig
{
public GlobalThreatSettings GlobalSettings { get; set; } = new GlobalThreatSettings();
public List<RundownThreatSettings> Rundowns { get; set; } = new List<RundownThreatSettings>();
}
public sealed class GlobalThreatSettings
{
public string QuickThreatText { get; set; } = "EST THREAT LEVEL <color=orange>[DisplayedThreat]%</color>";
public string LongThreatText { get; set; } = "ESTIMATED THREAT LEVEL <color=orange>[DisplayedThreat]%</color>, CURRENT EXPECTED SURVIVAL CHANCE <color=orange>[SurvivalText]</color>";
public List<SurvivalRange> SurvivalTexts { get; set; } = new List<SurvivalRange>();
}
public sealed class SurvivalRange
{
public double DisplayedThreatMin { get; set; }
public double DisplayedThreatMax { get; set; }
public string SurvivalText { get; set; } = "UNKNOWN";
}
public sealed class RundownThreatSettings
{
public int RundownID { get; set; }
public List<ExpeditionThreatSettings> Tier1 { get; set; } = new List<ExpeditionThreatSettings>();
public List<ExpeditionThreatSettings> Tier2 { get; set; } = new List<ExpeditionThreatSettings>();
public List<ExpeditionThreatSettings> Tier3 { get; set; } = new List<ExpeditionThreatSettings>();
public List<ExpeditionThreatSettings> Tier4 { get; set; } = new List<ExpeditionThreatSettings>();
public List<ExpeditionThreatSettings> Tier5 { get; set; } = new List<ExpeditionThreatSettings>();
public List<ExpeditionThreatSettings> GetTier(int tier)
{
return tier switch
{
1 => Tier1,
2 => Tier2,
3 => Tier3,
4 => Tier4,
5 => Tier5,
_ => new List<ExpeditionThreatSettings>(),
};
}
}
public sealed class ExpeditionThreatSettings
{
public double StartingThreat { get; set; } = 50.0;
public double MaxThreat { get; set; } = 100.0;
public double MinThreat { get; set; } = 0.0;
public double Deviation { get; set; }
public double ThreatChangeIncrease { get; set; }
public double ThreatChangeDecrease { get; set; }
public double ChangeDeviation { get; set; }
}
public sealed class ThreatSave
{
public double RealThreat { get; set; }
}
internal static class OverrideHeatText
{
[HarmonyPatch(typeof(CM_ExpeditionIcon_New), "SetArtifactHeat")]
private static class IconHeatPatch
{
[HarmonyPostfix]
private static void Postfix(CM_ExpeditionIcon_New __instance)
{
DynamicThreatCore.Tick();
Track(__instance);
Icon(__instance);
}
}
[HarmonyPatch(typeof(CM_MenuBar), "SetExpIconArtifactHeat")]
private static class MenuBarHeatPatch
{
[HarmonyPostfix]
[HarmonyPriority(0)]
private static void Postfix(CM_MenuBar __instance)
{
DynamicThreatCore.Tick();
if (!DynamicThreatCore.Loaded)
{
return;
}
try
{
Track(__instance.m_expIcon);
Icon(__instance.m_expIcon);
}
catch (Exception ex)
{
((BasePlugin)DynamicThreatCore.Instance).Log.LogDebug((object)ex);
}
}
}
[HarmonyPatch(typeof(CM_PageRundown_New), "Update")]
private static class RundownRefreshPatch
{
[HarmonyPostfix]
[HarmonyPriority(0)]
private static void Postfix()
{
DynamicThreatCore.Tick();
if (!DynamicThreatCore.Loaded)
{
return;
}
for (int num = KnownIcons.Count - 1; num >= 0; num--)
{
try
{
CM_ExpeditionIcon_New val = KnownIcons[num];
if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).gameObject == (Object)null)
{
KnownIcons.RemoveAt(num);
}
else
{
Icon(val);
}
}
catch (Exception)
{
KnownIcons.RemoveAt(num);
}
}
}
}
[HarmonyPatch(typeof(CM_ExpeditionWindow), "SetExpeditionInfo")]
private static class IntelPatch
{
[HarmonyPostfix]
private static void Postfix(CM_ExpeditionWindow __instance, eRundownTier tier, int expIndex)
{
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
//IL_0015: Expected I4, but got Unknown
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
//IL_0030: Expected I4, but got Unknown
DynamicThreatCore.Tick();
if (ThreatLevelMath.TryGet(DynamicThreatCore.CurrentRundown, (int)tier, expIndex, out ExpeditionThreatSettings _))
{
((TMP_Text)__instance.m_artifactHeatTitle).text = ThreatLevelMath.Quick(DynamicThreatCore.CurrentRundown, (int)tier, expIndex);
}
}
}
[HarmonyPatch(typeof(PlayerGuiLayer), "ShowWardenIntel")]
private static class DropIntelPatch
{
[HarmonyPrefix]
private static void Prefix(ref string intel)
{
//IL_0042: Unknown result type (might be due to invalid IL or missing references)
//IL_0054: Expected I4, but got Unknown
//IL_0069: Unknown result type (might be due to invalid IL or missing references)
//IL_0079: Expected I4, but got Unknown
DynamicThreatCore.Tick();
if (!string.IsNullOrEmpty(intel) && intel.Contains("<size=200%>") && intel.Contains("<color=white>"))
{
pActiveExpedition activeExpeditionData = RundownManager.GetActiveExpeditionData();
if (ThreatLevelMath.TryGet(DynamicThreatCore.CurrentRundown, (int)activeExpeditionData.tier, activeExpeditionData.expeditionIndex, out ExpeditionThreatSettings _))
{
intel = "<size=200%><color=white>" + ThreatLevelMath.Long(DynamicThreatCore.CurrentRundown, (int)activeExpeditionData.tier, activeExpeditionData.expeditionIndex) + "</color></size>";
}
}
}
}
[HarmonyPatch(typeof(RundownManager), "ConsumeBoostersForCurrentGameSession")]
private static class ConsumePatch
{
[HarmonyPostfix]
private static void Postfix()
{
//IL_0023: Unknown result type (might be due to invalid IL or missing references)
//IL_003d: Expected I4, but got Unknown
DynamicThreatCore.Tick();
if (!DynamicThreatCore.Loaded)
{
return;
}
try
{
pActiveExpedition activeExpeditionData = RundownManager.GetActiveExpeditionData();
ThreatLevelMath.OnDeployment(DynamicThreatCore.CurrentRundown, (int)activeExpeditionData.tier, activeExpeditionData.expeditionIndex, RundownManager.SessionGUID.ToString());
}
catch (Exception ex)
{
((BasePlugin)DynamicThreatCore.Instance).Log.LogError((object)ex);
}
}
}
private static readonly List<CM_ExpeditionIcon_New> KnownIcons = new List<CM_ExpeditionIcon_New>();
internal static void Icon(CM_ExpeditionIcon_New icon)
{
//IL_0019: Unknown result type (might be due to invalid IL or missing references)
//IL_001f: Invalid comparison between Unknown and I4
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Expected I4, but got Unknown
//IL_004e: Unknown result type (might be due to invalid IL or missing references)
//IL_0054: Invalid comparison between Unknown and I4
if ((Object)(object)icon == (Object)null || (Object)(object)icon.m_artifactHeatText == (Object)null || (int)icon.Status == 5)
{
return;
}
int tier = (int)icon.Tier;
if (ThreatLevelMath.TryGet(DynamicThreatCore.CurrentRundown, tier, icon.ExpIndex, out ExpeditionThreatSettings _) && (int)icon.Status != 0)
{
string text = ThreatLevelMath.Quick(DynamicThreatCore.CurrentRundown, tier, icon.ExpIndex);
if (((TMP_Text)icon.m_artifactHeatText).text != text)
{
((TMP_Text)icon.m_artifactHeatText).text = text;
}
}
}
private static void Track(CM_ExpeditionIcon_New icon)
{
if ((Object)(object)icon != (Object)null && !KnownIcons.Contains(icon))
{
KnownIcons.Add(icon);
}
}
}
internal static class ThreatLevelMath
{
private static readonly Random Random = new Random();
private static readonly Dictionary<string, double> Displayed = new Dictionary<string, double>();
private static string? LastDeployment;
internal static void InvalidateDisplay()
{
Displayed.Clear();
}
internal static bool TryGet(int rundown, int tier, int index, out ExpeditionThreatSettings settings)
{
settings = null;
List<ExpeditionThreatSettings> list = DynamicThreatCore.ThreatConfig.Rundowns.FirstOrDefault((RundownThreatSettings x) => x.RundownID == rundown)?.GetTier(tier);
if (list == null || index < 0 || index >= list.Count)
{
return false;
}
settings = list[index];
return true;
}
internal static double Real(int rundown, int tier, int index)
{
if (!TryGet(rundown, tier, index, out ExpeditionThreatSettings settings))
{
return 0.0;
}
string key = DynamicThreatCore.Key(rundown, tier, index);
if (!DynamicThreatCore.Saves.TryGetValue(key, out ThreatSave value))
{
Dictionary<string, ThreatSave> saves = DynamicThreatCore.Saves;
ThreatSave obj = new ThreatSave
{
RealThreat = Clamp(settings.StartingThreat, settings.MinThreat, settings.MaxThreat)
};
value = obj;
saves[key] = obj;
}
return value.RealThreat;
}
internal static double Display(int rundown, int tier, int index)
{
if (!TryGet(rundown, tier, index, out ExpeditionThreatSettings settings))
{
return 0.0;
}
string key = DynamicThreatCore.Key(rundown, tier, index);
if (!Displayed.TryGetValue(key, out var value))
{
value = (Displayed[key] = Clamp(Real(rundown, tier, index) + Roll(settings.Deviation), 0.0, 100.0));
}
return value;
}
internal static string Quick(int rundown, int tier, int index)
{
return Format(DynamicThreatCore.ThreatConfig.GlobalSettings.QuickThreatText, rundown, tier, index);
}
internal static string Long(int rundown, int tier, int index)
{
return Format(DynamicThreatCore.ThreatConfig.GlobalSettings.LongThreatText, rundown, tier, index);
}
private static string Format(string template, int rundown, int tier, int index)
{
double value = Display(rundown, tier, index);
string newValue = value.ToString("0.##", CultureInfo.InvariantCulture);
SurvivalRange survivalRange = DynamicThreatCore.ThreatConfig.GlobalSettings.SurvivalTexts.FirstOrDefault((SurvivalRange x) => value >= x.DisplayedThreatMin && value <= x.DisplayedThreatMax);
return (template ?? "").Replace("[DisplayedThreat]", newValue).Replace("[SurvivalText]", survivalRange?.SurvivalText ?? "UNKNOWN");
}
private static double Roll(double max)
{
return (Random.NextDouble() * 2.0 - 1.0) * Math.Abs(max);
}
private static double Clamp(double value, double min, double max)
{
return Math.Clamp(value, Math.Min(min, max), Math.Max(min, max));
}
internal static void OnDeployment(int rundown, int tier, int index, string session)
{
if (!DynamicThreatCore.Loaded || LastDeployment == session)
{
return;
}
RundownThreatSettings rundownThreatSettings = DynamicThreatCore.ThreatConfig.Rundowns.FirstOrDefault((RundownThreatSettings x) => x.RundownID == rundown);
if (rundownThreatSettings == null || !TryGet(rundown, tier, index, out ExpeditionThreatSettings _))
{
return;
}
LastDeployment = session;
for (int num = 1; num <= 5; num++)
{
List<ExpeditionThreatSettings> tier2 = rundownThreatSettings.GetTier(num);
for (int num2 = 0; num2 < tier2.Count; num2++)
{
ExpeditionThreatSettings expeditionThreatSettings = tier2[num2];
string key = DynamicThreatCore.Key(rundown, num, num2);
double num3 = Real(rundown, num, num2);
double num4 = ((num == tier && num2 == index) ? expeditionThreatSettings.ThreatChangeDecrease : expeditionThreatSettings.ThreatChangeIncrease) + Roll(expeditionThreatSettings.ChangeDeviation);
DynamicThreatCore.Saves[key].RealThreat = Clamp(num3 + num4, expeditionThreatSettings.MinThreat, expeditionThreatSettings.MaxThreat);
}
}
InvalidateDisplay();
DynamicThreatCore.Save();
((BasePlugin)DynamicThreatCore.Instance).Log.LogInfo((object)("Threat updated for " + session));
}
}
}