Decompiled source of AddressesCS2 v0.0.2
AddressesCS2.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using Belzont.AssemblyUtility; using Belzont.Interfaces; using Belzont.Serialization; using Belzont.Utils; using BepInEx; using BepInEx.Logging; using Colossal; using Colossal.Entities; using Colossal.IO.AssetDatabase; using Colossal.Localization; using Colossal.Logging; using Colossal.OdinSerializer.Utilities; using Colossal.Serialization.Entities; using Colossal.UI; using Game; using Game.Areas; using Game.Buildings; using Game.Citizens; using Game.Common; using Game.Companies; using Game.Modding; using Game.Net; using Game.Prefabs; using Game.Rendering; using Game.SceneFlow; using Game.Settings; using Game.Tools; using Game.UI; using Game.UI.Localization; using HarmonyLib; using Unity.Collections; using Unity.Entities; using Unity.Jobs; using Unity.Mathematics; 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.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: KlyteModCanonVersion("0.0.4.3", "0.0.2")] [assembly: AssemblyCompany("AddressesCS2")] [assembly: AssemblyConfiguration("Thunderstore")] [assembly: AssemblyFileVersion("0.0.2.65534")] [assembly: AssemblyInformationalVersion("0.0.2.65534")] [assembly: AssemblyProduct("AddressesCS2")] [assembly: AssemblyTitle("AddressesCS2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.2.65534")] [module: UnverifiableCode] namespace AddressesCS2 { public static class MyPluginInfo { public const string PLUGIN_GUID = "AddressesCS2"; public const string PLUGIN_NAME = "AddressesCS2"; public const string PLUGIN_VERSION = "0.0.2.65534"; } } namespace Belzont.AssemblyUtility { [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] internal sealed class KlyteModCanonVersionAttribute : Attribute { public string CanonVersion { get; } public string ThunderstoreVersion { get; } public KlyteModCanonVersionAttribute(string canonVersion, string thunderstore) { CanonVersion = canonVersion; ThunderstoreVersion = thunderstore; } } } namespace Belzont.Utils { public static class BridgeUtils { public static object[] GetAllLoadableClassesInAssemblyList(Type t, IEnumerable<Assembly> assemblies = null) { if (assemblies == null) { assemblies = AppDomain.CurrentDomain.GetAssemblies(); } return (from x in assemblies.SelectMany(delegate(Assembly s) { try { return s.GetExportedTypes(); } catch (ReflectionTypeLoadException ex2) { return ex2.Types; } catch (Exception arg) { LogUtils.DoWarnLog($"Error exporting types from assembly {s}\n{arg}"); return new Type[0]; } }).Where(delegate(Type p) { try { IEnumerable<string> enumerable = CollectionExtensions.AddItem<string>(from x in p.GetInterfaces() select x.Name, p.BaseType.Name); LogUtils.DoLog("srcs " + p.Name + " => " + string.Join("; ", enumerable)); return enumerable.Any((string x) => x == t.Name) && p.IsClass && !p.IsAbstract; } catch { return false; } }).Select(delegate(Type x) { try { LogUtils.DoLog("Trying to instantiate '{0}'", x.AssemblyQualifiedName); return x.GetConstructor(new Type[0]).Invoke(new object[0]); } catch (Exception ex) { LogUtils.DoLog("Failed instantiate '{0}': {1}", x.AssemblyQualifiedName, ex); return null; } }) where x != null select x).ToArray(); } public static T[] GetAllLoadableClassesInAppDomain<T>() where T : class { return GetAllLoadableClassesInAssemblyList(typeof(T)).Cast<T>().ToArray(); } public static T[] GetAllLoadableClassesByTypeName<T, U>(Func<U> destinationGenerator, Assembly targetAssembly = null) where T : class where U : T { string fullName = typeof(T).FullName; Type[] allInterfacesWithTypeName = GetAllInterfacesWithTypeName(fullName); LogUtils.DoLog("Classes with same name of '{0}' found: {1}", fullName, allInterfacesWithTypeName.Length); return (from x in allInterfacesWithTypeName.SelectMany(delegate(Type x) { object[] allLoadableClassesInAssemblyList = GetAllLoadableClassesInAssemblyList(x, new Assembly[1] { targetAssembly }); LogUtils.DoLog("Objects loaded: {0}", allLoadableClassesInAssemblyList.Length); return allLoadableClassesInAssemblyList; }) select TryConvertClass<T, U>(x, destinationGenerator) into x where x != null select x).ToArray(); } public static Type[] GetAllInterfacesWithTypeName(string typeName) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); return assemblies.SelectMany(delegate(Assembly s) { try { return s.GetExportedTypes(); } catch { return new Type[0]; } }).Where(delegate(Type p) { try { return p.FullName == typeName && p.IsInterface; } catch { return false; } }).ToArray(); } public static T TryConvertClass<T, U>(object srcValue, Func<U> destinationGenerator) where U : T { LogUtils.DoLog("Trying to convert {0} to class {1}", srcValue.GetType().FullName, typeof(T).FullName); if (srcValue.GetType().IsAssignableFrom(typeof(T))) { return (T)srcValue; } U val = destinationGenerator(); Type type = srcValue.GetType(); Type type2 = val.GetType(); PropertyInfo[] properties = typeof(T).GetProperties(RedirectorUtils.allFlags); foreach (PropertyInfo propertyInfo in properties) { LogUtils.DoLog("fieldOnItf: {0} {1}=>{2}", TypeExtensions.GetReturnType((MemberInfo)propertyInfo).FullName, typeof(T).FullName, propertyInfo.Name); PropertyInfo property = type.GetProperty(propertyInfo.Name, RedirectorUtils.allFlags); LogUtils.DoLog("fieldOnSrc: {0} {1}=>{2}", TypeExtensions.GetReturnType((MemberInfo)property).FullName, type.FullName, property.Name); PropertyInfo property2 = type2.GetProperty(propertyInfo.Name, RedirectorUtils.allFlags); LogUtils.DoLog("fieldOnDst: {0} {1}=>{2}", TypeExtensions.GetReturnType((MemberInfo)property2).FullName, type2.FullName, property2.Name); if ((object)property != null && property.PropertyType.IsAssignableFrom(property2.PropertyType)) { property2.SetValue(val, property.GetValue(srcValue)); } } return (T)(object)val; } } public static class ColorExtensions { public static string ToRGBA(this Color32 color) { //IL_000d: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) return $"{color.r:X2}{color.g:X2}{color.b:X2}{color.a:X2}"; } public static string ToRGB(this Color32 color, bool withHashtag = false) { //IL_001f: 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) //IL_003b: Unknown result type (might be due to invalid IL or missing references) return string.Format("{0}{1:X2}{2:X2}{3:X2}", withHashtag ? "#" : "", color.r, color.g, color.b); } public static string ToRGBA(this Color color) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Color32.op_Implicit(color).ToRGBA(); } public static string ToRGB(this Color color) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Color32.op_Implicit(color).ToRGB(); } public static Color SetBrightness(this Color color, float brightness) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) float num = default(float); float num2 = default(float); float num3 = default(float); Color.RGBToHSV(color, ref num, ref num2, ref num3); return Color.HSVToRGB(num, num2, brightness); } public static Color ClampSaturation(this Color color, float maxSaturation) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) float num = default(float); float num2 = default(float); float num3 = default(float); Color.RGBToHSV(color, ref num, ref num2, ref num3); return Color.HSVToRGB(num, Mathf.Min(num2, maxSaturation), num3); } public static Color MultiplyChannelsButAlpha(this Color color, Color other) { //IL_0000: 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_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0027: 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) return new Color(color.r * other.r, color.g * other.g, color.b * other.b, color.a); } public static Color32 FromRGBA(string rgba) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) long value = Convert.ToInt64(rgba, 16); return FromRGBA(value); } public static Color32 FromRGBA(long value) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) return new Color32((byte)((value & 0xFF000000u) >> 24), (byte)((value & 0xFF0000) >> 16), (byte)((value & 0xFF00) >> 8), (byte)(value & 0xFF)); } public static Color32 FromRGB(string rgb, bool withHashtag = false) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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) if (withHashtag) { string text = rgb; rgb = text.Substring(1, text.Length - 1); } int value = Convert.ToInt32(rgb, 16); return FromRGB(value); } public static Color32 FromRGB(int value) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) return new Color32((byte)((value & 0xFF0000) >> 16), (byte)((value & 0xFF00) >> 8), (byte)((uint)value & 0xFFu), byte.MaxValue); } public static Color ContrastColor(this Color color, bool grayAsWhite = false) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) if (color == default(Color)) { return Color.black; } float num = 0.299f * color.r + 0.587f * color.g + 0.114f * color.b; float num2 = ((!((double)num > 0.5)) ? (grayAsWhite ? 0.5f : 1f) : 0f); return new Color(num2, num2, num2, 1f); } } public class KFileUtils { public static readonly string BASE_FOLDER_PATH = Application.persistentDataPath + Path.DirectorySeparatorChar + "Klyte45Mods" + Path.DirectorySeparatorChar; public static FileInfo EnsureFolderCreation(string folderName) { if (File.Exists(folderName) && (File.GetAttributes(folderName) & FileAttributes.Directory) != FileAttributes.Directory) { File.Delete(folderName); } if (!Directory.Exists(folderName)) { Directory.CreateDirectory(folderName); } return new FileInfo(folderName); } public static bool IsFileCreated(string fileName) { return File.Exists(fileName); } public static string[] GetAllFilesEmbeddedAtFolder(string packageDirectory, string extension) { Assembly refAssemblyMod = KResourceLoader.RefAssemblyMod; string folderName = "Klyte." + packageDirectory; return (from r in refAssemblyMod.GetManifestResourceNames() where r.StartsWith(folderName) && r.EndsWith(extension) select r).Select(delegate(string r) { int num = folderName.Length + 1; return r.Substring(num, r.Length - num); }).ToArray(); } } public static class KResourceLoader { public static Assembly RefAssemblyMod => BasicIMod.Instance.GetType().Assembly; private static string NamespaceMod => BasicIMod.Instance.SafeName + "."; public static Assembly RefAssemblyBelzont => typeof(KResourceLoader).Assembly; public static byte[] LoadResourceDataMod(string name) { return LoadResourceData(NamespaceMod + name, RefAssemblyMod); } public static byte[] LoadResourceDataBelzont(string name) { return LoadResourceData("Belzont." + name, RefAssemblyBelzont); } private static byte[] LoadResourceData(string name, Assembly refAssembly) { UnmanagedMemoryStream unmanagedMemoryStream = (UnmanagedMemoryStream)refAssembly.GetManifestResourceStream(name); if (unmanagedMemoryStream == null) { LogUtils.DoLog("Could not find resource: " + name); return null; } BinaryReader binaryReader = new BinaryReader(unmanagedMemoryStream); return binaryReader.ReadBytes((int)unmanagedMemoryStream.Length); } public static string LoadResourceStringMod(string name) { return LoadResourceString(NamespaceMod + name, RefAssemblyMod); } public static string LoadResourceStringBelzont(string name) { return LoadResourceString("Belzont." + name, RefAssemblyBelzont); } private static string LoadResourceString(string name, Assembly refAssembly) { UnmanagedMemoryStream unmanagedMemoryStream = (UnmanagedMemoryStream)refAssembly.GetManifestResourceStream(name); if (unmanagedMemoryStream == null) { LogUtils.DoLog("Could not find resource: " + name); return null; } StreamReader streamReader = new StreamReader(unmanagedMemoryStream); return streamReader.ReadToEnd(); } public static IEnumerable<string> LoadResourceStringLinesMod(string name) { return LoadResourceStringLines(NamespaceMod + name, RefAssemblyMod); } public static IEnumerable<string> LoadResourceStringLinesBelzont(string name) { return LoadResourceStringLines("Belzont." + name, RefAssemblyBelzont); } private static IEnumerable<string> LoadResourceStringLines(string name, Assembly refAssembly) { using UnmanagedMemoryStream stream = (UnmanagedMemoryStream)refAssembly.GetManifestResourceStream(name); if (stream == null) { LogUtils.DoLog("Could not find resource: " + name); yield break; } using StreamReader reader = new StreamReader(stream); while (true) { string text; string line = (text = reader.ReadLine()); if (text == null) { break; } yield return line; } } } public static class LogUtils { private static ILog logOutput; private static ILog LogOutput { get { if (logOutput == null) { logOutput = LogManager.GetLogger("Mods_K45", true); logOutput.effectivenessLevel = Level.Info; } return logOutput; } } public static bool LogsEnabled { get; internal set; } internal static ManualLogSource Logger { get; set; } private static string LogLineStart(string level) { return (!LogsEnabled) ? "" : $"[{BasicIMod.Instance.Acronym,-4}] [v{BasicIMod.FullVersion,-16}] [{level,-8}] "; } public static void DoLog(string format, params object[] args) { try { if (!LogsEnabled) { ManualLogSource logger = Logger; if (logger != null) { logger.LogDebug((object)string.Format(LogLineStart("DEBUG") + format, args)); } } else if (BasicIMod.DebugMode) { Level effectivenessLevel = LogOutput.effectivenessLevel; LogOutput.effectivenessLevel = Level.Debug; LogOutput.Log(Level.Debug, string.Format(LogLineStart("DEBUG") + format, args), (Exception)null); LogOutput.effectivenessLevel = effectivenessLevel; } } catch (Exception e) { LogCaughtLogException(format, args, e); } } public static void DoWarnLog(string format, params object[] args) { try { if (!LogsEnabled) { ManualLogSource logger = Logger; if (logger != null) { logger.LogWarning((object)string.Format(LogLineStart("WARNING") + format, args)); } } else { LogOutput.Log(Level.Warn, string.Format(LogLineStart("WARNING") + format, args), (Exception)null); } } catch (Exception e) { LogCaughtLogException(format, args, e); } } private static void LogCaughtLogException(string format, object[] args, Exception e) { if (!LogsEnabled) { ManualLogSource logger = Logger; if (logger != null) { logger.LogFatal((object)string.Format(string.Format("{0} Erro ao fazer log: {{0}} (args = {{1}})\n{1}", LogLineStart("SEVERE"), e), format, (args == null) ? "[]" : string.Join(",", args.Select((object x) => (x != null) ? x.ToString() : "--NULL--").ToArray()))); } } else { LogOutput.Log(Level.Warn, string.Format(LogLineStart("SEVERE") + " Erro ao fazer log: {0} (args = {1})", format, (args == null) ? "[]" : string.Join(",", args.Select((object x) => (x != null) ? x.ToString() : "--NULL--").ToArray())), e); } } public static void DoInfoLog(string format, params object[] args) { try { if (!LogsEnabled) { ManualLogSource logger = Logger; if (logger != null) { logger.LogInfo((object)string.Format(LogLineStart("INFO") + format, args)); } } else { LogOutput.Log(Level.Info, string.Format(LogLineStart("INFO") + format, args), (Exception)null); } } catch (Exception e) { LogCaughtLogException(format, args, e); } } public static void DoErrorLog(string format, Exception e = null, params object[] args) { try { if (!LogsEnabled) { ManualLogSource logger = Logger; if (logger != null) { logger.LogError((object)string.Format(LogLineStart("ERROR") + format + $"\n{e}", args)); } } else { LogOutput.Log(Level.Error, string.Format(LogLineStart("ERROR") + format, args), e); } } catch (Exception e2) { if (e != null) { if (!LogsEnabled) { ManualLogSource logger2 = Logger; if (logger2 != null) { logger2.LogError((object)string.Format(LogLineStart("ERROR") + $"An exception has occurred.\n{e}")); } } else { LogOutput.Log(Level.Error, LogLineStart("ERROR") + "An exception has occurred.", e); } } LogCaughtLogException(format, args, e2); } } public static void PrintMethodIL(IEnumerable<CodeInstruction> inst, bool force = false) { if (force || BasicIMod.DebugMode) { int i = 0; DoInfoLog(LogLineStart("TRANSPILLED") + "\n\t" + string.Join("\n\t", inst.Select((CodeInstruction x) => $"{i++:D8} {x.opcode,-10} {ParseOperand(inst, x.operand)}").ToArray()), null); } } public static string GetLinesPointingToLabel(IEnumerable<CodeInstruction> inst, Label lbl) { int i = 0; return "\t" + string.Join("\n\t", (from x in inst select Tuple.New<CodeInstruction, string>(x, $"{i++:D8} {x.opcode.ToString().PadRight(10)} {ParseOperand(inst, x.operand)}") into x where x.First.operand is Label label && label == lbl select x.Second).ToArray()); } public static string ParseOperand(IEnumerable<CodeInstruction> instr, object operand) { if (operand == null) { return null; } if (operand is Label) { Label lbl = (Label)operand; if (true) { return "LBL: " + (from x in instr.Select((CodeInstruction x, int y) => Tuple.New<CodeInstruction, int>(x, y)) where x.First.labels.Contains(lbl) select $"{x.Second:D8} {x.First.opcode,-10} {ParseOperand(instr, x.First.operand)}").FirstOrDefault(); } } return operand.ToString() + $" (Type={operand.GetType()})"; } } public static class NameSystemExtensions { public class ValuableName { public readonly string __Type; public readonly string name; public readonly string nameId; public readonly string[] nameArgs; internal ValuableName(Name name) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: 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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected I4, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) NameType nameType = name.GetNameType(); NameType val = nameType; NameType val2 = val; switch ((int)val2) { default: __Type = "names.CustomName"; this.name = name.GetNameID(); nameId = null; nameArgs = null; break; case 1: __Type = "names.LocalizedName"; this.name = null; nameId = name.GetNameID(); nameArgs = null; break; case 2: __Type = "names.FormattedName"; this.name = null; nameId = name.GetNameID(); nameArgs = name.GetNameArgs(); break; } } } private static readonly FieldInfo NameTypeFI = typeof(Name).GetField("m_NameType", RedirectorUtils.allFlags); private static readonly FieldInfo NameIDFI = typeof(Name).GetField("m_NameID", RedirectorUtils.allFlags); private static readonly FieldInfo NameArgsFI = typeof(Name).GetField("m_NameArgs", RedirectorUtils.allFlags); public static NameType GetNameType(this Name name) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return (NameType)NameTypeFI.GetValue(name); } public static string GetNameID(this Name name) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return (string)NameIDFI.GetValue(name); } public static string[] GetNameArgs(this Name name) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return (string[])NameArgsFI.GetValue(name); } internal static ValuableName ToValueableName(this Name name) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return new ValuableName(name); } } public sealed class RedirectorUtils { public static readonly BindingFlags allFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.GetProperty; } public interface IRedirectableWorldless { } public interface IRedirectable { void DoPatches(World world); } public class Redirector : MonoBehaviour { private static Harmony m_harmony; private static readonly List<MethodInfo> m_patches = new List<MethodInfo>(); private static readonly List<Action> m_onUnpatchActions = new List<Action>(); private readonly List<MethodInfo> m_detourList = new List<MethodInfo>(); public static readonly MethodInfo semiPreventDefaultMI = ((Func<bool>)delegate { StackTrace stackTrace = new StackTrace(); StackFrame[] frames = stackTrace.GetFrames(); LogUtils.DoLog("SemiPreventDefault fullStackTrace: \r\n " + Environment.StackTrace); for (int i = 2; i < frames.Length; i++) { if (frames[i].GetMethod().DeclaringType.ToString().StartsWith("Klyte.")) { return false; } } return true; }).Method; private static readonly List<IRedirectable> worldDependantRedirectors = new List<IRedirectable>(); public static Harmony Harmony { get { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown if (m_harmony == null) { List<Type> subtypesRecursive = ReflectionUtils.GetSubtypesRecursive(typeof(BasicIMod), null); m_harmony = new Harmony("com.klyte.redirectors." + subtypesRecursive.First().Name); } return m_harmony; } } public static bool PreventDefault() { return false; } public void AddRedirect(MethodInfo oldMethod, MethodInfo newMethodPre, MethodInfo newMethodPost = null, MethodInfo transpiler = null) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) LogUtils.DoLog($"Adding patch! {oldMethod.DeclaringType} {oldMethod}"); object obj = m_detourList; obj = Harmony; obj = oldMethod; obj = (object)((!(newMethodPre != null)) ? ((HarmonyMethod)null) : new HarmonyMethod(newMethodPre)); obj = (object)((!(newMethodPost != null)) ? ((HarmonyMethod)null) : new HarmonyMethod(newMethodPost)); obj = (object)((!(transpiler != null)) ? ((HarmonyMethod)null) : new HarmonyMethod(transpiler)); ((List<MethodInfo>)obj).Add(((Harmony)obj).Patch((MethodBase)obj, (HarmonyMethod)obj, (HarmonyMethod)obj, (HarmonyMethod)obj, (HarmonyMethod)null, (HarmonyMethod)null)); m_patches.Add(oldMethod); } public void AddUnpatchAction(Action unpatchAction) { m_onUnpatchActions.Add(unpatchAction); } public static void UnpatchAll() { LogUtils.DoInfoLog("Unpatching all: " + Harmony.Id); foreach (MethodInfo patch in m_patches) { Harmony.Unpatch((MethodBase)patch, (HarmonyPatchType)0, Harmony.Id); } foreach (Action onUnpatchAction in m_onUnpatchActions) { onUnpatchAction?.Invoke(); } m_onUnpatchActions.Clear(); m_patches.Clear(); string text = "k45_Redirectors_" + Harmony.Id; Object.DestroyImmediate((Object)(object)GameObject.Find(text)); } public static void PatchAll() { //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Expected O, but got Unknown //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) LogUtils.DoInfoLog("Patching all: " + Harmony.Id); string text = "k45_Redirectors_" + Harmony.Id; GameObject val = (GameObject)(((object)GameObject.Find(text)) ?? ((object)new GameObject(text))); Object.DontDestroyOnLoad((Object)(object)val); Type typeFromHandle = typeof(IRedirectable); string basePathLocation = Path.GetDirectoryName(typeof(Redirector).Assembly.Location); List<Assembly> assembly = new List<Assembly>(AppDomain.CurrentDomain.GetAssemblies().Where(delegate(Assembly x) { try { return x.Location.StartsWith(basePathLocation); } catch { return false; } })); List<Type> interfaceImplementations = ReflectionUtils.GetInterfaceImplementations(typeFromHandle, assembly); LogUtils.DoLog($"Found Redirectors: {interfaceImplementations.Count}"); Type typeFromHandle2 = typeof(IRedirectableWorldless); List<Type> interfaceImplementations2 = ReflectionUtils.GetInterfaceImplementations(typeFromHandle2, assembly); LogUtils.DoLog($"Found Worldless Redirectors: {interfaceImplementations.Count}"); Application.logMessageReceived += new LogCallback(ErrorPatchingHandler); try { foreach (Type item in interfaceImplementations) { LogUtils.DoLog($"Redirector: {item}"); worldDependantRedirectors.Add(val.AddComponent(item) as IRedirectable); } foreach (Type item2 in interfaceImplementations2) { LogUtils.DoLog($"Redirector Worldless: {item2}"); val.AddComponent(item2); } } finally { Application.logMessageReceived -= new LogCallback(ErrorPatchingHandler); } } public static void OnWorldCreated(World world) { foreach (IRedirectable worldDependantRedirector in worldDependantRedirectors) { worldDependantRedirector.DoPatches(world); } } private static void ErrorPatchingHandler(string logString, string stackTrace, LogType type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 if ((int)type == 4) { LogUtils.DoErrorLog(logString + "\n" + stackTrace, null); } } public void EnableDebug() { Harmony.DEBUG = true; } public void DisableDebug() { Harmony.DEBUG = false; } } public static class ReflectionUtils { public static readonly BindingFlags allFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.GetProperty; private static readonly MethodInfo m_setFieldMethod = typeof(ReflectionUtils).GetMethod("SetField", BindingFlags.Static | BindingFlags.NonPublic); public static void GetPropertyDelegates<CL, PT>(string propertyName, out Action<CL, PT> setter, out Func<CL, PT> getter) { setter = (Action<CL, PT>)Delegate.CreateDelegate(typeof(Action<CL, PT>), null, typeof(CL).GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetSetMethod()); getter = (Func<CL, PT>)Delegate.CreateDelegate(typeof(Func<CL, PT>), null, typeof(CL).GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod()); } public static void GetStaticPropertyDelegates<CL, PT>(string propertyName, out Action<PT> setter, out Func<PT> getter) { setter = (Action<PT>)Delegate.CreateDelegate(typeof(Action<PT>), null, typeof(CL).GetProperty(propertyName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetSetMethod()); getter = (Func<PT>)Delegate.CreateDelegate(typeof(Func<PT>), null, typeof(CL).GetProperty(propertyName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetGetMethod()); } public static T RunPrivateMethod<T>(object o, string methodName, params object[] paramList) { if ((methodName ?? "") != string.Empty) { MethodInfo method = o.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method != null) { return (T)method.Invoke(o, paramList); } } return default(T); } public static T RunPrivateStaticMethod<T>(Type t, string methodName, params object[] paramList) { if ((methodName ?? "") != string.Empty) { MethodInfo method = t.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method != null) { return (T)method.Invoke(null, paramList); } } return default(T); } public static void GetFieldDelegates<TSource, TValue>(FieldInfo info, out Func<TSource, TValue> getter, out Action<TSource, TValue> setter) { getter = GetGetFieldDelegate<TSource, TValue>(info); setter = GetSetFieldDelegate<TSource, TValue>(info); } public static Func<TSource, TValue> GetGetFieldDelegate<TSource, TValue>(FieldInfo fieldInfo) { if (fieldInfo == null) { throw new ArgumentNullException("fieldInfo"); } Type declaringType = fieldInfo.DeclaringType; ParameterExpression parameterExpression = Expression.Parameter(typeof(TSource), "source"); Expression castOrConvertExpression = GetCastOrConvertExpression(parameterExpression, declaringType); MemberExpression expression = Expression.Field(castOrConvertExpression, fieldInfo); Expression castOrConvertExpression2 = GetCastOrConvertExpression(expression, typeof(TValue)); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<TSource, TValue>), castOrConvertExpression2, parameterExpression); return (Func<TSource, TValue>)lambdaExpression.Compile(); } public static Func<TSource, TValue> GetGetFieldDelegate<TSource, TValue>(string fieldName, Type fieldDeclaringType) { if (fieldName == null) { throw new ArgumentNullException("fieldName"); } if (fieldDeclaringType == null) { throw new ArgumentNullException("fieldDeclaringType"); } FieldInfo field = fieldDeclaringType.GetField(fieldName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); return GetGetFieldDelegate<TSource, TValue>(field); } public static Action<TSource, TValue> GetSetFieldDelegate<TSource, TValue>(FieldInfo fieldInfo) { if (fieldInfo == null) { throw new ArgumentNullException("fieldInfo"); } Type declaringType = fieldInfo.DeclaringType; ParameterExpression parameterExpression = Expression.Parameter(typeof(TSource), "source"); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(TValue), "value"); Expression castOrConvertExpression = GetCastOrConvertExpression(parameterExpression, declaringType); Expression expression = Expression.Field(castOrConvertExpression, fieldInfo); Expression castOrConvertExpression2 = GetCastOrConvertExpression(parameterExpression2, expression.Type); MethodInfo method = m_setFieldMethod.MakeGenericMethod(expression.Type); MethodCallExpression body = Expression.Call(null, method, expression, castOrConvertExpression2); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<TSource, TValue>), body, parameterExpression, parameterExpression2); return (Action<TSource, TValue>)lambdaExpression.Compile(); } public static Action<TSource, TValue> GetSetFieldDelegate<TSource, TValue>(string fieldName, Type fieldType, Type fieldDeclaringType) { if (fieldName == null) { throw new ArgumentNullException("fieldName"); } if (fieldType == null) { throw new ArgumentNullException("fieldType"); } if (fieldDeclaringType == null) { throw new ArgumentNullException("fieldDeclaringType"); } ParameterExpression parameterExpression = Expression.Parameter(typeof(TSource), "source"); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(TValue), "value"); Expression castOrConvertExpression = GetCastOrConvertExpression(parameterExpression, fieldDeclaringType); Expression castOrConvertExpression2 = GetCastOrConvertExpression(parameterExpression2, fieldType); MemberExpression arg = Expression.Field(castOrConvertExpression, fieldName); MethodInfo method = m_setFieldMethod.MakeGenericMethod(fieldType); MethodCallExpression body = Expression.Call(null, method, arg, castOrConvertExpression2); LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<TSource, TValue>), body, parameterExpression, parameterExpression2); return (Action<TSource, TValue>)lambdaExpression.Compile(); } private static Expression GetCastOrConvertExpression(Expression expression, Type targetType) { Type type = expression.Type; if (targetType.IsAssignableFrom(type)) { return expression; } if (targetType.IsValueType && !IsNullableType(targetType)) { return Expression.Convert(expression, targetType); } return Expression.TypeAs(expression, targetType); } public static T GetPrivateField<T>(object prefabAI, string v) { return (T)prefabAI.GetType().GetField(v, allFlags).GetValue(prefabAI); } public static object GetPrivateStaticField(string v, Type type) { return type.GetField(v, allFlags).GetValue(null); } public static void SetField<TValue>(ref TValue field, TValue newValue) { field = newValue; } public static Delegate GetMethodDelegate(string propertyName, Type targetType, Type actionType) { return GetMethodDelegate(targetType.GetMethod(propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic), actionType); } public static Delegate GetMethodDelegate(MethodInfo method, Type actionType) { return Delegate.CreateDelegate(actionType, null, method); } public static FieldInfo GetEventField(Type type, string eventName) { FieldInfo fieldInfo = null; while (type != null) { fieldInfo = type.GetField(eventName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); if (fieldInfo != null && (fieldInfo.FieldType == typeof(MulticastDelegate) || fieldInfo.FieldType.IsSubclassOf(typeof(MulticastDelegate)))) { break; } fieldInfo = type.GetField("EVENT_" + eventName.ToUpper(), BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); if (fieldInfo != null) { break; } type = type.BaseType; } return fieldInfo; } public static bool IsNullableType(Type type) { if (type == null) { throw new ArgumentNullException("type"); } bool result = false; if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { result = true; } return result; } public static bool HasField(object o, string fieldName) { FieldInfo[] fields = o.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { if (fieldInfo.Name == fieldName) { return true; } } return false; } public static List<Type> GetSubtypesRecursive(Type typeTarg, Type refType) { if (BasicIMod.DebugMode) { LogUtils.DoLog($"typeTarg = {typeTarg} | IsGenType={typeTarg.IsGenericType} "); } IEnumerable<Type> enumerable = from t in (from x in AppDomain.CurrentDomain.GetAssemblies() where refType == null || x == refType.Assembly select x)?.SelectMany(delegate(Assembly x) { try { return x?.GetTypes(); } catch { return new Type[0]; } }) let y = t.BaseType where t.IsClass && y != null && ((!typeTarg.IsGenericType && y == typeTarg) || (y.IsGenericType && y.GetGenericTypeDefinition() == typeTarg)) select t; List<Type> list = new List<Type>(); if (BasicIMod.DebugMode) { LogUtils.DoLog("classes:\r\n\t " + string.Join("\r\n\t", enumerable.Select((Type x) => x.ToString()).ToArray()) + " "); } foreach (Type item in enumerable) { if (!item.IsSealed) { list.AddRange(GetSubtypesRecursive(item, item)); } if (!item.IsAbstract) { list.Add(item); } } return list.Distinct().ToList(); } public static List<Type> GetInterfaceImplementations(Type interfaceType, IEnumerable<Assembly> assembly = null) { if (BasicIMod.DebugMode) { LogUtils.DoLog($"interfaceType = {interfaceType}\nFrom:{Environment.StackTrace}"); } if (assembly == null) { throw new NotSupportedException("Aguardando ModsMan Impl"); } IEnumerable<Type> source = from t in assembly.SelectMany(delegate(Assembly x) { try { return x?.GetTypes(); } catch { return new Type[0]; } }) let y = t.GetInterfaces() where t.IsClass && !t.IsAbstract && (y.Contains(interfaceType) || interfaceType.IsAssignableFrom(t)) select t; LogUtils.DoLog("classes:\r\n\t " + string.Join("\r\n\t", source.Select((Type x) => x.ToString()).ToArray()) + " "); return source.ToList(); } public static List<Type> GetStructForInterfaceImplementations(Type interfaceType, IEnumerable<Assembly> assembly = null) { if (BasicIMod.DebugMode) { LogUtils.DoLog($"interfaceType = {interfaceType}\nFrom:{Environment.StackTrace}"); } if (assembly == null) { throw new NotSupportedException("Aguardando ModsMan Impl"); } IEnumerable<Type> source = from t in assembly.SelectMany(delegate(Assembly x) { try { return x?.GetTypes(); } catch { return new Type[0]; } }) let y = t.GetInterfaces() where t.IsValueType && (y.Contains(interfaceType) || interfaceType.IsAssignableFrom(t)) select t; LogUtils.DoLog("classes:\r\n\t " + string.Join("\r\n\t", source.Select((Type x) => x.ToString()).ToArray()) + " "); return source.ToList(); } public static Type GetImplementationForGenericType(Type typeOr, params Type[] typeArgs) { Type typeTarg = typeOr.MakeGenericType(typeArgs); IEnumerable<Type> source = from t in Assembly.GetAssembly(typeOr).GetTypes() where t.IsClass && !t.IsAbstract && typeTarg.IsAssignableFrom(t) && !t.IsGenericType select t; if (source.Count() != 1) { throw new Exception(string.Format("Defininções inválidas para [{0}] no tipo genérico {1}", string.Join(", ", typeArgs.Select((Type x) => x.ToString()).ToArray()), typeOr)); } return source.First(); } public static bool CanMakeGenericTypeVia(Type openConstructedType, Type closedConstructedType) { if (openConstructedType == null) { throw new ArgumentNullException("openConstructedType"); } if (closedConstructedType == null) { throw new ArgumentNullException("closedConstructedType"); } if (openConstructedType.IsGenericParameter) { GenericParameterAttributes genericParameterAttributes = openConstructedType.GenericParameterAttributes; if (genericParameterAttributes != 0) { if ((genericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0 && !closedConstructedType.IsValueType) { return false; } if ((genericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0 && closedConstructedType.IsValueType) { return false; } if ((genericParameterAttributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0 && closedConstructedType.GetConstructor(Type.EmptyTypes) == null) { return false; } } Type[] genericParameterConstraints = openConstructedType.GetGenericParameterConstraints(); foreach (Type type in genericParameterConstraints) { if (type.IsGenericType != closedConstructedType.BaseType.IsGenericType) { return false; } if (type.IsGenericType) { if (closedConstructedType.BaseType.GetGenericTypeDefinition() != type.GetGenericTypeDefinition()) { return false; } } else if (!type.IsAssignableFrom(closedConstructedType)) { return false; } } return true; } if (openConstructedType.ContainsGenericParameters) { if (openConstructedType.IsGenericType) { Type genericTypeDefinition = openConstructedType.GetGenericTypeDefinition(); Type[] genericArguments = openConstructedType.GetGenericArguments(); List<Type> list = new List<Type> { closedConstructedType }; if (closedConstructedType.BaseType != null) { list.Add(closedConstructedType.BaseType); } list.AddRange(closedConstructedType.GetInterfaces()); foreach (Type item in list) { if (!item.IsGenericType || !(item.GetGenericTypeDefinition() == genericTypeDefinition)) { continue; } Type[] genericArguments2 = item.GetGenericArguments(); for (int j = 0; j < genericArguments.Length; j++) { if (!CanMakeGenericTypeVia(genericArguments[j], genericArguments2[j])) { return false; } } return true; } return false; } if (openConstructedType.IsArray) { if (!closedConstructedType.IsArray || closedConstructedType.GetArrayRank() != openConstructedType.GetArrayRank()) { return false; } Type elementType = openConstructedType.GetElementType(); Type elementType2 = closedConstructedType.GetElementType(); return CanMakeGenericTypeVia(elementType, elementType2); } throw new NotImplementedException("Open-constructed type contains generic parameters, but is neither an array nor a generic type."); } return openConstructedType.IsAssignableFrom(closedConstructedType); } public static bool IsAssignableToGenericType(Type givenType, Type genericType) { Type[] interfaces = givenType.GetInterfaces(); Type[] array = interfaces; foreach (Type type in array) { if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) { return true; } } if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType) { return true; } Type baseType = givenType.BaseType; if (baseType == null) { return false; } return IsAssignableToGenericType(baseType, genericType); } } [XmlRoot("SimpleEnumerableList")] public class SimpleEnumerableList<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable where TKey : Enum { public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.IsEmptyElement) { reader.Read(); return; } XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValueContainer<TKey, TValue>), ""); LogUtils.DoLog($"reader = {reader}; empty = {reader.IsEmptyElement}"); reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType != XmlNodeType.Element) { reader.Read(); continue; } ValueContainer<TKey, TValue> valueContainer = (ValueContainer<TKey, TValue>)xmlSerializer.Deserialize(reader); if (valueContainer.Index != null) { Add(valueContainer.Index, valueContainer.Value); } } reader.ReadEndElement(); } public void WriteXml(XmlWriter writer) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(ValueContainer<TKey, TValue>), ""); XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces(); xmlSerializerNamespaces.Add("", ""); foreach (TKey key in base.Keys) { TValue value = base[key]; xmlSerializer.Serialize(writer, new ValueContainer<TKey, TValue> { Index = key, Value = value }, xmlSerializerNamespaces); } } } [XmlRoot("ValueContainer")] public class ValueContainer<TKey, TValue> : IEnumerableIndex<TKey> where TKey : Enum { [XmlIgnore] public TKey Index { get; set; } [XmlAttribute("Index")] public string EnumValue { get { return Index.ToString(); } set { TKey index; try { index = (TKey)Enum.Parse(typeof(TKey), value); } catch { index = (TKey)Enum.ToObject(typeof(TKey), int.TryParse(value, out var result) ? result : 0); } Index = index; } } [XmlElement] public TValue Value { get; set; } } [XmlRoot("SimpleXmlDictionary")] public class SimpleXmlDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable where TKey : class where TValue : class { public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.IsEmptyElement) { reader.Read(); return; } XmlSerializer xmlSerializer = new XmlSerializer(typeof(EntryStructValueContainer<TKey, TValue>), ""); reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) { if (reader.NodeType != XmlNodeType.Element) { reader.Read(); continue; } EntryStructValueContainer<TKey, TValue> entryStructValueContainer = (EntryStructValueContainer<TKey, TValue>)xmlSerializer.Deserialize(reader); if (entryStructValueContainer.Value is IKeyGetter<TKey> keyGetter) { entryStructValueContainer.Id = keyGetter.GetKeyString() ?? entryStructValueContainer.Id; } if (entryStructValueContainer.Id != null) { Add(entryStructValueContainer.Id, entryStructValueContainer.Value ?? null); } } reader.ReadEndElement(); } public void WriteXml(XmlWriter writer) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(EntryStructValueContainer<TKey, TValue>), ""); XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces(); xmlSerializerNamespaces.Add("", ""); foreach (TKey key in base.Keys) { TValue value = base[key]; xmlSerializer.Serialize(writer, new EntryStructValueContainer<TKey, TValue> { Id = key, Value = value }, xmlSerializerNamespaces); } } } [XmlRoot("Entry")] public class EntryStructValueContainer<TKey, TValue> where TKey : class where TValue : class { [XmlAttribute("key")] public TKey Id { get; set; } [XmlElement] public TValue Value { get; set; } } public interface IKeyGetter<TKey> { TKey GetKeyString(); } public class Tuple<T1, T2, T3, T4, T5> : Tuple<T1, T2, T3, T4> { public T5 Fifth { get; protected set; } public Tuple(ref T1 first, ref T2 second, ref T3 third, ref T4 fourth, ref T5 fifth) : base(ref first, ref second, ref third, ref fourth) { Fifth = fifth; } } public class Tuple<T1, T2, T3, T4> : Tuple<T1, T2, T3> { public T4 Fourth { get; protected set; } public Tuple(ref T1 first, ref T2 second, ref T3 third, ref T4 fourth) : base(ref first, ref second, ref third) { Fourth = fourth; } } public class Tuple<T1, T2, T3> : Tuple<T1, T2> { public T3 Third { get; protected set; } public Tuple(ref T1 first, ref T2 second, ref T3 third) : base(ref first, ref second) { Third = third; } } public class Tuple<T1, T2> { public T1 First { get; protected set; } public T2 Second { get; protected set; } public Tuple(ref T1 first, ref T2 second) { First = first; Second = second; } } public class TupleRef<T1, T2, T3, T4, T5> : TupleRef<T1, T2, T3, T4> { private T5 m_fifth; public ref T5 Fifth => ref m_fifth; public TupleRef(ref T1 first, ref T2 second, ref T3 third, ref T4 fourth, ref T5 fifth) : base(ref first, ref second, ref third, ref fourth) { m_fifth = fifth; } } public class TupleRef<T1, T2, T3, T4> : TupleRef<T1, T2, T3> { private T4 m_fourth; public ref T4 Fourth => ref m_fourth; public TupleRef(ref T1 first, ref T2 second, ref T3 third, ref T4 fourth) : base(ref first, ref second, ref third) { m_fourth = fourth; } } public class TupleRef<T1, T2, T3> : TupleRef<T1, T2> { private T3 m_third; public ref T3 Third => ref m_third; public TupleRef(ref T1 first, ref T2 second, ref T3 third) : base(ref first, ref second) { m_third = third; } } public class TupleRef<T1, T2> { private T1 m_first; private T2 m_second; public ref T1 First => ref m_first; public ref T2 Second => ref m_second; public TupleRef(ref T1 first, ref T2 second) { m_first = first; m_second = second; } } public static class Tuple { public static Tuple<T1, T2, T3, T4, T5> New<T1, T2, T3, T4, T5>(T1 first, T2 second, T3 third, T4 fourth, T5 fifth) { return new Tuple<T1, T2, T3, T4, T5>(ref first, ref second, ref third, ref fourth, ref fifth); } public static Tuple<T1, T2, T3, T4> New<T1, T2, T3, T4>(T1 first, T2 second, T3 third, T4 fourth) { return new Tuple<T1, T2, T3, T4>(ref first, ref second, ref third, ref fourth); } public static Tuple<T1, T2, T3> New<T1, T2, T3>(T1 first, T2 second, T3 third) { return new Tuple<T1, T2, T3>(ref first, ref second, ref third); } public static Tuple<T1, T2> New<T1, T2>(T1 first, T2 second) { return new Tuple<T1, T2>(ref first, ref second); } public static TupleRef<T1, T2, T3, T4, T5> NewRef<T1, T2, T3, T4, T5>(T1 first, T2 second, T3 third, T4 fourth, T5 fifth) { return new TupleRef<T1, T2, T3, T4, T5>(ref first, ref second, ref third, ref fourth, ref fifth); } public static TupleRef<T1, T2, T3, T4> NewRef<T1, T2, T3, T4>(T1 first, T2 second, T3 third, T4 fourth) { return new TupleRef<T1, T2, T3, T4>(ref first, ref second, ref third, ref fourth); } public static TupleRef<T1, T2, T3> NewRef<T1, T2, T3>(ref T1 first, ref T2 second, ref T3 third) { return new TupleRef<T1, T2, T3>(ref first, ref second, ref third); } public static TupleRef<T1, T2> NewRef<T1, T2>(ref T1 first, ref T2 second) { return new TupleRef<T1, T2>(ref first, ref second); } } public class Wrapper<T> { public T Value { get; set; } public Wrapper(T value) { Value = value; } public Wrapper() { } } public class XmlUtils { public class ListWrapper<T> { [XmlElement("item")] public List<T> listVal = new List<T>(); } public static T CloneViaXml<T>(T input) { return DefaultXmlDeserialize<T>(DefaultXmlSerialize(input)); } public static U TransformViaXml<T, U>(T input) { return DefaultXmlDeserialize<U>(DefaultXmlSerialize(input)); } public static T DefaultXmlDeserialize<T>(string s, Action<string, Exception> OnException = null) { XmlSerializer xmlser = new XmlSerializer(typeof(T)); return DefaultXmlDeserializeImpl<T>(s, xmlser, OnException); } public static object DefaultXmlDeserialize(Type t, string s, Action<string, Exception> OnException = null) { XmlSerializer xmlser = new XmlSerializer(t); return DefaultXmlDeserializeImpl<object>(s, xmlser, OnException); } private static T DefaultXmlDeserializeImpl<T>(string s, XmlSerializer xmlser, Action<string, Exception> OnException = null) { using TextReader input = new StringReader(s); using XmlReader xmlReader = XmlReader.Create(input); try { if (xmlser.CanDeserialize(xmlReader)) { return (T)xmlser.Deserialize(xmlReader); } LogUtils.DoErrorLog($"CAN'T DESERIALIZE {typeof(T)}!\nText : {s}", null); OnException?.Invoke(s, null); } catch (Exception ex) { LogUtils.DoErrorLog($"CAN'T DESERIALIZE {typeof(T)}!\nText : {s}\n{ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}", null); OnException?.Invoke(s, ex); throw ex; } return default(T); } public static string DefaultXmlSerialize<T>(T targetObj, bool indent = true) { XmlSerializer xmlSerializer = new XmlSerializer(targetObj?.GetType() ?? typeof(T)); XmlWriterSettings settings = new XmlWriterSettings { Indent = indent, OmitXmlDeclaration = true }; using StringWriter stringWriter = new StringWriter(); using XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings); XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces(); xmlSerializerNamespaces.Add("", ""); xmlSerializer.Serialize(xmlWriter, targetObj, xmlSerializerNamespaces); return stringWriter.ToString(); } } } namespace Belzont.Serialization { internal struct BelzontDeserializeJob<TReader, B> : IJob where TReader : struct, IReader where B : ComponentSystemBase, IBelzontSerializableSingleton<B>, new() { public int m_WorldIndex; public EntityReaderData m_ReaderData; public void Execute() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) try { TReader reader = ((EntityReaderData)(ref m_ReaderData)).GetReader<TReader>(); World.All[m_WorldIndex].GetExistingSystemManaged<B>().Deserialize(reader); LogUtils.DoLog($"Deserialized {typeof(B)}"); } catch (Exception arg) { LogUtils.DoWarnLog($"Error loading deserialization for {typeof(B)}!\n{arg}"); } } } internal struct BelzontSerializeJob<TWriter, B> : IJob where TWriter : struct, IWriter where B : ComponentSystemBase, IBelzontSerializableSingleton<B>, new() { public int m_WorldIndex; public EntityWriterData m_WriterData; public void Execute() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) TWriter writer = ((EntityWriterData)(ref m_WriterData)).GetWriter<TWriter>(); World.All[m_WorldIndex].GetExistingSystemManaged<B>().Serialize(writer); LogUtils.DoLog($"Serialized {typeof(B)}"); } } internal interface IBelzontSerializableSingleton<B> : IJobSerializable where B : ComponentSystemBase, IBelzontSerializableSingleton<B>, new() { World World { get; } internal void Serialize<TWriter>(TWriter writer) where TWriter : IWriter; internal void Deserialize<TReader>(TReader reader) where TReader : IReader; JobHandle IJobSerializable.Serialize<TWriter>(EntityWriterData writerData, JobHandle inputDeps) { //IL_000b: 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) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) BelzontSerializeJob<TWriter, B> belzontSerializeJob = default(BelzontSerializeJob<TWriter, B>); belzontSerializeJob.m_WriterData = writerData; belzontSerializeJob.m_WorldIndex = -1; for (int i = 0; i < World.All.Count; i++) { if (World.All[i] == World) { belzontSerializeJob.m_WorldIndex = i; break; } } return IJobExtensions.Schedule<BelzontSerializeJob<TWriter, B>>(belzontSerializeJob, inputDeps); } JobHandle IJobSerializable.Deserialize<TReader>(EntityReaderData readerData, JobHandle inputDeps) { //IL_000b: 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) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) BelzontDeserializeJob<TReader, B> belzontDeserializeJob = default(BelzontDeserializeJob<TReader, B>); belzontDeserializeJob.m_ReaderData = readerData; belzontDeserializeJob.m_WorldIndex = -1; for (int i = 0; i < World.All.Count; i++) { if (World.All[i] == World) { belzontDeserializeJob.m_WorldIndex = i; break; } } inputDeps = IJobExtensions.Schedule<BelzontDeserializeJob<TReader, B>>(belzontDeserializeJob, inputDeps); return inputDeps; } } } namespace Belzont.Thunderstore { public class ModHooksRedirects : Redirector, IRedirectableWorldless { private static List<BasicIMod> basicMods = new List<BasicIMod>(); private static FieldInfo updateSystemField = typeof(GameManager).GetField("m_UpdateSystem", RedirectorUtils.allFlags); public void Awake() { AddRedirect(typeof(GameManager).GetMethod("CreateSystems", RedirectorUtils.allFlags), ((object)this).GetType().GetMethod("LoadMods", RedirectorUtils.allFlags), ((object)this).GetType().GetMethod("OnCreateWorld", RedirectorUtils.allFlags)); } private static void LoadMods() { List<Type> subtypesRecursive = ReflectionUtils.GetSubtypesRecursive(typeof(BasicIMod), null); foreach (Type item in subtypesRecursive) { BasicIMod basicIMod = item.GetConstructor(new Type[0]).Invoke(new object[0]) as BasicIMod; basicIMod.OnLoad(); basicMods.Add(basicIMod); } } private static void OnCreateWorld(GameManager __instance) { object? value = updateSystemField.GetValue(__instance); UpdateSystem updateSystem = (UpdateSystem)((value is UpdateSystem) ? value : null); foreach (BasicIMod basicMod in basicMods) { basicMod.OnCreateWorld(updateSystem); } } } } namespace Belzont.Interfaces { public interface IBelzontBindable { void SetupCaller(Action<string, object[]> eventCaller); void SetupEventBinder(Action<string, Delegate> eventCaller); void SetupCallBinder(Action<string, Delegate> eventCaller); } public abstract class BasicIMod { private class ModGenI18n : IDictionarySource { private BasicModData modData; public ModGenI18n(BasicModData data) { modData = data; } public IEnumerable<KeyValuePair<string, string>> ReadEntries(IList<IDictionaryEntryError> errors, Dictionary<string, int> indexCounts) { string[] array = Instance.GeneralName.Split(" ("); int length = array[1].Replace(".", "").Length; while (array[0].Length > 26 - length) { string[] array2 = array[0].Split(" "); if (!array2.Any((string x) => x.Length > 2)) { break; } int num = -1; int num2 = 2; for (int i = 0; i < array2.Length; i++) { if (array2[i].Length > num2) { num = i; num2 = array2[i].Length; } } if (num < 0) { break; } array2[num] = array2[num][0] + "."; array[0] = string.Join(" ", array2); } return new Dictionary<string, string> { [((ModSetting)modData).GetSettingsLocaleID()] = array[0] + " (" + array[1], [((ModSetting)modData).GetOptionTabLocaleID("About")] = "About", [PrepareFieldName(((ModSetting)modData).GetOptionLabelLocaleID("DebugMode"))] = "Debug Mode", [PrepareFieldName(((ModSetting)modData).GetOptionDescLocaleID("DebugMode"))] = "Turns on the log debugging for this mod", [PrepareFieldName(((ModSetting)modData).GetOptionLabelLocaleID("Version"))] = "Mod Version", [PrepareFieldName(((ModSetting)modData).GetOptionDescLocaleID("Version"))] = "The current mod version.\n\nIf version ends with 'B', it's a version compiled for BepInEx framework.", [PrepareFieldName(((ModSetting)modData).GetOptionLabelLocaleID("CanonVersion"))] = "Canonic Mod Version", [PrepareFieldName(((ModSetting)modData).GetOptionDescLocaleID("CanonVersion"))] = "The global version of this mod, used as main version reference.\n\nIf the first digit is '0', means this is a pre-release and experimental version.\n\nThe 4th digit being higher than 1000 indicates beta version.", [PrepareFieldName(((ModSetting)modData).GetOptionLabelLocaleID("ThunderstoreVersion"))] = "Thunderstore Version", [PrepareFieldName(((ModSetting)modData).GetOptionDescLocaleID("ThunderstoreVersion"))] = "The equivalent version of this mod registered at the Thunderstore" }; string PrepareFieldName(string f) { return f.Replace(((object)modData).GetType().Name, "BasicModData"); } } public void Unload() { } } private static ulong m_modId; private static string m_rootFolder; private const string kVersionSuffix = "B"; private static string m_modInstallFolder; protected UpdateSystem UpdateSystem { get; set; } public static string CurrentSaveVersion { get; } public abstract string SimpleName { get; } public abstract string SafeName { get; } public abstract string Acronym { get; } public string IconName { get; } = "ModIcon"; public string GitHubRepoPath { get; } = ""; public string[] AssetExtraDirectoryNames { get; } = new string[0]; public string[] AssetExtraFileNames { get; } = new string[0]; public virtual string ModRootFolder => KFileUtils.BASE_FOLDER_PATH + SafeName; public abstract string Description { get; } public static BasicIMod Instance { get; private set; } public static BasicModData ModData { get; protected set; } public static bool DebugMode => ModData?.DebugMode ?? true; public static ulong ModId { get { if (m_modId == 0) { m_modId = ulong.MaxValue; } return m_modId; } } public static string ModSettingsRootFolder { get { if (m_rootFolder == null) { m_rootFolder = Instance.ModRootFolder; } return m_rootFolder; } } public static string ModInstallFolder { get { if (m_modInstallFolder == null) { m_modInstallFolder = Path.GetDirectoryName(Instance.GetType().Assembly.Location); LogUtils.DoInfoLog("Mod location: " + m_modInstallFolder); } return m_modInstallFolder; } } public static string MinorVersion => Instance.MinorVersion_ + "B"; public static string MajorVersion => Instance.MajorVersion_ + "B"; public static string FullVersion => Version; public static string Version => Instance.Version_ + "B"; public string Name => SimpleName + " " + Version; public string GeneralName => SimpleName + " (v" + Version + ")"; protected Dictionary<string, Coroutine> TasksRunningOnController { get; } = new Dictionary<string, Coroutine>(); private string MinorVersion_ => MajorVersion_ + "." + GetType().Assembly.GetName().Version.Build; private string MajorVersion_ => GetType().Assembly.GetName().Version.Major + "." + GetType().Assembly.GetName().Version.Minor; private string FullVersion_ => MinorVersion_ + " r" + GetType().Assembly.GetName().Version.Revision; private string Version_ => (GetType().Assembly.GetName().Version.Minor == 0 && GetType().Assembly.GetName().Version.Build == 0) ? GetType().Assembly.GetName().Version.Major.ToString() : ((GetType().Assembly.GetName().Version.Build > 0) ? MinorVersion_ : MajorVersion_); public string CouiHost => Acronym.ToLower() + ".k45"; public void OnCreateWorld(UpdateSystem updateSystem) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) UpdateSystem = updateSystem; Redirector.OnWorldCreated(((ComponentSystemBase)UpdateSystem).World); LoadLocales(); UISystem uiSystem = GameManager.instance.userInterface.view.uiSystem; LogUtils.DoLog("CouiHost => " + CouiHost); ((DefaultResourceHandler)uiSystem.resourceHandler).HostLocationsMap.Add(CouiHost, new List<string> { ModInstallFolder }); DoOnCreateWorld(updateSystem); } public abstract void OnDispose(); public abstract BasicModData CreateSettingsFile(); public void OnLoad() { Instance = this; LogUtils.LogsEnabled = true; ModData = CreateSettingsFile(); ((ModSetting)ModData).RegisterInOptionsUI(); AssetDatabase.global.LoadSettings(SafeName, (object)ModData, (object)null); KFileUtils.EnsureFolderCreation(ModSettingsRootFolder); DoOnLoad(); } public abstract void DoOnCreateWorld(UpdateSystem updateSystem); public abstract void DoOnLoad(); private void LoadLocales() { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Expected O, but got Unknown string path = Path.Combine(ModInstallFolder, "i18n.csv"); if (File.Exists(path)) { IEnumerable<string[]> enumerable = from x in File.ReadAllLines(path) select x.Split('\t'); int valueColumn = Array.IndexOf(enumerable.First(), "en-US"); MemorySource val = new MemorySource(LocaleFileForColumn(enumerable, valueColumn)); string[] supportedLocales = GameManager.instance.localizationManager.GetSupportedLocales(); foreach (string text in supportedLocales) { GameManager.instance.localizationManager.AddSource(text, (IDictionarySource)(object)val); if (text != "en-US") { int num = Array.IndexOf(enumerable.First(), text); if (num > 0) { MemorySource val2 = new MemorySource(LocaleFileForColumn(enumerable, num)); GameManager.instance.localizationManager.AddSource(text, (IDictionarySource)(object)val2); } } GameManager.instance.localizationManager.AddSource(text, (IDictionarySource)(object)new ModGenI18n(ModData)); } } else { string[] supportedLocales2 = GameManager.instance.localizationManager.GetSupportedLocales(); foreach (string text2 in supportedLocales2) { GameManager.instance.localizationManager.AddSource("en-US", (IDictionarySource)(object)new ModGenI18n(ModData)); } } } private static Dictionary<string, string> LocaleFileForColumn(IEnumerable<string[]> fileLines, int valueColumn) { return (from x in fileLines.Skip(1) group x by x[0] into x select x.First()).ToDictionary((string[] x) => ProcessKey(x[0], ModData), delegate(string[] x) { string text = x.ElementAtOrDefault(valueColumn); return RemoveQuotes((text != null && !StringExtensions.IsNullOrWhitespace(text)) ? text : x.ElementAtOrDefault(1)); }); } private static string ProcessKey(string key, BasicModData modData) { if (!key.StartsWith("::")) { return key; } string text = key.Substring(0, 3); string text2 = key; string text3 = text2.Substring(3, text2.Length - 3); if (1 == 0) { } switch (text) { case "::L": text2 = ((ModSetting)modData).GetOptionLabelLocaleID(text3); break; case "::G": text2 = ((ModSetting)modData).GetOptionGroupLocaleID(text3); break; case "::D": text2 = ((ModSetting)modData).GetOptionDescLocaleID(text3); break; case "::T": text2 = ((ModSetting)modData).GetOptionTabLocaleID(text3); break; case "::W": text2 = ((ModSetting)modData).GetOptionWarningLocaleID(text3); break; case "::E": { string[] array = text3.Split(".", 2); text2 = ((array != null && array.Length == 2) ? modData.GetEnumValueLocaleID(array[0], array[1]) : text3); break; } default: text2 = text3; break; } if (1 == 0) { } return text2; } private static string RemoveQuotes(string v) { string result; if (v == null || !v.StartsWith("\"") || !v.EndsWith("\"")) { result = v; } else { result = v.Substring(1, v.Length - 1 - 1); } return result; } public T GetManagedSystem<T>() where T : ComponentSystemBase { return ((ComponentSystemBase)UpdateSystem).World.GetOrCreateSystemManaged<T>(); } public ComponentSystemBase GetManagedSystem(Type t) { return ((ComponentSystemBase)UpdateSystem).World.GetOrCreateSystemManaged(t); } public void SetupCaller(Action<string, object[]> eventCaller) { List<Type> interfaceImplementations = ReflectionUtils.GetInterfaceImplementations(typeof(IBelzontBindable), new Assembly[1] { GetType().Assembly }); foreach (Type item in interfaceImplementations) { (GetManagedSystem(item) as IBelzontBindable).SetupCaller(eventCaller); } } public void SetupEventBinder(Action<string, Delegate> eventCaller) { List<Type> interfaceImplementations = ReflectionUtils.GetInterfaceImplementations(typeof(IBelzontBindable), new Assembly[1] { GetType().Assembly }); foreach (Type item in interfaceImplementations) { (GetManagedSystem(item) as IBelzontBindable).SetupEventBinder(eventCaller); } } public void SetupCallBinder(Action<string, Delegate> eventCaller) { List<Type> interfaceImplementations = ReflectionUtils.GetInterfaceImplementations(typeof(IBelzontBindable), new Assembly[1] { GetType().Assembly }); foreach (Type item in interfaceImplementations) { (GetManagedSystem(item) as IBelzontBindable).SetupCallBinder(eventCaller); } } } public abstract class BasicModData : ModSetting { public const string kAboutTab = "About"; public static BasicModData Instance { get; private set; } public BasicIMod ModInstance { get; private set; } [SettingsUISection("About", null)] public bool DebugMode { get; set; } [SettingsUISection("About", null)] public string Version => BasicIMod.FullVersion; [SettingsUISection("About", null)] public string CanonVersion => ModInstance?.GetType()?.Assembly?.GetCustomAttribute<KlyteModCanonVersionAttribute>()?.CanonVersion ?? "<N/D>"; protected BasicModData(IMod mod) : base(mod) { ModInstance = mod as BasicIMod; } public sealed override void SetDefaults() { DebugMode = false; OnSetDefaults(); } public abstract void OnSetDefaults(); public string GetEnumValueLocaleID(string classname, string value) { return "Options." + ((ModSetting)this).id + "." + classname.ToUpper() + "[" + value + "]"; } } public interface IEnumerableIndex<T> where T : Enum { T Index { get; set; } } } namespace BelzontAdr { [BepInPlugin("AddressesCS2", "AddressesCS2", "0.0.2.65534")] public class EUIBepinexPlugin : BaseUnityPlugin { public void Awake() { LogUtils.LogsEnabled = false; LogUtils.Logger = ((BaseUnityPlugin)this).Logger; LogUtils.DoInfoLog("STARTING MOD!"); Redirector.PatchAll(); } } public class AddressesCs2Mod : BasicIMod, IMod { public new static AddressesCs2Mod Instance => (AddressesCs2Mod)BasicIMod.Instance; public override string SimpleName => "Addresses CS2"; public override string SafeName => "Addresses"; public override string Acronym => "Adr"; public override string Description => "!!!"; public override void DoOnCreateWorld(UpdateSystem updateSystem) { AdrNameFilesManager.Instance.ReloadNameFiles(); updateSystem.UpdateAfter<AdrDistrictsSystem>((SystemUpdatePhase)9); } public override void OnDispose() { } public override void DoOnLoad() { } public override BasicModData CreateSettingsFile() { return new AdrModData((IMod)(object)this); } } public class AdrNameFilesManager { private static AdrNameFilesManager instance; internal readonly Dictionary<Guid, AdrNameFile> SimpleNamesDict = new Dictionary<Guid, AdrNameFile>(); public static string SimpleNameFolder { get; } = Path.Combine(BasicIMod.ModSettingsRootFolder, "SimpleNameFiles"); public static AdrNameFilesManager Instance => instance ?? (instance = new AdrNameFilesManager()); private AdrNameFilesManager() { KFileUtils.EnsureFolderCreation(SimpleNameFolder); } public void ReloadNameFiles() { LoadSimpleNamesFiles(SimpleNamesDict, SimpleNameFolder); } private static Dictionary<Guid, AdrNameFile> LoadSimpleNamesFiles(Dictionary<Guid, AdrNameFile> result, string path) { result.Clear(); string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories); foreach (string text in files) { string text2 = text.Replace(SimpleNameFolder, ""); string name = text2.Substring(1, text2.Length - 4 - 1).Replace("\\", "/"); string[] source = File.ReadAllLines(text, Encoding.UTF8); AdrNameFile adrNameFile = new AdrNameFile(name, (from x in source select x?.Trim() into x where !string.IsNullOrEmpty(x) select x).ToArray()); result[adrNameFile.Id] = adrNameFile; LogUtils.DoLog($"LOADED Files at {path} ({text} - GUID: {adrNameFile.Id}) QTT: {result[adrNameFile.Id].Values.Length}"); } return result; } } public struct ADRDistrictData : IComponentData, IQueryTypeParameter, ISerializable { public Guid m_roadsNamesId; private const uint CURRENT_VERSION = 0u; public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter { ((IWriter)writer).Write(0u); ((IWriter)writer).Write(m_roadsNamesId.ToString()); } public void Deserialize<TReader>(TReader reader) where TReader : IReader { uint num = default(uint); ((IReader)reader).Read(ref num); if (num != 0) { throw new Exception("Invalid version of ADRDistrictData!"); } string input = default(string); ((IReader)reader).Read(ref input); Guid.TryParse(input, out m_roadsNamesId); } } public struct ADREntityStationRef : IComponentData, IQueryTypeParameter, ISerializable { private const uint CURRENT_VERSION = 0u; public Entity m_refStationBuilding; public void Deserialize<TReader>(TReader reader) where TReader : IReader { uint num = default(uint); ((IReader)reader).Read(ref num); if (num != 0) { throw new Exception("Invalid version of ADREntityStationRef!"); } ((IReader)reader).Read(ref m_refStationBuilding); } public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter { //IL_0013: Unknown result type (might be due to invalid IL or missing references) ((IWriter)writer).Write(0u); ((IWriter)writer).Write(m_refStationBuilding); } } public struct ADRLocalizationData : IComponentData, IQueryTypeParameter, ISerializable { public ushort m_seedReference; private const uint CURRENT_VERSION = 0u; public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter { ((IWriter)writer).Write(0u); ((IWriter)writer).Write(m_seedReference); } public void Deserialize<TReader>(TReader reader) where TReader : IReader { uint num = default(uint); ((IReader)reader).Read(ref num); if (num != 0) { throw new Exception("Invalid version of ADRLocalizationData!"); } ((IReader)reader).Read(ref m_seedReference); } } [XmlRoot("AdrCitywideSettings")] public class AdrCitywideSettings { internal Guid CitizenMaleNameOverrides { get; private set; } internal Guid CitizenFemaleNameOverrides { get; private set; } internal Guid CitizenSurnameOverrides { get; private set; } internal Guid CitizenDogOverrides { get; private set; } internal Guid DefaultRoadNameOverrides { get; private set; } internal Guid DefaultDistrictNameOverrides { get; private set; } [XmlAttribute("RoadNameAsNameStation")] public bool RoadNameAsNameStation { get; set; } [XmlAttribute("RoadNameAsNameCargoStation")] public bool RoadNameAsNameCargoStation { get; set; } [XmlAttribute("SurnameAtFirst")] public bool SurnameAtFirst { get; set; } [XmlAttribute("CitizenMaleNameOverrides")] public string CitizenMaleNameOverridesStr { get { return CitizenMaleNameOverrides.ToString(); } set { CitizenMaleNameOverrides = (Guid.TryParse(value ?? "", out var result) ? result : default(Guid)); } } [XmlAttribute("CitizenFemaleNameOverrides")] public string CitizenFemaleNameOverridesStr { get { return CitizenFemaleNameOverrides.ToString(); } set { CitizenFemaleNameOverrides = (Guid.TryParse(value ?? "", out var result) ? result : default(Guid)); } } [XmlAttribute("CitizenSurnameOverrides")] public string CitizenSurnameOverridesStr { get { return CitizenSurnameOverrides.ToString(); } set { CitizenSurnameOverrides = (Guid.TryParse(value ?? "", out var result) ? result : default(Guid)); } } [XmlAttribute("CitizenDogOverrides")] public string CitizenDogOverridesStr { get { return CitizenDogOverrides.ToString(); } set { CitizenDogOverrides = (Guid.TryParse(value ?? "", out var result) ? result : default(Guid)); } } [XmlAttribute("DefaultRoadNameOverrides")] public string DefaultRoadNameOverridesStr { get { return DefaultRoadNameOverrides.ToString(); } set { DefaultRoadNameOverrides = (Guid.TryParse(value ?? "", out var result) ? result : default(Guid)); } } [XmlAttribute("DefaultDistrictNameOverrides")] public string DefaultDistrictNameOverridesStr { get { return DefaultDistrictNameOverrides.ToString(); } set { DefaultDistrictNameOverrides = (Guid.TryParse(value ?? "", out var result) ? result : default(Guid)); } } [XmlElement("RoadPrefix")] public AdrRoadPrefixSetting RoadPrefixSetting { get; set; } = new AdrRoadPrefixSetting(); [XmlAttribute("DistrictNameAsNameCargoStation")] public bool DistrictNameAsNameCargoStation { get; set; } [XmlAttribute("DistrictNameAsNameStation")] public bool DistrictNameAsNameStation { get; set; } } [XmlRoot("RoadPrefixSetting")] public class AdrRoadPrefixSetting { public AdrRoadPrefixRule FallbackRule { get; set; } = new AdrRoadPrefixRule { FormatPattern = "{name}" }; public List<AdrRoadPrefixRule> AdditionalRules { get; set; } = new List<AdrRoadPrefixRule>(); public AdrRoadPrefixRule GetFirstApplicable(RoadData roadData, bool fullBridge) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) return AdditionalRules.FirstOrDefault((AdrRoadPrefixRule x) => x.IsApplicable(roadData, fullBridge)) ?? FallbackRule; } } [XmlRoot("RoadPrefixRule")] public class AdrRoadPrefixRule { internal float MinSpeed { get; set; } internal float MaxSpeed { get; set; } internal RoadFlags RequiredFlags { get; set; } internal RoadFlags ForbiddenFlags { get; set; } internal bool? FullBridgeRequire { get; set; } = null; [XmlText] public string FormatPattern { get; set; } [XmlAttribute("MinSpeedKmh")] public float MinSpeedKmh { get { return MinSpeed * 1.8f; } set { MinSpeed = value / 1.8f; } } [XmlAttribute("MaxSpeedKmh")] public float MaxSpeedKmh { get { return MaxSpeed * 1.8f; } set { MaxSpeed = value / 1.8f; } } [XmlAttribute("RequiredFlags")] public int RequiredFlagsInt { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected I4, but got Unknown return (int)RequiredFlags; } set { RequiredFlags = (RoadFlags)value; } } [XmlAttribute("ForbiddenFlags")] public int ForbiddenFlagsInt { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected I4, but got Unknown return (int)ForbiddenFlags; } set { ForbiddenFlags = (RoadFlags)value; } } [XmlAttribute("FullBridge")] public int FullBridge { get { return FullBridgeRequire.HasValue ? (FullBridgeRequire.Value ? 1 : (-1)) : 0; } set { if (1 == 0) { } bool? fullBridgeRequire = ((value >= 1) ? new bool?(true) : ((value > -1) ? null : new bool?(false))); if (1 == 0) { } FullBridgeRequire = fullBridgeRequire; } } public bool IsApplicable(RoadData roadData, bool fullBridge) { //IL_0000: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: 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_002a: 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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) return roadData.m_SpeedLimit >= MinSpeed && roadData.m_SpeedLimit <= MaxSpeed && (RoadFlags)(RequiredFlags & roadData.m_Flags) == RequiredFlags && (ForbiddenFlags & roadData.m_Flags) == 0 && (!FullBridgeRequire.HasValue || FullBridgeRequire.Value == fullBridge); } } public class AdrModData : BasicModData { public AdrModData(IMod mod) : base(mod) { } public override void OnSetDefaults() { } } public class AdrNameFile { private static readonly Guid baseGuid = new Guid(214, 657, 645, 54, 54, 45, 45, 45, 45, 45, 45); internal readonly Guid Id; public readonly string Name; public readonly string[] Values; public string IdString => Id.ToString(); public AdrNameFile(string name, string[] values) { Id = GuidUtils.Create(baseGuid, name); Name = name; Values = (from x in values?.Select((string x) => x?.Trim()) where !string.IsNullOrEmpty(x) select x).ToArray() ?? new string[0]; } } public class AdrNameSystemOverrides : Redirector, IRedirectable { private static PrefabSystem prefabSystem; private static EntityManager entityManager; private static EndFrameBarrier m_EndFrameBarrier; private static AdrMainSystem adrMainSystem; public void DoPatches(World world) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) prefabSystem = world.GetExistingSystemManaged<PrefabSystem>(); adrMainSystem = world.GetOrCreateSystemManaged<AdrMainSystem>(); entityManager = world.EntityManager; m_EndFrameBarrier = world.GetOrCreateSystemManaged<EndFrameBarrier>(); MethodInfo method = typeof(NameSystem).GetMethod("GetCitizenName", RedirectorUtils.allFlags); AddRedirect(method, ((object)this).GetType().GetMethod("GetCitizenName", RedirectorUtils.allFlags)); MethodInfo method2 = typeof(NameSystem).GetMethod("GetName", RedirectorUtils.allFlags); AddRedirect(method2, ((object)this).GetType().GetMethod("GetName", RedirectorUtils.allFlags)); MethodInfo method3 = typeof(NameSystem).GetMethod("GetRenderedLabelName", RedirectorUtils.allFlags); AddRedirect(method3, ((object)this).GetType().GetMethod("GetRenderedLabelName", RedirectorUtils.allFlags)); MethodInfo method4 = typeof(NameSystem).GetMethod("GetSpawnableBuildingName", RedirectorUtils.allFlags); AddRedirect(method4, ((object)this).GetType().GetMethod("GetSpawnableBuildingName", RedirectorUtils.allFlags)); MethodInfo method5 = typeof(NameSystem).GetMethod("GetMarkerTransportStopName", RedirectorUtils.allFlags); AddRedirect(method5, ((object)this).GetType().GetMethod("GetMarkerTransportStopName", RedirectorUtils.allFlags)); MethodInfo method6 = typeof(NameSystem).GetMethod("GetStaticTransportStopName", RedirectorUtils.allFlags); AddRedirect(method6, ((object)this).GetType().GetMethod("GetStaticTransportStopName", RedirectorUtils.allFlags)); } public static bool GetRenderedLabelName(ref string __result, ref NameSystem __instance, ref Entity entity) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0099: 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_00ad: 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) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) string format = null; if (((EntityManager)(ref entityManager)).HasComponent<Aggregate>(entity)) { if (__instance.TryGetCustomName(entity, ref __result)) { return false; } if (GetAggregateName(out format, out __result, entity)) { string id = GetId(entity); string text = default(string); __result = (GameManager.instance.localizationManager.activeDictionary.TryGetValue(id, ref text) ? text : id); return false; } __result = format.Replace("{name}", __result); return false; } if (((EntityManager)(ref entityManager)).HasComponent<District>(entity)) { if (__instance.TryGetCustomName(entity, ref __result)) { return false; } if (GetDistrictName(out format, out __result, entity)) { string id2 = GetId(entity); string text2 = default(string); __result = (GameManager.instance.localizationManager.activeDictionary.TryGetValue(id2, ref text2) ? text2 : id2); return false; } __result = format.Replace("{name}", __result); return false; } return true; } private static bool GetMarkerTransportStopName(ref Name __result, ref NameSystem __instance, ref Entity stop) { //IL_0002: 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_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) Entity val = stop; Owner val2 = default(Owner); for (int i = 0; i < 8; i++) { if (!EntitiesExtensions.TryGetComponent<Owner>(entityManager, val, ref val2)) { break; } val = val2.m_Owner; } if (val != stop) { __result = __instance.GetName(val, false); return false; } return true; } private static bool GetStaticTransportStopName(ref Name __result, ref NameSystem __instance, ref Entity stop) { //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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) Entity entity = default(Entity); int num = default(int); BuildingUtils.GetAddress(entityManager, stop, ref entity, ref num); if (GetAggregateName(out var format, out var name, entity)) { return true; } string text = format.Replace("{name}", name); __result = Name.FormattedName("Assets.ADDRESS_NAME_FORMAT", new string[4] { "ROAD", text, "NUMBER", num.ToString() }); return false; } private static bool GetSpawnableBuildingName(ref Name __result, ref Entity building, ref Entity zone, ref bool omitBrand) { //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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_005b: Invalid comparison between Unknown and I4 //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) Entity entity = default(Entity); int num = default(int); BuildingUtils.GetAddress(entityManager, building, ref entity, ref num); if (GetAggregateName(out var format, out var name, entity)) { return true; } string text = format.Replace("{name}", name); ZonePrefab prefab = prefabSystem.GetPrefab<ZonePrefab>(zone); if (!omitBrand && (int)prefab.m_AreaType != 1) { string brandId = GetBrandId(building); if (brandId != null) { __result = Name.FormattedName("Assets.NAMED_ADDRESS_NAME_FORMAT", new string[6] { "NAME", brandId, "ROAD", text, "NUMBER", num.ToString() }); return false; } } __result = Name.FormattedName("Assets.ADDRESS_NAME_FORMAT", new string[4] { "ROAD", text, "NUMBER", num.ToString() }); return false; } private static string GetBrandId(Entity building) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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) DynamicBuffer<Renter> buffer = ((EntityManager)(ref entityManager)).GetBuffer<Renter>(building, true); CompanyData val = default(CompanyData); for (int i = 0; i < buffer.Length; i++) { if (EntitiesExtensions.TryGetComponent<CompanyData>(entityManager, buffer[i].m_Renter, ref val)) { return GetId(val.m_Brand); } } return null; } private static bool GetName(ref Name __result, ref NameSystem __instance, Entity entity) { //IL_0003: 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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Invalid comparison between Unknown and I4 //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_038c: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03b7: Unknown result type (might be due to invalid IL or missing references) //IL_03b8: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_02f6: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Unknown result type (m