Decompiled source of GetFogged v1.0.0
GetFogged.dll
Decompiled 10 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Logging; using GSSerializer; using GSSerializer.Internal; using GSSerializer.Internal.DirectConverters; using HarmonyLib; using PCGSharp; 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(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("GetFogged")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Make the fog harder.")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+9f69af4d8a0be60322ee9e755828d94cab37f75f")] [assembly: AssemblyProduct("GetFogged")] [assembly: AssemblyTitle("GetFogged")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace GetFogged { public static class GF { private class exceptionOutput { public string exception; public string version; public exceptionOutput(string e) { version = Version; exception = e; } } private class ErrorObject { public readonly List<string> stack = new List<string>(); public string message; public string version = Version; } public enum Alignment { Left, Right, Center } public class Random : Pcg { private int count; private int seed = 1; public int Seed { get { return seed; } set { seed = value; reseed(value); } } public string Id => $"[{seed}=>{count}]"; public Random(int seed) : base(seed) { Seed = seed; } public bool NextPick(double chance) { return NextDouble() < chance; } public override uint NextUInt() { count++; return base.NextUInt(); } public float Normal(float averageValue, float standardDeviation) { return averageValue + standardDeviation * (float)(Math.Sqrt(-2.0 * Math.Log(1.0 - NextDouble())) * Math.Sin(Math.PI * 2.0 * NextDouble())); } public new float NextFloat(float min, float max) { if (Math.Abs(min - max) < float.MinValue) { return min; } if (min > max) { Warn($"{GetCaller()}-NextFloat: Min > Max. {min} {max}", 59); return max; } return base.NextFloat(min, max); } public new int Next(int minInclusive, int maxExclusive) { if (minInclusive == maxExclusive) { return minInclusive; } if (minInclusive > maxExclusive) { Error($"Next: Min > Max. {minInclusive} {maxExclusive}", 74); return maxExclusive - 1; } if (maxExclusive <= 0) { Error($"Max {maxExclusive} <= 0 {GetCaller()}", 80); return maxExclusive; } return base.Next(minInclusive, maxExclusive); } public int NextInclusive(int minInclusive, int maxInclusive) { if (minInclusive == maxInclusive) { return minInclusive; } if (minInclusive > maxInclusive) { Error($"Next: Min > Max. {minInclusive} {maxInclusive}", 93); return maxInclusive; } return base.Next(minInclusive, maxInclusive + 1); } public float ClampedNormal(float min, float max, int bias) { float num = max - min; float num2 = (float)bias / 100f * num + min; float val = (max - num2) / 3f; float val2 = (num2 - min) / 3f; float standardDeviation = Math.Max(val2, val); float num3 = Normal(num2, standardDeviation); return Mathf.Clamp(num3, min, max); } public VectorLF3 PointOnSphere(double radius) { //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) double num = NextDouble() * 2.0 * radius - radius; double num2 = NextDouble() * Math.PI * 2.0; double num3 = Math.Sqrt(Math.Pow(radius, 2.0) - Math.Pow(num, 2.0)) * Math.Cos(num2); double num4 = Math.Sqrt(Math.Pow(radius, 2.0) - Math.Pow(num, 2.0)) * Math.Sin(num2); return new VectorLF3(num3, num4, num); } public T Item<T>(List<T> items) { if (items.Count == 0) { Error("Item Length 0 " + GetCaller(), 124); } return items[Next(items.Count)]; } public (int, T) ItemWithIndex<T>(List<T> items) { if (items.Count == 0) { Error("Item Length 0 " + GetCaller(), 133); } int num = Next(items.Count); return (num, items[num]); } public T ItemAndRemove<T>(List<T> items) { if (items.Count == 0) { Error("Item Length 0 " + GetCaller(), 143); } int index = Next(items.Count); T result = items[index]; items.RemoveAt(index); return result; } public T Item<T>(T[] items) { if (items.Length == 0) { Error("Item Length 0 " + GetCaller(), 154); } return items[Next(items.Length)]; } public (int, T) ItemWithIndex<T>(T[] items) { if (items.Length == 0) { Error("Item Length 0 " + GetCaller(), 163); } int num = Next(items.Length); return (num, items[num]); } public KeyValuePair<W, X> Item<W, X>(Dictionary<W, X> items) { if (items.Count == 0) { Error("Item Length 0 " + GetCaller(), 173); } W[] array = new W[0]; items.Keys.CopyTo(array, 0); W key = array[Next(array.Length)]; return new KeyValuePair<W, X>(key, items[key]); } } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Response <>9__31_0; internal void <AbortGameStart>b__31_0() { UIRoot.instance.OpenMainMenuUI(); UIRoot.ClearFatalError(); } } public static int PreferencesVersion = 2104; public static string Version; public static string AssemblyPath; public static bool DebugOn = true; public static void DumpObjectToJson(string path, object obj) { fsSerializer fsSerializer = new fsSerializer(); fsSerializer.TrySerialize(obj, out var data).AssertSuccessWithoutWarnings(); string contents = fsJsonPrinter.PrettyJson(data); File.WriteAllText(path, contents); } public static void DumpException(Exception e) { Error(e.Message + " " + GetCaller(1) + " " + GetCaller(2) + " " + GetCaller(3) + " " + GetCaller(4) + " " + GetCaller(5), 23); string text = Path.Combine(AssemblyPath, "ErrorLog"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } text = Path.Combine(text, DateTime.Now.ToString("yyMMddHHmmss")); text += ".exceptionlog.json"; if (!File.Exists(text)) { Log(text, 31); Log("Logging Error to " + text, 32); exceptionOutput instance = new exceptionOutput(e.ToString()); fsSerializer fsSerializer = new fsSerializer(); fsSerializer.TrySerialize(instance, out var data).AssertSuccessWithoutWarnings(); string contents = fsJsonPrinter.PrettyJson(data); File.WriteAllText(text, contents); Log("End", 38); } } public static void DumpError(string message) { string text = Path.Combine(AssemblyPath, "ErrorLog"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } text = Path.Combine(text, DateTime.Now.ToString("yyMMddHHmmss")); text += ".errorlog.json"; Log(text, 47); Log("Logging Error to " + text, 48); ErrorObject errorObject = new ErrorObject(); errorObject.message = message; for (int i = 0; i < 100; i++) { string caller = GetCaller(i); if (caller != "") { errorObject.stack.Add(caller); } } fsSerializer fsSerializer = new fsSerializer(); fsSerializer.TrySerialize(errorObject, out var data).AssertSuccessWithoutWarnings(); string contents = fsJsonPrinter.PrettyJson(data); File.AppendAllText(text, contents); Log("End", 61); } private static void CleanErrorLogs() { string path = Path.Combine(AssemblyPath, "ErrorLog"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string[] files = Directory.GetFiles(path, "*.json"); string[] array = files; foreach (string fileName in array) { FileInfo fileInfo = new FileInfo(fileName); if (fileInfo.LastAccessTime < DateTime.Now.AddDays(-7.0)) { fileInfo.Delete(); } } } private static bool CheckJsonFileExists(string path) { if (File.Exists(path)) { return true; } Log("Json file does not exist at " + path, 83); return false; } public static void ConsoleSplash() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) GlobalObject.LoadVersions(); Version gameVersion = GameConfig.gameVersion; string text = ((object)(Version)(ref gameVersion)).ToString(); Debug.Log((object)"GetFogged."); } public static void Log(string s, [CallerLineNumber] int lineNumber = 0) { if (DebugOn) { Bootstrap.Debug(lineNumber.ToString().PadLeft(4) + ":" + GetCaller() + s); } } public static void LogTop(int width = 80) { if (BCE.disabled) { Log("-----", 25); return; } int num = width - 21; int num2 = Mathf.FloorToInt((float)(num / 2)) - 2; int spaces = num - num2 - 4; BCE.Console.Write("\r\n╔═", ConsoleColor.White); BCE.Console.Write("═", ConsoleColor.Gray); BCE.Console.Write("═", ConsoleColor.DarkGray); BCE.Console.Write(SpaceString(num2), ConsoleColor.Green); BCE.Console.Write("*", ConsoleColor.Yellow); BCE.Console.Write(".·", ConsoleColor.Gray); BCE.Console.Write(":", ConsoleColor.DarkGray); BCE.Console.Write("·.", ConsoleColor.Gray); BCE.Console.Write("✧", ConsoleColor.DarkCyan); BCE.Console.Write(" ✦ ", ConsoleColor.Cyan); BCE.Console.Write("✧", ConsoleColor.DarkCyan); BCE.Console.Write(".·", ConsoleColor.Gray); BCE.Console.Write(":", ConsoleColor.DarkGray); BCE.Console.Write("·.", ConsoleColor.Gray); BCE.Console.Write("*", ConsoleColor.Yellow); BCE.Console.Write(SpaceString(spaces), ConsoleColor.Green); BCE.Console.Write("═", ConsoleColor.DarkGray); BCE.Console.Write("═", ConsoleColor.Gray); BCE.Console.Write("═╗\r\n", ConsoleColor.White); } public static void LogBot(int width = 80) { if (BCE.disabled) { Log("-----", 57); return; } int num = width - 21; int num2 = Mathf.FloorToInt((float)(num / 2)) - 2; int spaces = num - num2 - 4; BCE.Console.Write("╚═", ConsoleColor.White); BCE.Console.Write("═", ConsoleColor.Gray); BCE.Console.Write("═", ConsoleColor.DarkGray); BCE.Console.Write(SpaceString(num2), ConsoleColor.Green); BCE.Console.Write("*", ConsoleColor.Yellow); BCE.Console.Write(".·", ConsoleColor.Gray); BCE.Console.Write(":", ConsoleColor.DarkGray); BCE.Console.Write("·.", ConsoleColor.Gray); BCE.Console.Write("✧", ConsoleColor.DarkCyan); BCE.Console.Write(" ✦ ", ConsoleColor.Cyan); BCE.Console.Write("✧", ConsoleColor.DarkCyan); BCE.Console.Write(".·", ConsoleColor.Gray); BCE.Console.Write(":", ConsoleColor.DarkGray); BCE.Console.Write("·.", ConsoleColor.Gray); BCE.Console.Write("*", ConsoleColor.Yellow); BCE.Console.Write(SpaceString(spaces), ConsoleColor.Green); BCE.Console.Write("═", ConsoleColor.DarkGray); BCE.Console.Write("═", ConsoleColor.Gray); BCE.Console.WriteLine("═╝", ConsoleColor.White); } public static string SpaceString(int spaces) { return new string(' ', spaces); } public static void LogMid(string text, int width = 80) { string[] array = text.Split(new char[1] { '\n' }); if (array.Length > 1) { string[] array2 = array; foreach (string text2 in array2) { LogMid(text2, width); } } if (BCE.disabled) { Log(text, 106); return; } if (text.Length < width - 4) { LogMidLine(text, width); return; } List<string> list = new List<string>(); int startIndex = 0; while (text.Length > width - 4) { LogMidLine(text.Substring(startIndex, width - 4), width); text = text.Remove(startIndex, width - 4); } } public static void LogMidLine(string text, int width = 80) { BCE.Console.Write("║ ", ConsoleColor.White); BCE.Console.Write(string.Format("{0," + (width - 4) + "}", text), ConsoleColor.Green); BCE.Console.Write(" ║\r\n", ConsoleColor.White); } public static void LogSpace(int lineCount = 1) { if (DebugOn) { for (int i = 0; i < lineCount; i++) { Bootstrap.Debug(" ", (LogLevel)8, isActive: true); } } } public static void Error(string message, [CallerLineNumber] int lineNumber = 0) { Bootstrap.Debug($"{lineNumber,4}:{GetCaller()}{message}", (LogLevel)2, isActive: true); DumpError(lineNumber + "|" + message); } public static void Warn(string message, [CallerLineNumber] int lineNumber = 0) { Bootstrap.Debug(lineNumber.ToString().PadLeft(4) + ":" + GetCaller() + message, (LogLevel)4, isActive: true); } public static void LogJson(object o, bool force = false) { if (DebugOn || force) { fsSerializer fsSerializer = new fsSerializer(); fsSerializer.TrySerialize(o, out var data).AssertSuccessWithoutWarnings(); string text = fsJsonPrinter.PrettyJson(data); Bootstrap.Debug(GetCaller() + text); } } public static void WarnJson(object o) { fsSerializer fsSerializer = new fsSerializer(); fsSerializer.TrySerialize(o, out var data).AssertSuccessWithoutWarnings(); string text = fsJsonPrinter.PrettyJson(data); Bootstrap.Debug(GetCaller() + text, (LogLevel)4, isActive: true); } public static string GetCaller(int depth = 0) { depth += 2; StackTrace stackTrace = new StackTrace(); if (stackTrace.FrameCount <= depth) { return ""; } string text = stackTrace.GetFrame(depth).GetMethod().Name; Type reflectedType = stackTrace.GetFrame(depth).GetMethod().ReflectedType; if (reflectedType != null) { string text2 = reflectedType.ToString().Split(new char[1] { '.' })[^1]; if (text == ".ctor") { text = "<Constructor>"; } return text2 + "|" + text + "|"; } return "ERROR GETTING CALLER"; } public static void LogError(object sender, UnhandledExceptionEventArgs e, [CallerLineNumber] int lineNumber = 0) { Error($"{lineNumber} {GetCaller()}", 187); LogException(e.ExceptionObject as Exception); } private static void LogException(Exception ex) { Error(ex.StackTrace, 193); } public static string FormatTableHeader(string[] headers, int[] columnWidths, params Alignment[] alignments) { if (headers.Length != columnWidths.Length || headers.Length != alignments.Length) { throw new ArgumentException("Input arrays must have the same length."); } string format = GenerateFormatString(columnWidths, alignments); string text = string.Format(format, headers); return text ?? ""; } public static string FormatTable(string[] values, int[] columnWidths, params Alignment[] alignments) { if (values.Length != columnWidths.Length || values.Length != alignments.Length) { throw new ArgumentException("Input arrays must have the same length."); } string format = GenerateFormatString(columnWidths, alignments); string text = string.Format(format, values); return text ?? ""; } private static string GenerateFormatString(int[] columnWidths, Alignment[] alignments) { if (columnWidths.Length != alignments.Length) { throw new ArgumentException("Column widths and alignments must have the same length."); } string text = ""; for (int i = 0; i < columnWidths.Length; i++) { text += $"{{{i},-{columnWidths[i]}}}"; if (i < columnWidths.Length - 1) { text += " "; } } return text; } public static IEnumerable<CodeInstruction> LogTranspilerError(IEnumerable<CodeInstruction> instructions, string text) { Error(text, 253); Log(GetCaller(), 254); LogTop(); foreach (CodeInstruction instruction in instructions) { LogMid(((object)instruction).ToString()); } LogBot(); return instructions; } public static bool AbortGameStart(string message) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown Error("Aborting Game Start|" + message, 7); UIRoot.instance.CloseLoadingUI(); UIRoot.instance.CloseGameUI(); UIRoot.instance.launchSplash.Restart(); DSPGame.StartDemoGame(0); string text = "Cannot Start Game. Possibly reason: " + message; object obj = <>c.<>9__31_0; if (obj == null) { Response val = delegate { UIRoot.instance.OpenMainMenuUI(); UIRoot.ClearFatalError(); }; <>c.<>9__31_0 = val; obj = (object)val; } UIMessageBox.Show("Somewhat Fatal Error", text, "Rats!", 3, (Response)obj); UIRoot.ClearFatalError(); return false; } public static void EndGame() { GameMain.End(); } } [BepInPlugin("dsp.getfogged", "Get Fogged Plug-In", "1.0.0")] public class Bootstrap : BaseUnityPlugin { public static Bootstrap instance; public static ManualLogSource Logger; public static Queue buffer = new Queue(); internal void Awake() { instance = this; InitializeLogger(); ApplyHarmonyPatches(); } private void InitializeLogger() { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Expected O, but got Unknown AppDomain.CurrentDomain.UnhandledException += delegate(object o, UnhandledExceptionEventArgs e) { GF.LogError(o, e, 34); }; Version version = Assembly.GetExecutingAssembly().GetName().Version; Assembly assembly = Assembly.GetAssembly(typeof(Patches)); GF.Version = $"{version.Major}.{version.Minor}.{version.Build}"; BCE.Console.Init(); Logger = new ManualLogSource("GF"); Logger.Sources.Add((ILogSource)(object)Logger); GF.ConsoleSplash(); } private void ApplyHarmonyPatches() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown try { Harmony val = new Harmony("dsp.getfogged"); val.PatchAll(typeof(Patches)); } catch (Exception ex) { GF.Error(ex.ToString(), 56); } } public static void Debug(object data, LogLevel logLevel, bool isActive) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (isActive && Logger != null) { while (buffer.Count > 0) { object obj = buffer.Dequeue(); (object, LogLevel, bool) tuple = ((object, LogLevel, bool))obj; if (tuple.Item3) { Logger.Log(tuple.Item2, (object)("Q:" + tuple.Item1)); } } Logger.Log(logLevel, data); } else { buffer.Enqueue((data, logLevel, true)); } } public static void Debug(object data) { Debug(data, (LogLevel)8, isActive: true); } } public static class Patches { [HarmonyPrefix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] public static bool get_difficulty(ref CombatSettings __instance, ref float __result) { float num = ((__instance.aggressiveness < -0.1f) ? (-0.2f) : ((__instance.aggressiveness < 0.25f) ? 0f : ((__instance.aggressiveness < 0.75f) ? 0.5f : ((__instance.aggressiveness < 1.5f) ? 0.75f : ((!(__instance.aggressiveness < 2.5f)) ? 1.125f : 0.875f))))); float num2 = __instance.initialLevel * 0.8f; float num3 = ((__instance.initialGrowth < 0.15f) ? 0f : ((__instance.initialGrowth < 0.3f) ? 0.25f : ((__instance.initialGrowth < 0.65f) ? 0.5f : ((__instance.initialGrowth < 0.8f) ? 0.75f : ((__instance.initialGrowth < 1.15f) ? 1f : ((!(__instance.initialGrowth < 1.65f)) ? __instance.initialGrowth : 1.25f)))))); float num4 = ((__instance.initialColonize < 0.15f) ? 0f : ((__instance.initialColonize < 0.3f) ? 0.25f : ((__instance.initialColonize < 0.65f) ? 0.5f : ((__instance.initialColonize < 0.8f) ? 0.75f : ((__instance.initialColonize < 1.15f) ? 1f : ((!(__instance.initialColonize < 1.65f)) ? __instance.initialColonize : 1.25f)))))); float num5 = __instance.maxDensity - 1f; float num6 = ((__instance.growthSpeedFactor < 0.35f) ? 0.3f : ((__instance.growthSpeedFactor < 0.75f) ? 0.7f : ((__instance.growthSpeedFactor < 1.5f) ? 1f : ((!(__instance.growthSpeedFactor < 2.5f)) ? (__instance.growthSpeedFactor / 2f) : 1.2f)))); float num7 = ((__instance.powerThreatFactor < 0.05f) ? 0.125f : ((__instance.powerThreatFactor < 0.15f) ? 0.3f : ((__instance.powerThreatFactor < 0.25f) ? 0.6f : ((__instance.powerThreatFactor < 0.55f) ? 0.8f : ((__instance.powerThreatFactor < 1.15f) ? 1f : ((__instance.powerThreatFactor < 2.15f) ? 1.2f : ((__instance.powerThreatFactor < 5.15f) ? 1.5f : ((!(__instance.powerThreatFactor < 8.15f)) ? (__instance.powerThreatFactor / 4f) : 1.8f)))))))); float num8 = ((__instance.battleThreatFactor < 0.05f) ? 0.125f : ((__instance.battleThreatFactor < 0.15f) ? 0.3f : ((__instance.battleThreatFactor < 0.25f) ? 0.6f : ((__instance.battleThreatFactor < 0.55f) ? 0.8f : ((__instance.battleThreatFactor < 1.15f) ? 1f : ((__instance.battleThreatFactor < 2.15f) ? 1.2f : ((__instance.battleThreatFactor < 5.15f) ? 1.5f : ((!(__instance.battleThreatFactor < 8.15f)) ? (__instance.battleExpFactor / 4f) : 1.8f)))))))); float num9 = ((__instance.battleExpFactor < 0.05f) ? 0f : ((__instance.battleExpFactor < 0.15f) ? 1f : ((__instance.battleExpFactor < 0.25f) ? 3f : ((__instance.battleExpFactor < 0.55f) ? 6f : ((__instance.battleExpFactor < 1.15f) ? 10f : ((__instance.battleExpFactor < 2.15f) ? 12f : ((__instance.battleExpFactor < 5.15f) ? 14f : ((!(__instance.battleExpFactor < 8.15f)) ? (__instance.battleExpFactor * 2f) : 16f)))))))); float num10 = ((num < 0f) ? 0f : (0.25f + num * (num7 * 0.5f + num8 * 0.5f))); float num11 = 0.375f + 0.625f * ((num2 + num9) / 10f); float num12 = 0.375f + 0.625f * ((num4 * 0.6f + num3 * 0.4f * (num4 * 0.75f + 0.25f)) * 0.6f + num6 * 0.4f * (num4 * 0.8f + 0.2f) + num5 * 0.29f * (num4 * 0.5f + 0.5f)); __result = (float)(int)(num10 * num11 * num12 * 10000f + 0.5f) / 10000f; if (__result < 0f || __result > 9001f) { __result = 9001f; } return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "OnCombatThreatSliderChanged")] private static bool OnCombatThreatSliderChanged(ref UICombatSettingsDF __instance, float arg0) { float value = __instance.combatThreatSlider.value; if (value < 0.5f) { __instance.combatSettings.battleThreatFactor = 0.01f; } else if (value < 1.5f) { __instance.combatSettings.battleThreatFactor = 0.1f; } else if (value < 2.5f) { __instance.combatSettings.battleThreatFactor = 0.2f; } else if (value < 3.5f) { __instance.combatSettings.battleThreatFactor = 0.5f; } else if (value < 4.5f) { __instance.combatSettings.battleThreatFactor = 1f; } else if (value < 5.5f) { __instance.combatSettings.battleThreatFactor = 2f; } else if (value < 6.5f) { __instance.combatSettings.battleThreatFactor = 5f; } else if (value < 7.5f) { __instance.combatSettings.battleThreatFactor = 8f; } else { __instance.combatSettings.battleThreatFactor = Mathf.FloorToInt(value); } return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "OnEXPSliderChanged")] private static bool OnEXPSliderChanged(ref UICombatSettingsDF __instance, float arg0) { float value = __instance.DFExpSlider.value; if (value < 0.5f) { __instance.combatSettings.battleExpFactor = 0.01f; } else if (value < 1.5f) { __instance.combatSettings.battleExpFactor = 0.1f; } else if (value < 2.5f) { __instance.combatSettings.battleExpFactor = 0.2f; } else if (value < 3.5f) { __instance.combatSettings.battleExpFactor = 0.5f; } else if (value < 4.5f) { __instance.combatSettings.battleExpFactor = 1f; } else if (value < 5.5f) { __instance.combatSettings.battleExpFactor = 2f; } else if (value < 6.5f) { __instance.combatSettings.battleExpFactor = 5f; } else if (value < 7.5f) { __instance.combatSettings.battleExpFactor = 8f; } else { __instance.combatSettings.battleExpFactor = Mathf.FloorToInt(value + 1f); } __instance.UpdateUIParametersDisplay(); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "OnGrowthSpeedSliderChanged")] private static bool OnGrowthSpeedSliderChanged(ref UICombatSettingsDF __instance, float arg0) { float value = __instance.growthSpeedSlider.value; if (value < 0.5f) { __instance.combatSettings.growthSpeedFactor = 0.25f; } else if (value < 1.5f) { __instance.combatSettings.growthSpeedFactor = 0.5f; } else if (value < 2.5f) { __instance.combatSettings.growthSpeedFactor = 1f; } else if (value < 3.5f) { __instance.combatSettings.growthSpeedFactor = 2f; } else { __instance.combatSettings.growthSpeedFactor = Mathf.RoundToInt(value - 1.5f); } __instance.UpdateUIParametersDisplay(); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "OnInitGrowthSliderChanged")] private static bool OnInitGrowthSliderChanged(ref UICombatSettingsDF __instance, float arg0) { float value = __instance.initGrowthSlider.value; if (value < 0.5f) { __instance.combatSettings.initialGrowth = 0f; } else if (value < 1.5f) { __instance.combatSettings.initialGrowth = 0.25f; } else if (value < 2.5f) { __instance.combatSettings.initialGrowth = 0.5f; } else if (value < 3.5f) { __instance.combatSettings.initialGrowth = 0.75f; } else if (value < 4.5f) { __instance.combatSettings.initialGrowth = 1f; } else if (value < 5.5f) { __instance.combatSettings.initialGrowth = 1.5f; } else { __instance.combatSettings.initialGrowth = Mathf.FloorToInt(value / 3f); } __instance.UpdateUIParametersDisplay(); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "OnInitOccupiedSliderChanged")] private static bool OnInitOccupiedSliderChanged(ref UICombatSettingsDF __instance, float arg0) { float value = __instance.initOccupiedSlider.value; if (value < 0.5f) { __instance.combatSettings.initialColonize = 0.01f; } else if (value < 1.5f) { __instance.combatSettings.initialColonize = 0.25f; } else if (value < 2.5f) { __instance.combatSettings.initialColonize = 0.5f; } else if (value < 3.5f) { __instance.combatSettings.initialColonize = 0.75f; } else if (value < 4.5f) { __instance.combatSettings.initialColonize = 1f; } else if (value < 5.5f) { __instance.combatSettings.initialColonize = 1.5f; } else { __instance.combatSettings.initialColonize = Mathf.FloorToInt(value / 3f); } __instance.UpdateUIParametersDisplay(); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "OnMaxDensitySliderChanged")] private static bool OnMaxDensitySliderChanged(ref UICombatSettingsDF __instance, float arg0) { float value = __instance.maxDensitySlider.value; if (value < 0.5f) { __instance.combatSettings.maxDensity = 1f; } else if (value < 1.5f) { __instance.combatSettings.maxDensity = 1.5f; } else if (value < 2.5f) { __instance.combatSettings.maxDensity = 2f; } else if (value < 3.5f) { __instance.combatSettings.maxDensity = 2.5f; } else { __instance.combatSettings.maxDensity = Mathf.FloorToInt(value); } __instance.UpdateUIParametersDisplay(); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "OnPowerThreatSliderChanged")] private static bool OnPowerThreatSliderChanged(ref UICombatSettingsDF __instance, float arg0) { float value = __instance.powerThreatSlider.value; if (value < 0.5f) { __instance.combatSettings.powerThreatFactor = 0.01f; } else if (value < 1.5f) { __instance.combatSettings.powerThreatFactor = 0.1f; } else if (value < 2.5f) { __instance.combatSettings.powerThreatFactor = 0.2f; } else if (value < 3.5f) { __instance.combatSettings.powerThreatFactor = 0.5f; } else if (value < 4.5f) { __instance.combatSettings.powerThreatFactor = 1f; } else if (value < 5.5f) { __instance.combatSettings.powerThreatFactor = 2f; } else if (value < 6.5f) { __instance.combatSettings.powerThreatFactor = 5f; } else if (value < 7.5f) { __instance.combatSettings.powerThreatFactor = 8f; } else { __instance.combatSettings.powerThreatFactor = Mathf.FloorToInt(value); } __instance.UpdateUIParametersDisplay(); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "OnInitLevelSliderChanged")] private static bool OnInitLevelSliderChanged(ref UICombatSettingsDF __instance, float arg0) { float value = __instance.initLevelSlider.value; if (value < 0.5f) { __instance.combatSettings.initialLevel = 0f; } else if (value < 1.5f) { __instance.combatSettings.initialLevel = 1f; } else if (value < 2.5f) { __instance.combatSettings.initialLevel = 2f; } else if (value < 3.5f) { __instance.combatSettings.initialLevel = 3f; } else if (value < 4.5f) { __instance.combatSettings.initialLevel = 4f; } else if (value < 5.5f) { __instance.combatSettings.initialLevel = 5f; } else if (value < 6.5f) { __instance.combatSettings.initialLevel = 6f; } else if (value < 7.5f) { __instance.combatSettings.initialLevel = 7f; } else if (value < 8.5f) { __instance.combatSettings.initialLevel = 8f; } else if (value < 9.5f) { __instance.combatSettings.initialLevel = 9f; } else { __instance.combatSettings.initialLevel = Mathf.FloorToInt(value); } __instance.UpdateUIParametersDisplay(); return false; } [HarmonyPrefix] [HarmonyPatch(typeof(UICombatSettingsDF), "UpdateUIParametersDisplay")] public static bool UpdateUIParametersDisplay(ref UICombatSettingsDF __instance) { //IL_0bd1: Unknown result type (might be due to invalid IL or missing references) //IL_0bd7: Expected O, but got Unknown //IL_0c34: Unknown result type (might be due to invalid IL or missing references) //IL_0c3b: Invalid comparison between Unknown and I4 //IL_0c67: Unknown result type (might be due to invalid IL or missing references) //IL_0c6c: Unknown result type (might be due to invalid IL or missing references) float aggressiveness = __instance.combatSettings.aggressiveness; string text = ""; if (aggressiveness < -0.99f) { __instance.aggresiveSlider.value = 0f; } else if (aggressiveness < 0.01f) { __instance.aggresiveSlider.value = 1f; } else if (aggressiveness < 0.51f) { __instance.aggresiveSlider.value = 2f; } else if (aggressiveness < 1.01f) { __instance.aggresiveSlider.value = 3f; } else if (aggressiveness < 2.01f) { __instance.aggresiveSlider.value = 4f; } else { __instance.aggresiveSlider.value = 5f; } switch ((int)(__instance.aggresiveSlider.value + 0.5f)) { case 0: text = Localization.Translate("活靶子"); break; case 1: text = Localization.Translate("被动"); break; case 2: text = Localization.Translate("消极"); break; case 3: text = Localization.Translate("正常"); break; case 4: text = Localization.Translate("积极"); break; case 5: text = Localization.Translate("狂暴"); break; } __instance.aggresiveText.text = text; aggressiveness = __instance.combatSettings.initialLevel; if (aggressiveness < 0.01f) { __instance.initLevelSlider.value = 0f; } else if (aggressiveness < 1.01f) { __instance.initLevelSlider.value = 1f; } else if (aggressiveness < 2.01f) { __instance.initLevelSlider.value = 2f; } else if (aggressiveness < 3.01f) { __instance.initLevelSlider.value = 3f; } else if (aggressiveness < 4.01f) { __instance.initLevelSlider.value = 4f; } else if (aggressiveness < 5.01f) { __instance.initLevelSlider.value = 5f; } else if (aggressiveness < 6.01f) { __instance.initLevelSlider.value = 6f; } else if (aggressiveness < 7.01f) { __instance.initLevelSlider.value = 7f; } else if (aggressiveness < 8.01f) { __instance.initLevelSlider.value = 8f; } else if (aggressiveness < 9.01f) { __instance.initLevelSlider.value = 9f; } else { __instance.initLevelSlider.value = Mathf.CeilToInt(__instance.initLevelSlider.value); } text = aggressiveness.ToString(); __instance.initLevelText.text = text; aggressiveness = __instance.combatSettings.initialGrowth; if (aggressiveness < 0.01f) { __instance.initGrowthSlider.value = 0f; } else if (aggressiveness < 0.26f) { __instance.initGrowthSlider.value = 1f; } else if (aggressiveness < 0.51f) { __instance.initGrowthSlider.value = 2f; } else if (aggressiveness < 0.76f) { __instance.initGrowthSlider.value = 3f; } else if (aggressiveness < 1.01f) { __instance.initGrowthSlider.value = 4f; } else if (aggressiveness < 1.51f) { __instance.initGrowthSlider.value = 5f; } else { __instance.initGrowthSlider.value = Mathf.CeilToInt(aggressiveness * 3.33f); } text = aggressiveness * 100f + "%"; __instance.initGrowthText.text = text; aggressiveness = __instance.combatSettings.initialColonize; if (aggressiveness < 0.02f) { __instance.initOccupiedSlider.value = 0f; } else if (aggressiveness < 0.26f) { __instance.initOccupiedSlider.value = 1f; } else if (aggressiveness < 0.51f) { __instance.initOccupiedSlider.value = 2f; } else if (aggressiveness < 0.76f) { __instance.initOccupiedSlider.value = 3f; } else if (aggressiveness < 1.01f) { __instance.initOccupiedSlider.value = 4f; } else if (aggressiveness < 1.51f) { __instance.initOccupiedSlider.value = 5f; } else { __instance.initOccupiedSlider.value = Mathf.CeilToInt(aggressiveness * 3.33f); } text = aggressiveness * 100f + "%"; __instance.initOccupiedText.text = text; aggressiveness = __instance.combatSettings.maxDensity; if (aggressiveness < 1.01f) { __instance.maxDensitySlider.value = 0f; } else if (aggressiveness < 1.51f) { __instance.maxDensitySlider.value = 1f; } else if (aggressiveness < 2.01f) { __instance.maxDensitySlider.value = 2f; } else if (aggressiveness < 2.51f) { __instance.maxDensitySlider.value = 3f; } else { __instance.maxDensitySlider.value = Mathf.FloorToInt(aggressiveness); } text = aggressiveness + "x"; __instance.maxDensityText.text = text; aggressiveness = __instance.combatSettings.growthSpeedFactor; if (aggressiveness < 0.26f) { __instance.growthSpeedSlider.value = 0f; } else if (aggressiveness < 0.51f) { __instance.growthSpeedSlider.value = 1f; } else if (aggressiveness < 1.01f) { __instance.growthSpeedSlider.value = 2f; } else if (aggressiveness < 2.01f) { __instance.growthSpeedSlider.value = 3f; } else { __instance.growthSpeedSlider.value = (float)Mathf.CeilToInt(aggressiveness) + 1f; } text = aggressiveness * 100f + "%"; __instance.growthSpeedText.text = text; aggressiveness = __instance.combatSettings.powerThreatFactor; if (aggressiveness < 0.02f) { __instance.powerThreatSlider.value = 0f; } else if (aggressiveness < 0.11f) { __instance.powerThreatSlider.value = 1f; } else if (aggressiveness < 0.21000001f) { __instance.powerThreatSlider.value = 2f; } else if (aggressiveness < 0.51f) { __instance.powerThreatSlider.value = 3f; } else if (aggressiveness < 1.01f) { __instance.powerThreatSlider.value = 4f; } else if (aggressiveness < 2.01f) { __instance.powerThreatSlider.value = 5f; } else if (aggressiveness < 5.01f) { __instance.powerThreatSlider.value = 6f; } else if (aggressiveness < 8.01f) { __instance.powerThreatSlider.value = 7f; } else { __instance.powerThreatSlider.value = Mathf.FloorToInt(aggressiveness); } text = aggressiveness * 100f + "%"; __instance.powerThreatText.text = text; aggressiveness = __instance.combatSettings.battleThreatFactor; if (aggressiveness < 0.02f) { __instance.combatThreatSlider.value = 0f; } else if (aggressiveness < 0.11f) { __instance.combatThreatSlider.value = 1f; } else if (aggressiveness < 0.21000001f) { __instance.combatThreatSlider.value = 2f; } else if (aggressiveness < 0.51f) { __instance.combatThreatSlider.value = 3f; } else if (aggressiveness < 1.01f) { __instance.combatThreatSlider.value = 4f; } else if (aggressiveness < 2.01f) { __instance.combatThreatSlider.value = 5f; } else if (aggressiveness < 5.01f) { __instance.combatThreatSlider.value = 6f; } else if (aggressiveness < 8.01f) { __instance.combatThreatSlider.value = 7f; } else { __instance.combatThreatSlider.value = Mathf.FloorToInt(aggressiveness); } text = aggressiveness * 100f + "%"; __instance.combatThreatText.text = text; aggressiveness = __instance.combatSettings.battleExpFactor; if (aggressiveness < 0.02f) { __instance.DFExpSlider.value = 0f; } else if (aggressiveness < 0.11f) { __instance.DFExpSlider.value = 1f; } else if (aggressiveness < 0.21000001f) { __instance.DFExpSlider.value = 2f; } else if (aggressiveness < 0.51f) { __instance.DFExpSlider.value = 3f; } else if (aggressiveness < 1.01f) { __instance.DFExpSlider.value = 4f; } else if (aggressiveness < 2.01f) { __instance.DFExpSlider.value = 5f; } else if (aggressiveness < 5.01f) { __instance.DFExpSlider.value = 6f; } else if (aggressiveness < 8.01f) { __instance.DFExpSlider.value = 7f; } else { __instance.DFExpSlider.value = Mathf.FloorToInt(aggressiveness + 1f); } text = aggressiveness * 100f + "%"; __instance.DFExpText.text = text; GameDesc val = new GameDesc(); float difficulty = ((CombatSettings)(ref __instance.combatSettings)).difficulty; string arg = ((difficulty >= 9.9999f) ? difficulty.ToString("0.00") : difficulty.ToString("0.000")); __instance.difficultyText.text = string.Format(Localization.Translate("难度系数值"), arg); __instance.difficultTipGroupDF.SetActive(((int)((CombatSettings)(ref __instance.combatSettings)).aggressiveLevel == 40 && difficulty > 4.5f) || difficulty > 6f); __instance.gameDesc.CopyTo(val); val.combatSettings = __instance.combatSettings; __instance.propertyMultiplierText.text = Localization.Translate("元数据生成倍率") + " " + val.propertyMultiplier.ToString("0%"); return false; } [HarmonyPostfix] [HarmonyPatch(typeof(UICombatSettingsDF), "_OnOpen")] public static void _OnOpen(ref UICombatSettingsDF __instance) { __instance.initLevelSlider.maxValue = 100f; __instance.initLevelSlider.m_MaxValue = 100f; __instance.growthSpeedSlider.maxValue = 300f; __instance.growthSpeedSlider.m_MaxValue = 300f; __instance.initGrowthSlider.maxValue = 300f; __instance.initGrowthSlider.m_MaxValue = 300f; __instance.initOccupiedSlider.maxValue = 300f; __instance.initOccupiedSlider.m_MaxValue = 300f; __instance.maxDensitySlider.maxValue = 30f; __instance.maxDensitySlider.m_MaxValue = 30f; __instance.powerThreatSlider.maxValue = 1000f; __instance.powerThreatSlider.m_MaxValue = 1000f; __instance.DFExpSlider.maxValue = 1000f; __instance.DFExpSlider.m_MaxValue = 1000f; __instance.combatThreatSlider.maxValue = 1000f; __instance.combatThreatSlider.m_MaxValue = 1000f; } [HarmonyPrefix] [HarmonyPatch(typeof(EvolveData), "AddExpPoint")] public static bool AddExpPoint(ref EvolveData __instance, int _addexpp) { if (__instance.level >= 100) { if (__instance.expf != 0 || __instance.expp != 0 || __instance.level != 100) { __instance.level = 100; __instance.expf = 0; __instance.expp = 0; __instance.expl = EvolveData.LevelCummulativeExp(100); } return false; } if (_addexpp > 0) { __instance.expp += _addexpp; if (__instance.expp >= 10000) { __instance.expf += __instance.expp / 10000; __instance.expp %= 10000; while (__instance.expf >= EvolveData.levelExps[__instance.level]) { int num = EvolveData.levelExps.Length - 1; __instance.expf -= EvolveData.levelExps[__instance.level]; __instance.expl += EvolveData.levelExps[__instance.level]; __instance.level++; if (__instance.level >= num) { __instance.level = num; __instance.expf = 0; __instance.expp = 0; return false; } } } } return false; } [HarmonyPrefix] [HarmonyPatch(typeof(EvolveData), "AddExp")] public static bool AddExp(ref EvolveData __instance, int _addexp) { if (__instance.level >= 100) { if (__instance.expf != 0 || __instance.expp != 0 || __instance.level != 100) { __instance.level = 100; __instance.expf = 0; __instance.expp = 0; __instance.expl = EvolveData.LevelCummulativeExp(100); } return false; } __instance.expf += _addexp; while (__instance.expf >= EvolveData.levelExps[__instance.level]) { int num = EvolveData.levelExps.Length - 1; __instance.expf -= EvolveData.levelExps[__instance.level]; __instance.expl += EvolveData.levelExps[__instance.level]; __instance.level++; if (__instance.level >= num) { __instance.level = num; __instance.expf = 0; return false; } } return false; } [HarmonyPostfix] [HarmonyPatch(typeof(StarGen), "CreateStar")] [HarmonyPatch(typeof(StarGen), "CreateBirthStar")] public static void ClampHiveCount(ref StarData __result) { __result.maxHiveCount = Mathf.Clamp(__result.maxHiveCount, 0, 8); __result.initialHiveCount = Mathf.Clamp(__result.initialHiveCount, 0, 8); } } public static class BCE { public static class Console { public static void Init() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); Assembly[] array = assemblies; foreach (Assembly assembly in array) { if (!(assembly.GetName().Name != "BCE")) { t = assembly.GetType("BCE.console"); disabled = false; } } initialized = true; } public static void Write(string s, ConsoleColor c) { if (!initialized) { Init(); } if (!disabled) { t.GetMethod("Write", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, new object[2] { s, c }); } else { GF.Log(s, 35); } } public static void WriteLine(string s, ConsoleColor c) { if (!initialized) { Init(); } if (!disabled) { t.GetMethod("WriteLine", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, new object[2] { s, c }); } } } public static bool disabled = true; private static bool initialized; private static Type t; } public static class Utils { public static class AddressHelper { [StructLayout(LayoutKind.Explicit)] private struct ObjectReinterpreter { [FieldOffset(0)] public ObjectWrapper AsObject; [FieldOffset(0)] public readonly IntPtrWrapper AsIntPtr; } private class ObjectWrapper { public object Object; } private class IntPtrWrapper { public IntPtr Value; } private static readonly object mutualObject; private static readonly ObjectReinterpreter reinterpreter; static AddressHelper() { mutualObject = new object(); reinterpreter = default(ObjectReinterpreter); reinterpreter.AsObject = new ObjectWrapper(); } public static IntPtr GetAddress(object obj) { lock (mutualObject) { reinterpreter.AsObject.Object = obj; IntPtr value = reinterpreter.AsIntPtr.Value; reinterpreter.AsObject.Object = null; return value; } } public static T GetInstance<T>(IntPtr address) { lock (mutualObject) { reinterpreter.AsIntPtr.Value = address; return (T)reinterpreter.AsObject.Object; } } } public static Dictionary<PlanetData, PlanetFactory> PlanetFactories = new Dictionary<PlanetData, PlanetFactory>(); public static CodeInstruction Call(Type type, string name, Type[] parameters = null, Type[] generics = null) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(type, name, parameters, generics); if ((object)methodInfo == null) { throw new ArgumentException($"No method found for type={type}, name={name}, parameters={GeneralExtensions.Description(parameters)}, generics={GeneralExtensions.Description(generics)}"); } return new CodeInstruction(OpCodes.Call, (object)methodInfo); } public static CodeInstruction Call(string typeColonMethodname, Type[] parameters = null, Type[] generics = null) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeColonMethodname, parameters, generics); if ((object)methodInfo == null) { throw new ArgumentException("No method found for " + typeColonMethodname + ", parameters=" + GeneralExtensions.Description(parameters) + ", generics=" + GeneralExtensions.Description(generics)); } return new CodeInstruction(OpCodes.Call, (object)methodInfo); } public static CodeInstruction Call(Expression<Action> expression) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new CodeInstruction(OpCodes.Call, (object)SymbolExtensions.GetMethodInfo(expression)); } public static CodeInstruction Call<T>(Expression<Action<T>> expression) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new CodeInstruction(OpCodes.Call, (object)SymbolExtensions.GetMethodInfo<T>(expression)); } public static CodeInstruction Call<T, TResult>(Expression<Func<T, TResult>> expression) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new CodeInstruction(OpCodes.Call, (object)SymbolExtensions.GetMethodInfo<T, TResult>(expression)); } public static CodeInstruction Call(LambdaExpression expression) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new CodeInstruction(OpCodes.Call, (object)SymbolExtensions.GetMethodInfo(expression)); } public static CodeInstruction LoadField(Type type, string name, bool useAddress = false) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown FieldInfo fieldInfo = AccessTools.Field(type, name); if ((object)fieldInfo == null) { throw new ArgumentException($"No field found for {type} and {name}"); } return new CodeInstruction((!useAddress) ? (fieldInfo.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld) : (fieldInfo.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda), (object)fieldInfo); } public static CodeInstruction StoreField(Type type, string name) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown FieldInfo fieldInfo = AccessTools.Field(type, name); if ((object)fieldInfo == null) { throw new ArgumentException($"No field found for {type} and {name}"); } return new CodeInstruction(fieldInfo.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, (object)fieldInfo); } public static CodeInstruction LoadLocal(int index, bool useAddress = false) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown if (useAddress) { if (index < 256) { return new CodeInstruction(OpCodes.Ldloca_S, (object)Convert.ToByte(index)); } return new CodeInstruction(OpCodes.Ldloca, (object)index); } if (index == 0) { return new CodeInstruction(OpCodes.Ldloc_0, (object)null); } if (index == 1) { return new CodeInstruction(OpCodes.Ldloc_1, (object)null); } if (index == 2) { return new CodeInstruction(OpCodes.Ldloc_2, (object)null); } if (index == 3) { return new CodeInstruction(OpCodes.Ldloc_3, (object)null); } if (index < 256) { return new CodeInstruction(OpCodes.Ldloc_S, (object)Convert.ToByte(index)); } return new CodeInstruction(OpCodes.Ldloc, (object)index); } public static CodeInstruction StoreLocal(int index) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown if (index == 0) { return new CodeInstruction(OpCodes.Stloc_0, (object)null); } if (index == 1) { return new CodeInstruction(OpCodes.Stloc_1, (object)null); } if (index == 2) { return new CodeInstruction(OpCodes.Stloc_2, (object)null); } if (index == 3) { return new CodeInstruction(OpCodes.Stloc_3, (object)null); } if (index < 256) { return new CodeInstruction(OpCodes.Stloc_S, (object)Convert.ToByte(index)); } return new CodeInstruction(OpCodes.Stloc, (object)index); } public static CodeInstruction LoadArgument(int index, bool useAddress = false) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown if (useAddress) { if (index < 256) { return new CodeInstruction(OpCodes.Ldarga_S, (object)Convert.ToByte(index)); } return new CodeInstruction(OpCodes.Ldarga, (object)index); } if (index == 0) { return new CodeInstruction(OpCodes.Ldarg_0, (object)null); } if (index == 1) { return new CodeInstruction(OpCodes.Ldarg_1, (object)null); } if (index == 2) { return new CodeInstruction(OpCodes.Ldarg_2, (object)null); } if (index == 3) { return new CodeInstruction(OpCodes.Ldarg_3, (object)null); } if (index < 256) { return new CodeInstruction(OpCodes.Ldarg_S, (object)Convert.ToByte(index)); } return new CodeInstruction(OpCodes.Ldarg, (object)index); } public static CodeInstruction StoreArgument(int index) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown if (index < 256) { return new CodeInstruction(OpCodes.Starg_S, (object)Convert.ToByte(index)); } return new CodeInstruction(OpCodes.Starg, (object)index); } public static double ModifyRadius(double vanilla, double realRadius) { bool flag = false; if (realRadius < 0.0) { flag = true; realRadius *= -1.0; } double num = vanilla - 200.0; realRadius += num; if (flag) { realRadius *= -1.0; } return realRadius; } public static T GetRadiusFromMecha<T>(T t, Mecha mecha) { double vanilla = Convert.ToDouble(t); float? obj; if (mecha == null) { obj = null; } else { Player player = mecha.player; if (player == null) { obj = null; } else { PlanetData planetData = player.planetData; obj = ((planetData != null) ? new float?(planetData.realRadius) : null); } } double num = ModifyRadius(vanilla, ((double?)obj) ?? 200.0); return (T)Convert.ChangeType(num, typeof(T)); } public static T GetRadiusFromFactory<T>(T t, PlanetFactory factory) { double vanilla = Convert.ToDouble(t); float? obj; if (factory == null) { obj = null; } else { PlanetData planet = factory.planet; obj = ((planet != null) ? new float?(planet.realRadius) : null); } double num = ModifyRadius(vanilla, ((double?)obj) ?? 200.0); return (T)Convert.ChangeType(num, typeof(T)); } public static float GetSquareRadiusFromAstroFactoryId(int id) { PlanetFactory val = GameMain.data.spaceSector.skillSystem.astroFactories[id]; float num = val.planet.realRadius * val.planet.realRadius; if (VFInput.alt) { GF.Log($"GetRadiusSquareFromFactory Called By {GF.GetCaller()} {GF.GetCaller(1)} {GF.GetCaller(2)} returning {num}", 48); } return num; } public static T GetRadiusFromAstroId<T>(T t, int id) { double vanilla = Convert.ToDouble(t); GalaxyData galaxy = GameMain.data.galaxy; float? obj; if (galaxy == null) { obj = null; } else { PlanetFactory obj2 = galaxy.astrosFactory[id]; if (obj2 == null) { obj = null; } else { PlanetData planet = obj2.planet; obj = ((planet != null) ? new float?(planet.realRadius) : null); } } double num = ModifyRadius(vanilla, ((double?)obj) ?? 200.0); return (T)Convert.ChangeType(num, typeof(T)); } public static T GetRadiusFromLocalPlanet<T>(T t) { double vanilla = Convert.ToDouble(t); PlanetData localPlanet = GameMain.localPlanet; double num = ModifyRadius(vanilla, ((double?)((localPlanet != null) ? new float?(localPlanet.realRadius) : null)) ?? 200.0); return (T)Convert.ChangeType(num, typeof(T)); } public static T GetRadiusFromEnemyData<T>(T t, ref EnemyData enemyData) { double vanilla = Convert.ToDouble(t); PlanetData obj = GameMain.galaxy.PlanetById(enemyData.astroId); double num = ModifyRadius(vanilla, ((double?)((obj != null) ? new float?(obj.realRadius) : null)) ?? 200.0); return (T)Convert.ChangeType(num, typeof(T)); } public static T GetRadiusFromAltitude<T>(T t, float alt) { double num = ModifyRadius(Convert.ToDouble(t), Convert.ToDouble(alt)); return (T)Convert.ChangeType(num, typeof(T)); } public static PlanetFactory GetPlanetFactoryFromPlanetData(PlanetData planet) { if (planet == null) { return null; } if (PlanetFactories.ContainsKey(planet)) { return PlanetFactories[planet]; } PlanetFactory[] astrosFactory = GameMain.spaceSector.galaxy.astrosFactory; foreach (PlanetFactory val in astrosFactory) { if (((val != null) ? val.planet : null) != null && !PlanetFactories.ContainsKey(val.planet)) { PlanetFactories.Add(val.planet, val); } } return PlanetFactories.ContainsKey(planet) ? PlanetFactories[planet] : null; } public static float getPlanetSize(float mod = 0f) { PlanetData localPlanet = GameMain.localPlanet; return (localPlanet != null) ? (localPlanet.realRadius + mod) : (200f + mod); } public static string Serialize(object value, bool pretty = true) { fsSerializer fsSerializer = new fsSerializer(); fsSerializer.TrySerialize(value, out var data); if (!pretty) { return fsJsonPrinter.CompressedJson(data); } return fsJsonPrinter.PrettyJson(data); } public static T DeSerialize<T>(string json) { fsSerializer fsSerializer = new fsSerializer(); fsData data; fsResult fsResult = fsJsonParser.Parse(json, out data); if (fsResult.Failed) { GF.Error("Deserialization of Json " + json + " failed. " + fsResult.FormattedMessages, 59); return default(T); } T instance = default(T); fsResult fsResult2 = fsSerializer.TryDeserialize(data, ref instance); if (fsResult2.Failed) { GF.Error("Failed to deserialize " + json + ": " + fsResult2.FormattedMessages, 67); return default(T); } return instance; } public static T[] ResourcesLoadArray<T>(string path, string format, bool emptyNull) where T : Object { List<T> list = new List<T>(); T val = Resources.Load<T>(path); if ((Object)(object)val == (Object)null) { return null; } int num = 0; if ((Object)(object)val != (Object)null) { list.Add(val); num = 1; } do { val = Resources.Load<T>(string.Format(format, path, num)); if ((Object)(object)val == (Object)null || ((num == 1 || num == 2) && list.Contains(val))) { break; } list.Add(val); num++; } while (num < 1024); if (emptyNull && list.Count == 0) { return null; } return list.ToArray(); } public static VectorLF3 PolarToCartesian(double p, double theta, double phi) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) double num = p * Math.Sin(phi) * Math.Cos(theta); double num2 = p * Math.Sin(phi) * Math.Sin(theta); double num3 = p * Math.Cos(phi); return new VectorLF3(num3, num2, num3); } public static Vector3 RandomDirection(GF.Random random) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) Vector3 zero = Vector3.zero; zero.x = (float)random.NextDouble() * 2f - 1f; zero.y = (float)random.NextDouble() * 2f - 1f; zero.z = (float)random.NextDouble() * 2f - 1f; return zero; } public static Type GetCallingType() { return new StackTrace().GetFrame(2).GetMethod().ReflectedType; } public static double DistanceVLF3(VectorLF3 a, VectorLF3 b) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) VectorLF3 val = new VectorLF3(a.x - b.x, a.y - b.y, a.z - b.z); return ((VectorLF3)(ref val)).magnitude; } public static bool ArrayCompare<T>(T[] a1, T[] a2) { return a1.SequenceEqual(a2); } public static T ReverseLookup<T, W>(Dictionary<T, W> dict, W val) { foreach (KeyValuePair<T, W> item in dict) { if (item.Value.ToString() == val.ToString()) { return item.Key; } } return default(T); } public static float diff(float a, float b) { return (!(a > b)) ? (b - a) : (a - b); } public static List<VectorLF3> RegularPointsOnSphere(float radius, int count) { //IL_00f9: Unknown result type (might be due to invalid IL or missing references) List<VectorLF3> list = new List<VectorLF3>(); if (count == 0) { return list; } double num = Math.PI * 4.0 * (Math.Pow(radius, 2.0) / (double)count); double num2 = Math.Sqrt(num); int num3 = (int)Math.Round(Math.PI / num2); double num4 = Math.PI / (double)num3; double num5 = num / num4; for (int i = 0; i < num3; i++) { double num6 = Math.PI * ((double)i + 0.5) / (double)num3; int num7 = (int)Math.Round(Math.PI * 2.0 * Math.Sin(num6) / num5); for (int j = 0; j < num7; j++) { double num8 = Math.PI * 2.0 * (double)j / (double)num7; double num9 = (double)radius * Math.Sin(num6) * Math.Cos(num8); double num10 = (double)radius * Math.Sin(num6) * Math.Sin(num8); double num11 = (double)radius * Math.Cos(num6); list.Add(new VectorLF3(num9, num10, num11)); } } return list; } public static float Round2DP(float num) { return Mathf.Round(num * 100f) / 100f; } } public static class Methods { public static MethodInfo GetRadiusFromAstroId(this CodeMatcher matcher) { return AccessTools.Method(typeof(Utils), "GetRadiusFromAstroId", (Type[])null, (Type[])null).MakeGenericMethod(matcher.Operand?.GetType() ?? typeof(float)); } public static MethodInfo GetRadiusFromLocalPlanet(this CodeMatcher matcher) { return AccessTools.Method(typeof(Utils), "GetRadiusFromLocalPlanet", (Type[])null, (Type[])null).MakeGenericMethod(matcher.Operand?.GetType() ?? typeof(float)); } public static MethodInfo GetRadiusFromEnemyData(this CodeMatcher matcher) { return AccessTools.Method(typeof(Utils), "GetRadiusFromEnemyData", (Type[])null, (Type[])null).MakeGenericMethod(matcher.Operand?.GetType() ?? typeof(float)); } public static MethodInfo GetRadiusFromMecha(this CodeMatcher matcher) { return AccessTools.Method(typeof(Utils), "GetRadiusFromMecha", (Type[])null, (Type[])null).MakeGenericMethod(matcher.Operand?.GetType() ?? typeof(float)); } public static MethodInfo GetRadiusFromFactory(this CodeMatcher matcher) { return AccessTools.Method(typeof(Utils), "GetRadiusFromFactory", (Type[])null, (Type[])null).MakeGenericMethod(matcher.Operand?.GetType() ?? typeof(float)); } public static MethodInfo GetRadiusFromAltitude(this CodeMatcher matcher) { return AccessTools.Method(typeof(Utils), "GetRadiusFromAltitude", (Type[])null, (Type[])null).MakeGenericMethod(matcher.Operand?.GetType() ?? typeof(float)); } public static MethodInfo GetSquareRadiusFromAstroFactoryId(this CodeMatcher matcher) { return AccessTools.Method(typeof(Utils), "GetSquareRadiusFromAstroFactoryId", (Type[])null, (Type[])null); } } public static class PluginInfo { public const string PLUGIN_GUID = "GetFogged"; public const string PLUGIN_NAME = "GetFogged"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace PCGSharp { public class Pcg { private const ulong ShiftedIncrement = 721347520444481703uL; private const ulong Multiplier = 6364136223846793005uL; private const double ToDouble01 = 2.3283064365386963E-10; private ulong _increment = 1442695040888963407uL; private ulong _state; public Pcg(int seed) : this((ulong)seed) { } public Pcg(ulong seed, ulong sequence = 721347520444481703uL) { Initialize(seed, sequence); } public int Next() { uint num = NextUInt(); return (int)(num >> 1); } public int Next(int maxExclusive) { if (maxExclusive <= 0) { throw new ArgumentException("Max Exclusive must be positive"); } uint num = (uint)(0L - (long)(uint)maxExclusive) % (uint)maxExclusive; uint num2; do { num2 = NextUInt(); } while (num2 < num); return (int)(num2 % (uint)maxExclusive); } public int Next(int minInclusive, int maxExclusive) { if (maxExclusive <= minInclusive) { throw new ArgumentException("MaxExclusive must be larger than MinInclusive"); } uint num = (uint)(maxExclusive - minInclusive); uint num2 = (uint)(0L - (long)num) % num; uint num3; do { num3 = NextUInt(); } while (num3 < num2); return (int)(num3 % num + minInclusive); } public virtual uint NextUInt() { ulong state = _state; _state = state * 6364136223846793005L + _increment; uint num = (uint)(((state >> 18) ^ state) >> 27); int num2 = (int)(state >> 59); return (num >> num2) | (num << (-num2 & 0x1F)); } public uint NextUInt(uint maxExclusive) { uint num = (uint)(0L - (long)maxExclusive) % maxExclusive; uint num2; do { num2 = NextUInt(); } while (num2 < num); return num2 % maxExclusive; } public uint NextUInt(uint minInclusive, uint maxExclusive) { if (maxExclusive <= minInclusive) { throw new ArgumentException(); } uint num = maxExclusive - minInclusive; uint num2 = (uint)(0L - (long)num) % num; uint num3; do { num3 = NextUInt(); } while (num3 < num2); return num3 % num + minInclusive; } public float NextFloat() { return (float)((double)NextUInt() * 2.3283064365386963E-10); } public float NextFloat(float maxInclusive) { if (maxInclusive <= 0f) { throw new ArgumentException("MaxInclusive must be larger than 0"); } return (float)((double)NextUInt() * 2.3283064365386963E-10) * maxInclusive; } public float NextFloat(float minInclusive, float maxInclusive) { if (maxInclusive < minInclusive) { throw new ArgumentException("Max must be larger than min"); } return (float)((double)NextUInt() * 2.3283064365386963E-10) * (maxInclusive - minInclusive) + minInclusive; } public double NextDouble() { return (double)NextUInt() * 2.3283064365386963E-10; } public double NextDouble(double maxInclusive) { if (maxInclusive <= 0.0) { throw new ArgumentException("Max must be larger than 0"); } return (double)NextUInt() * 2.3283064365386963E-10 * maxInclusive; } public double NextDouble(double minInclusive, double maxInclusive) { if (maxInclusive < minInclusive) { throw new ArgumentException("Max must be larger than min"); } return (double)NextUInt() * 2.3283064365386963E-10 * (maxInclusive - minInclusive) + minInclusive; } public bool NextBool() { uint num = NextUInt(); return num % 2 == 1; } public void SetStream(ulong sequence) { _increment = (sequence << 1) | 1; } protected void reseed(int seed) { Initialize((ulong)seed, 721347520444481703uL); } protected void Initialize(ulong seed, ulong initseq) { _state = 0uL; SetStream(initseq); NextUInt(); _state += seed; NextUInt(); } } } namespace GSSerializer { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class fsForwardAttribute : Attribute { public string MemberName; public fsForwardAttribute(string memberName) { MemberName = memberName; } } public class fsConverterRegistrar { public static AnimationCurve_DirectConverter Register_AnimationCurve_DirectConverter; public static Bounds_DirectConverter Register_Bounds_DirectConverter; public static Gradient_DirectConverter Register_Gradient_DirectConverter; public static GUIStyleState_DirectConverter Register_GUIStyleState_DirectConverter; public static GUIStyle_DirectConverter Register_GUIStyle_DirectConverter; public static Keyframe_DirectConverter Register_Keyframe_DirectConverter; public static LayerMask_DirectConverter Register_LayerMask_DirectConverter; public static RectOffset_DirectConverter Register_RectOffset_DirectConverter; public static Rect_DirectConverter Register_Rect_DirectConverter; public static List<Type> Converters; static fsConverterRegistrar() { Converters = new List<Type>(); FieldInfo[] declaredFields = typeof(fsConverterRegistrar).GetDeclaredFields(); foreach (FieldInfo fieldInfo in declaredFields) { if (fieldInfo.Name.StartsWith("Register_")) { Converters.Add(fieldInfo.FieldType); } } MethodInfo[] declaredMethods = typeof(fsConverterRegistrar).GetDeclaredMethods(); foreach (MethodInfo methodInfo in declaredMethods) { if (methodInfo.Name.StartsWith("Register_")) { methodInfo.Invoke(null, null); } } List<Type> list = new List<Type>(Converters); foreach (Type converter in Converters) { object obj = null; try { obj = Activator.CreateInstance(converter); } catch (Exception) { } if (obj is fsIAotConverter fsIAotConverter2) { fsMetaType currentModel = fsMetaType.Get(new fsConfig(), fsIAotConverter2.ModelType); if (!fsAotCompilationManager.IsAotModelUpToDate(currentModel, fsIAotConverter2)) { list.Remove(converter); } } } Converters = list; } } public class fsAotCompilationManager { public static HashSet<Type> AotCandidateTypes = new HashSet<Type>(); private static bool HasMember(fsAotVersionInfo versionInfo, fsAotVersionInfo.Member member) { fsAotVersionInfo.Member[] members = versionInfo.Members; foreach (fsAotVersionInfo.Member member2 in members) { if (member2 == member) { return true; } } return false; } public static bool IsAotModelUpToDate(fsMetaType currentModel, fsIAotConverter aotModel) { if (currentModel.IsDefaultConstructorPublic != aotModel.VersionInfo.IsConstructorPublic) { return false; } if (currentModel.Properties.Length != aotModel.VersionInfo.Members.Length) { return false; } fsMetaProperty[] properties = currentModel.Properties; foreach (fsMetaProperty property in properties) { if (!HasMember(aotModel.VersionInfo, new fsAotVersionInfo.Member(property))) { return false; } } return true; } public static string RunAotCompilationForType(fsConfig config, Type type) { fsMetaType fsMetaType2 = fsMetaType.Get(config, type); fsMetaType2.EmitAotData(throwException: true); return GenerateDirectConverterForTypeInCSharp(type, fsMetaType2.Properties, fsMetaType2.IsDefaultConstructorPublic); } private static string EmitVersionInfo(string prefix, Type type, fsMetaProperty[] members, bool isConstructorPublic) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("new fsAotVersionInfo {"); stringBuilder.AppendLine(prefix + " IsConstructorPublic = " + (isConstructorPublic ? "true" : "false") + ","); stringBuilder.AppendLine(prefix + " Members = new fsAotVersionInfo.Member[] {"); foreach (fsMetaProperty fsMetaProperty in members) { stringBuilder.AppendLine(prefix + " new fsAotVersionInfo.Member {"); stringBuilder.AppendLine(prefix + " MemberName = \"" + fsMetaProperty.MemberName + "\","); stringBuilder.AppendLine(prefix + " JsonName = \"" + fsMetaProperty.JsonName + "\","); stringBuilder.AppendLine(prefix + " StorageType = \"" + fsMetaProperty.StorageType.CSharpName(includeNamespace: true) + "\","); if (fsMetaProperty.OverrideConverterType != null) { stringBuilder.AppendLine(prefix + " OverrideConverterType = \"" + fsMetaProperty.OverrideConverterType.CSharpName(includeNamespace: true) + "\","); } stringBuilder.AppendLine(prefix + " },"); } stringBuilder.AppendLine(prefix + " }"); stringBuilder.Append(prefix + "}"); return stringBuilder.ToString(); } private static string GetConverterString(fsMetaProperty member) { if (member.OverrideConverterType == null) { return "null"; } return $"typeof({member.OverrideConverterType.CSharpName(includeNamespace: true)})"; } public static string GetQualifiedConverterNameForType(Type type) { return "FullSerializer.Speedup." + type.CSharpName(includeNamespace: true, ensureSafeDeclarationName: true) + "_DirectConverter"; } private static string GenerateDirectConverterForTypeInCSharp(Type type, fsMetaProperty[] members, bool isConstructorPublic) { StringBuilder stringBuilder = new StringBuilder(); string text = type.CSharpName(includeNamespace: true); string text2 = type.CSharpName(includeNamespace: true, ensureSafeDeclarationName: true); stringBuilder.AppendLine("using System;"); stringBuilder.AppendLine("using System.Collections.Generic;"); stringBuilder.AppendLine(); stringBuilder.AppendLine("namespace FullSerializer {"); stringBuilder.AppendLine(" partial class fsConverterRegistrar {"); stringBuilder.AppendLine(" public static Speedup." + text2 + "_DirectConverter Register_" + text2 + ";"); stringBuilder.AppendLine(" }"); stringBuilder.AppendLine("}"); stringBuilder.AppendLine(); stringBuilder.AppendLine("namespace FullSerializer.Speedup {"); stringBuilder.AppendLine(" public class " + text2 + "_DirectConverter : fsDirectConverter<" + text + ">, fsIAotConverter {"); stringBuilder.AppendLine(" private fsAotVersionInfo _versionInfo = " + EmitVersionInfo(" ", type, members, isConstructorPublic) + ";"); stringBuilder.AppendLine(" fsAotVersionInfo fsIAotConverter.VersionInfo { get { return _versionInfo; } }"); stringBuilder.AppendLine(); stringBuilder.AppendLine(" protected override fsResult DoSerialize(" + text + " model, Dictionary<string, fsData> serialized) {"); stringBuilder.AppendLine(" var result = fsResult.Success;"); stringBuilder.AppendLine(); foreach (fsMetaProperty fsMetaProperty in members) { stringBuilder.AppendLine(" result += SerializeMember(serialized, " + GetConverterString(fsMetaProperty) + ", \"" + fsMetaProperty.JsonName + "\", model." + fsMetaProperty.MemberName + ");"); } stringBuilder.AppendLine(); stringBuilder.AppendLine(" return result;"); stringBuilder.AppendLine(" }"); stringBuilder.AppendLine(); stringBuilder.AppendLine(" protected override fsResult DoDeserialize(Dictionary<string, fsData> data, ref " + text + " model) {"); stringBuilder.AppendLine(" var result = fsResult.Success;"); stringBuilder.AppendLine(); for (int j = 0; j < members.Length; j++) { fsMetaProperty fsMetaProperty2 = members[j]; stringBuilder.AppendLine(" var t" + j + " = model." + fsMetaProperty2.MemberName + ";"); stringBuilder.AppendLine(" result += DeserializeMember(data, " + GetConverterString(fsMetaProperty2) + ", \"" + fsMetaProperty2.JsonName + "\", out t" + j + ");"); stringBuilder.AppendLine(" model." + fsMetaProperty2.MemberName + " = t" + j + ";"); stringBuilder.AppendLine(); } stringBuilder.AppendLine(" return result;"); stringBuilder.AppendLine(" }"); stringBuilder.AppendLine(); stringBuilder.AppendLine(" public override object CreateInstance(fsData data, Type storageType) {"); if (isConstructorPublic) { stringBuilder.AppendLine(" return new " + text + "();"); } else { stringBuilder.AppendLine(" return Activator.CreateInstance(typeof(" + text + "), /*nonPublic:*/true);"); } stringBuilder.AppendLine(" }"); stringBuilder.AppendLine(" }"); stringBuilder.AppendLine("}"); return stringBuilder.ToString(); } } [CreateAssetMenu(menuName = "Full Serializer AOT Configuration")] public class fsAotConfiguration : ScriptableObject { public enum AotState { Default, Enabled, Disabled } [Serializable] public struct Entry { public AotState State; public string FullTypeName; public Entry(Type type) { FullTypeName = type.FullName; State = AotState.Default; } public Entry(Type type, AotState state) { FullTypeName = type.FullName; State = state; } } public List<Entry> aotTypes = new List<Entry>(); public string outputDirectory = "Assets/AotModels"; public bool TryFindEntry(Type type, out Entry result) { string fullName = type.FullName; foreach (Entry aotType in aotTypes) { if (aotType.FullTypeName == fullName) { result = aotType; return true; } } result = default(Entry); return false; } public void UpdateOrAddEntry(Entry entry) { for (int i = 0; i < aotTypes.Count; i++) { if (aotTypes[i].FullTypeName == entry.FullTypeName) { aotTypes[i] = entry; return; } } aotTypes.Add(entry); } } public struct fsAotVersionInfo { public struct Member { public string MemberName; public string JsonName; public string StorageType; public string OverrideConverterType; public Member(fsMetaProperty property) { MemberName = property.MemberName; JsonName = property.JsonName; StorageType = property.StorageType.CSharpName(includeNamespace: true); OverrideConverterType = null; if (property.OverrideConverterType != null) { OverrideConverterType = property.OverrideConverterType.CSharpName(); } } public override bool Equals(object obj) { if (!(obj is Member)) { return false; } return this == (Member)obj; } public override int GetHashCode() { return MemberName.GetHashCode() + 17 * JsonName.GetHashCode() + 17 * StorageType.GetHashCode() + ((!string.IsNullOrEmpty(OverrideConverterType)) ? (17 * OverrideConverterType.GetHashCode()) : 0); } public static bool operator ==(Member a, Member b) { return a.MemberName == b.MemberName && a.JsonName == b.JsonName && a.StorageType == b.StorageType && a.OverrideConverterType == b.OverrideConverterType; } public static bool operator !=(Member a, Member b) { return !(a == b); } } public bool IsConstructorPublic; public Member[] Members; } public abstract class fsBaseConverter { public fsSerializer Serializer; public virtual object CreateInstance(fsData data, Type storageType) { if (RequestCycleSupport(storageType)) { throw new InvalidOperationException("Please override CreateInstance for " + GetType().FullName + "; the object graph for " + storageType?.ToString() + " can contain potentially contain cycles, so separated instance creation is needed"); } return storageType; } public virtual bool RequestCycleSupport(Type storageType) { if (storageType == typeof(string)) { return false; } return storageType.Resolve().IsClass || storageType.Resolve().IsInterface; } public virtual bool RequestInheritanceSupport(Type storageType) { return !storageType.Resolve().IsSealed; } public abstract fsResult TrySerialize(object instance, out fsData serialized, Type storageType); public abstract fsResult TryDeserialize(fsData data, ref object instance, Type storageType); protected fsResult FailExpectedType(fsData data, params fsDataType[] types) { return fsResult.Fail(GetType().Name + " expected one of " + string.Join(", ", types.Select((fsDataType t) => t.ToString()).ToArray()) + " but got " + data.Type.ToString() + " in " + data); } protected fsResult CheckType(fsData data, fsDataType type) { if (data.Type != type) { return fsResult.Fail(GetType().Name + " expected " + type.ToString() + " but got " + data.Type.ToString() + " in " + data); } return fsResult.Success; } protected fsResult CheckKey(fsData data, string key, out fsData subitem) { return CheckKey(data.AsDictionary, key, out subitem); } protected fsResult CheckKey(Dictionary<string, fsData> data, string key, out fsData subitem) { if (!data.TryGetValue(key, out subitem)) { return fsResult.Fail(GetType().Name + " requires a <" + key + "> key in the data " + data); } return fsResult.Success; } protected fsResult SerializeMember<T>(Dictionary<string, fsData> data, Type overrideConverterType, string name, T value) { fsData data2; fsResult result = Serializer.TrySerialize(typeof(T), overrideConverterType, value, out data2); if (result.Succeeded) { data[name] = data2; } return result; } protected fsResult DeserializeMember<T>(Dictionary<string, fsData> data, Type overrideConverterType, string name, out T value) { if (!data.TryGetValue(name, out var value2)) { value = default(T); return fsResult.Fail("Unable to find member \"" + name + "\""); } object result = null; fsResult result2 = Serializer.TryDeserialize(value2, typeof(T), overrideConverterType, ref result); value = (T)result; return result2; } } public static class fsGlobalConfig { public static bool IsCaseSensitive = true; public static bool AllowInternalExceptions = true; public static string InternalFieldPrefix = "$"; } public class fsConfig { public bool CoerceStringsToNumbers = false; public string CustomDateTimeFormatString = null; public fsMemberSerialization DefaultMemberSerialization = fsMemberSerialization.Default; public bool EnablePropertySerialization = true; public Func<string, MemberInfo, string> GetJsonNameFromMemberName = (string name, MemberInfo info) => name; public Type[] IgnoreSerializeAttributes = new Type[2] { typeof(NonSerializedAttribute), typeof(fsIgnoreAttribute) }; public Type[] IgnoreSerializeTypeAttributes = new Type[1] { typeof(fsIgnoreAttribute) }; public bool Serialize64BitIntegerAsString = false; public Type[] SerializeAttributes = new Type[2] { typeof(SerializeField), typeof(fsPropertyAttribute) }; public bool SerializeEnumsAsInteger = false; public bool SerializeNonAutoProperties = false; public bool SerializeNonPublicSetProperties = true; } public sealed class fsContext { private readonly Dictionary<Type, object> _contextObjects = new Dictionary<Type, object>(); public void Reset() { _contextObjects.Clear(); } public void Set<T>(T obj) { _contextObjects[typeof(T)] = obj; } public bool Has<T>() { return _contextObjects.ContainsKey(typeof(T)); } public T Get<T>() { if (_contextObjects.TryGetValue(typeof(T), out var value)) { return (T)value; } throw new InvalidOperationException("There is no context object of type " + typeof(T)); } } public abstract class fsConverter : fsBaseConverter { public abstract bool CanProcess(Type type); } public enum fsDataType { Array, Object, Double, Int64, Boolean, String, Null } public sealed class fsData { private object _value; public static readonly fsData True = new fsData(boolean: true); public static readonly fsData False = new fsData(boolean: false); public static readonly fsData Null = new fsData(); public fsDataType Type { get { if (_value == null) { return fsDataType.Null; } if (_value is double) { return fsDataType.Double; } if (_value is long) { return fsDataType.Int64; } if (_value is bool) { return fsDataType.Boolean; } if (_value is string) { return fsDataType.String; } if (_value is Dictionary<string, fsData>) { return fsDataType.Object; } if (_value is List<fsData>) { return fsDataType.Array; } throw new InvalidOperationException("unknown JSON data type"); } } public bool IsNull => _value == null; public bool IsDouble => _value is double; public bool IsInt64 => _value is long; public bool IsBool => _value is bool; public bool IsString => _value is string; public bool IsDictionary => _value is Dictionary<string, fsData>; public bool IsList => _value is List<fsData>; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public double AsDouble => Cast<double>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public long AsInt64 => Cast<long>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool AsBool => Cast<bool>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string AsString => Cast<string>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Dictionary<string, fsData> AsDictionary => Cast<Dictionary<string, fsData>>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public List<fsData> AsList => Cast<List<fsData>>(); public override string ToString() { return fsJsonPrinter.CompressedJson(this); } public fsData() { _value = null; } public fsData(bool boolean) { _value = boolean; } public fsData(double f) { _value = f; } public fsData(long i) { _value = i; } public fsData(string str) { _value = str; } public fsData(Dictionary<string, fsData> dict) { _value = dict; } public fsData(List<fsData> list) { _value = list; } public static fsData CreateDictionary() { return new fsData(new Dictionary<string, fsData>(fsGlobalConfig.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase)); } public static fsData CreateList() { return new fsData(new List<fsData>()); } public static fsData CreateList(int capacity) { return new fsData(new List<fsData>(capacity)); } internal void BecomeDictionary() { _value = new Dictionary<string, fsData>(); } internal fsData Clone() { fsData fsData2 = new fsData(); fsData2._value = _value; return fsData2; } private T Cast<T>() { if (_value is T) { return (T)_value; } throw new InvalidCastException("Unable to cast <" + this?.ToString() + "> (with type = " + _value.GetType()?.ToString() + ") to type " + typeof(T)); } public override bool Equals(object obj) { return Equals(obj as fsData); } public bool Equals(fsData other) { if (other == null || Type != other.Type) { return false; } switch (Type) { case fsDataType.Null: return true; case fsDataType.Double: return AsDouble == other.AsDouble || Math.Abs(AsDouble - other.AsDouble) < double.Epsilon; case fsDataType.Int64: return AsInt64 == other.AsInt64; case fsDataType.Boolean: return AsBool == other.AsBool; case fsDataType.String: return AsString == other.AsString; case fsDataType.Array: { List<fsData> asList = AsList; List<fsData> asList2 = other.AsList; if (asList.Count != asList2.Count) { return false; } for (int i = 0; i < asList.Count; i++) { if (!asList[i].Equals(asList2[i])) { return false; } } return true; } case fsDataType.Object: { Dictionary<string, fsData> asDictionary = AsDictionary; Dictionary<string, fsData> asDictionary2 = other.AsDictionary; if (asDictionary.Count != asDictionary2.Count) { return false; } foreach (string key in asDictionary.Keys) { if (!asDictionary2.ContainsKey(key)) { return false; } if (!asDictionary[key].Equals(asDictionary2[key])) { return false; } } return true; } default: throw new Exception("Unknown data type"); } } public static bool operator ==(fsData a, fsData b) { if ((object)a == b) { return true; } if ((object)a == null || (object)b == null) { return false; } if (a.IsDouble && b.IsDouble) { return Math.Abs(a.AsDouble - b.AsDouble) < double.Epsilon; } return a.Equals(b); } public static bool operator !=(fsData a, fsData b) { return !(a == b); } public override int GetHashCode() { return _value.GetHashCode(); } } public abstract class fsDirectConverter : fsBaseConverter { public abstract Type ModelType { get; } } public abstract class fsDirectConverter<TModel> : fsDirectConverter { public override Type ModelType => typeof(TModel); public sealed override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) { Dictionary<string, fsData> dictionary = new Dictionary<string, fsData>(); fsResult result = DoSerialize((TModel)instance, dictionary); serialized = new fsData(dictionary); return result; } public sealed override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { fsResult success = fsResult.Success; fsResult fsResult2 = (success += CheckType(data, fsDataType.Object)); if (fsResult2.Failed) { return success; } TModel model = (TModel)instance; success += DoDeserialize(data.AsDictionary, ref model); instance = model; return success; } protected abstract fsResult DoSerialize(TModel model, Dictionary<string, fsData> serialized); protected abstract fsResult DoDeserialize(Dictionary<string, fsData> data, ref TModel model); } public sealed class fsMissingVersionConstructorException : Exception { public fsMissingVersionConstructorException(Type versionedType, Type constructorType) : base(versionedType?.ToString() + " is missing a constructor for previous model type " + constructorType) { } } public sealed class fsDuplicateVersionNameException : Exception { public fsDuplicateVersionNameException(Type typeA, Type typeB, string version) : base(typeA?.ToString() + " and " + typeB?.ToString() + " have the same version string (" + version + "); please change one of them.") { } } public interface fsIAotConverter { Type ModelType { get; } fsAotVersionInfo VersionInfo { get; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field)] public sealed class fsIgnoreAttribute : Attribute { } public interface fsISerializationCallbacks { void OnBeforeSerialize(Type storageType); void OnAfterSerialize(Type storageType, ref fsData data); void OnBeforeDeserialize(Type storageType, ref fsData data); void OnAfterDeserialize(Type storageType); } public class fsJsonParser { private readonly StringBuilder _cachedStringBuilder = new StringBuilder(256); private readonly string _input; private int _start; private fsJsonParser(string input) { _input = input; _start = 0; } private fsResult MakeFailure(string message) { int num = Math.Max(0, _start - 20); int length = Math.Min(50, _input.Length - num); string warning = "Error while parsing: " + message + "; context = <" + _input.Substring(num, length) + ">"; return fsResult.Fail(warning); } private bool TryMoveNext() { if (_start < _input.Length) { _start++; return true; } return false; } private bool HasValue() { return HasValue(0); } private bool HasValue(int offset) { return _start + offset >= 0 && _start + offset < _input.Length; } private char Character() { return Character(0); } private char Character(int offset) { return _input[_start + offset]; } private void SkipSpace() { while (HasValue()) { char c = Character(); if (char.IsWhiteSpace(c)) { TryMoveNext(); continue; } if (!HasValue(1) || Character(0) != '/') { break; } if (Character(1) == '/') { while (HasValue() && !Environment.NewLine.Contains(Character().ToString() ?? "")) { TryMoveNext(); } } else { if (Character(1) != '*') { continue; } TryMoveNext(); TryMoveNext(); while (HasValue(1)) { if (Character(0) == '*' && Character(1) == '/') { TryMoveNext(); TryMoveNext(); TryMoveNext(); break; } TryMoveNext(); } } } } private fsResult TryParseExact(string content) { for (int i = 0; i < content.Length; i++) { if (Character() != content[i]) { return MakeFailure("Expected " + content[i]); } if (!TryMoveNext()) { return MakeFailure("Unexpected end of content when parsing " + content); } } return fsResult.Success; } private fsResult TryParseTrue(out fsData data) { fsResult result = TryParseExact("true"); if (result.Succeeded) { data = new fsData(boolean: true); return fsResult.Success; } data = null; return result; } private fsResult TryParseFalse(out fsData data) { fsResult result = TryParseExact("false"); if (result.Succeeded) { data = new fsData(boolean: false); return fsResult.Success; } data = null; return result; } private fsResult TryParseNull(out fsData data) { fsResult result = TryParseExact("null"); if (result.Succeeded) { data = new fsData(); return fsResult.Success; } data = null; return result; } private bool IsSeparator(char c) { return char.IsWhiteSpace(c) || c == ',' || c == '}' || c == ']'; } private fsResult TryParseNumber(out fsData data) { int start = _start; while (TryMoveNext() && HasValue() && !IsSeparator(Character())) { } string text = _input.Substring(start, _start - start); if (text.Contains(".") || text.Contains("e") || text.Contains("E") || text == "Infinity" || text == "-Infinity" || text == "NaN") { if (!double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out var result)) { data = null; return MakeFailure("Bad double format with " + text); } data = new fsData(result); return fsResult.Success; } if (!long.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out var result2)) { data = null; return MakeFailure("Bad Int64 format with " + text); } data = new fsData(result2); return fsResult.Success; } private fsResult TryParseString(out string str) { _cachedStringBuilder.Length = 0; if (Character() != '"' || !TryMoveNext()) { str = string.Empty; return MakeFailure("Expected initial \" when parsing a string"); } while (HasValue() && Character() != '"') { char c = Character(); if (c == '\\') { char escaped; fsResult result = TryUnescapeChar(out escaped); if (result.Failed) { str = string.Empty; return result; } _cachedStringBuilder.Append(escaped); } else { _cachedStringBuilder.Append(c); if (!TryMoveNext()) { str = string.Empty; return MakeFailure("Unexpected end of input when reading a string"); } } } if (!HasValue() || Character() != '"' || !TryMoveNext()) { str = string.Empty; return MakeFailure("No closing \" when parsing a string"); } str = _cachedStringBuilder.ToString(); return fsResult.Success; } private fsResult TryParseArray(out fsData arr) { if (Character() != '[') { arr = null; return MakeFailure("Expected initial [ when parsing an array"); } if (!TryMoveNext()) { arr = null; return MakeFailure("Unexpected end of input when parsing an array"); } SkipSpace(); List<fsData> list = new List<fsData>(); while (HasValue() && Character() != ']') { fsData data; fsResult result = RunParse(out data); if (result.Failed) { arr = null; return result; } list.Add(data); SkipSpace(); if (HasValue() && Character() == ',') { if (!TryMoveNext()) { break; } SkipSpace(); } } if (!HasValue() || Character() != ']' || !TryMoveNext()) { arr = null; return MakeFailure("No closing ] for array"); } arr = new fsData(list); return fsResult.Success; } private fsResult TryParseObject(out fsData obj) { if (Character() != '{') { obj = null; return MakeFailure("Expected initial { when parsing an object"); } if (!TryMoveNext()) { obj = null; return MakeFailure("Unexpected end of input when parsing an object"); } SkipSpace(); Dictionary<string, fsData> dictionary = new Dictionary<string, fsData>(fsGlobalConfig.IsCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); while (HasValue() && Character() != '}') { SkipSpace(); fsResult result = TryParseString(out var str); if (result.Failed) { obj = null; return result; } SkipSpace(); if (!HasValue() || Character() != ':' || !TryMoveNext()) { obj = null; return MakeFailure("Expected : after key \"" + str + "\""); } SkipSpace(); result = RunParse(out var data); if (result.Failed) { obj = null; return result; } dictionary.Add(str, data); SkipSpace(); if (HasValue() && Character() == ',') { if (!TryMoveNext()) { break; } SkipSpace(); } } if (!HasValue() || Character() != '}' || !TryMoveNext()) { obj = null; return MakeFailure("No closing } for object"); } obj = new fsData(dictionary); return fsResult.Success; } private fsResult RunParse(out fsData data) { SkipSpace(); if (!HasValue()) { data = null; return MakeFailure("Unexpected end of input"); } switch (Character()) { case '+': case '-': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'I': case 'N': return TryParseNumber(out data); case '"': { string str; fsResult result = TryParseString(out str); if (result.Failed) { data = null; return result; } data = new fsData(str); return fsResult.Success; } case '[': return TryParseArray(out data); case '{': return TryParseObject(out data); case 't': return TryParseTrue(out data); case 'f': return TryParseFalse(out data); case 'n': return TryParseNull(out data); default: data = null; return MakeFailure("unable to parse; invalid token \"" + Character() + "\""); } } public static fsResult Parse(string input, out fsData data) { if (string.IsNullOrEmpty(input)) { data = null; return fsResult.Fail("No input"); } fsJsonParser fsJsonParser2 = new fsJsonParser(input); return fsJsonParser2.RunParse(out data); } public static fsData Parse(string input) { Parse(input, out var data).AssertSuccess(); return data; } private bool IsHex(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } private uint ParseSingleChar(char c1, uint multipliyer) { uint result = 0u; if (c1 >= '0' && c1 <= '9') { result = (uint)(c1 - 48) * multipliyer; } else if (c1 >= 'A' && c1 <= 'F') { result = (uint)(c1 - 65 + 10) * multipliyer; } else if (c1 >= 'a' && c1 <= 'f') { result = (uint)(c1 - 97 + 10) * multipliyer; } return result; } private uint ParseUnicode(char c1, char c2, char c3, char c4) { uint num = ParseSingleChar(c1, 4096u); uint num2 = ParseSingleChar(c2, 256u); uint num3 = ParseSingleChar(c3, 16u); uint num4 = ParseSingleChar(c4, 1u); return num + num2 + num3 + num