Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of BeegOptimizations v1.0.0
BepInEx/plugins/BeegOptimizations/BeegOptimizations.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("TheDrillTeam")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BeegOptimizations")] [assembly: AssemblyTitle("BeegOptimizations")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BeegOptimizations { internal sealed class FairAIConfigCache : Feature { private ConfigEntry<bool> _enabled; private static readonly Dictionary<(string, string, string), bool> Memo = new Dictionary<(string, string, string), bool>(); private static ConfigFile _cfg; private static int _count = -1; private static FieldInfo _instanceField; private static bool _patched; internal static long Hits; internal static long Misses; internal override string Name => "FairAIConfigCache"; internal static string Stats() { return $"FairAIConfigCache: {Hits} answered from cache, {Misses} computed"; } internal override bool Bind(ConfigFile cfg) { _enabled = cfg.Bind<bool>("Mods", "FairAIConfigCache", true, "Fair AI: remember the answers of its config lookups (asked every frame and per turret/mine target) instead of re-scanning and re-formatting all of its config keys each time. Removes ~130 KB/frame of garbage (GC stutter). Answers are refreshed whenever its config changes."); return _enabled.Value; } internal override void Apply() { AppDomain.CurrentDomain.AssemblyLoad += delegate(object _, AssemblyLoadEventArgs e) { TryPatch(e.LoadedAssembly); }; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int num = 0; num < assemblies.Length; num++) { TryPatch(assemblies[num]); } } private static void TryPatch(Assembly a) { //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Expected O, but got Unknown //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Expected O, but got Unknown //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Expected O, but got Unknown if (_patched) { return; } string name; try { name = a.GetName().Name; } catch { return; } if (name != "FairAI") { return; } _patched = true; try { Type type = a.GetType("FairAI.Plugin", throwOnError: false); MethodInfo methodInfo = type?.GetMethod("Can", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(string) }, null); MethodInfo methodInfo2 = type?.GetMethod("CanMob", BindingFlags.Static | BindingFlags.Public, null, new Type[3] { typeof(string), typeof(string), typeof(string) }, null); _instanceField = type?.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (methodInfo == null || methodInfo2 == null || methodInfo.ReturnType != typeof(bool) || methodInfo2.ReturnType != typeof(bool) || _instanceField == null) { Plugin.Log.LogInfo((object)"FairAIConfigCache: Fair AI looks different in this version; not patching."); return; } HarmonyMethod val = new HarmonyMethod(typeof(FairAIConfigCache), "Post", (Type[])null); Plugin.Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(FairAIConfigCache), "CanPrefix", (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.Harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(FairAIConfigCache), "CanMobPrefix", (Type[])null), val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.Log.LogInfo((object)"FairAIConfigCache: patched Fair AI"); } catch (Exception ex) { Plugin.Log.LogWarning((object)("FairAIConfigCache: not patched: " + ex.Message)); } } private static bool Valid() { if (_cfg == null) { object? value = _instanceField.GetValue(null); BaseUnityPlugin val = (BaseUnityPlugin)((value is BaseUnityPlugin) ? value : null); if (val == null || val.Config == null) { return false; } _cfg = val.Config; _cfg.SettingChanged += delegate { Memo.Clear(); }; _cfg.ConfigReloaded += delegate { Memo.Clear(); }; } int count = _cfg.Count; if (count != _count) { Memo.Clear(); _count = count; } return true; } private static bool Lookup((string, string, string) key, ref bool result, ref (string, string, string)? state) { try { if (!Valid()) { return true; } if (Memo.TryGetValue(key, out var value)) { result = value; Hits++; return false; } state = key; Misses++; } catch { } return true; } private static bool CanPrefix(string identifier, ref bool __result, out (string, string, string)? __state, bool __runOriginal) { __state = null; if (!__runOriginal || identifier == null) { return __runOriginal; } return Lookup((null, identifier, null), ref __result, ref __state); } private static bool CanMobPrefix(string parentIdentifier, string identifier, string mobName, ref bool __result, out (string, string, string)? __state, bool __runOriginal) { __state = null; if (!__runOriginal || parentIdentifier == null || identifier == null || mobName == null) { return __runOriginal; } return Lookup((parentIdentifier, identifier, mobName), ref __result, ref __state); } private static void Post(bool __result, (string, string, string)? __state) { if (__state.HasValue) { Memo[__state.Value] = __result; } } } [BepInPlugin("beeg.optimizations", "BeegOptimizations", "1.0.0")] public class Plugin : BaseUnityPlugin { internal static ManualLogSource Log; internal static Harmony Harmony; internal static ConfigFile Cfg; internal static ConfigEntry<bool> VerboseLogging; private static readonly List<Feature> Features = new List<Feature>(); private static string _lastStats; private void Awake() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Cfg = ((BaseUnityPlugin)this).Config; Harmony = new Harmony("beeg.optimizations"); VerboseLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "VerboseLogging", false, "Log what each optimization does (for troubleshooting)."); Features.Add(new UnityStackTraces()); Features.Add(new SceneScanRegistry()); Features.Add(new FairAIConfigCache()); Features.Add(new TheComplexProcTextures()); ((BaseUnityPlugin)this).Config.Bind<bool>("Startup", "TypeLookupIndex", true, "Answer Harmony's AccessTools.TypeByName / GetTypesFromAssembly from a per-assembly index instead of re-listing every type of every loaded assembly on each call (seconds of startup in big packs). Same results, same search order. Applies at next launch."); ((BaseUnityPlugin)this).Config.Bind<bool>("Startup", "TheComplexTextureCache", true, "The Complex: keep a pre-compressed copy of each cached texture next to its own cache so later launches skip re-compressing ~500 textures on the main thread. Identical textures; costs some extra disk in BepInEx/cache/TheComplex. Applies at next launch."); ((BaseUnityPlugin)this).Config.Bind<bool>("Startup", "TheComplexFastMeshAppend", true, "The Complex: faster MeshBuilder.Append while it builds its room templates at boot (same arithmetic written out inline, lists sized up front; bit-identical geometry). Applies at next launch."); ((BaseUnityPlugin)this).Config.Bind<bool>("Startup", "SkipIdleOpenXR", true, "LCVR: when no VR runtime (SteamVR, Virtual Desktop, Oculus, WMR, ALVR, Pico, Vive) is running at launch, skip its OpenXR start-up attempt (~6 s, always fails without a headset) and go straight to flat mode. Start your VR runtime before the game to play in VR."); SceneManager.sceneLoaded += LogStartupStats; SceneManager.sceneLoaded += delegate { LogFeatureStats(); }; foreach (Feature feature in Features) { try { if (feature.Bind(((BaseUnityPlugin)this).Config)) { feature.Apply(); Log.LogInfo((object)(feature.Name + ": on")); } else { Log.LogInfo((object)(feature.Name + ": off")); } } catch (Exception arg) { Log.LogError((object)$"{feature.Name} failed to start and was skipped: {arg}"); } } } private static void LogStartupStats(Scene scene, LoadSceneMode mode) { if (((Scene)(ref scene)).name != "MainMenu") { return; } SceneManager.sceneLoaded -= LogStartupStats; try { Assembly? assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "BeegOptimizations.Preloader"); object obj = assembly?.GetType("BeegOptimizations.Preloader.TypeIndex")?.GetMethod("Stats")?.Invoke(null, null); object obj2 = assembly?.GetType("BeegOptimizations.Preloader.TheComplexMeshes")?.GetMethod("Stats")?.Invoke(null, null); if (obj2 != null) { obj = obj?.ToString() + "; " + obj2; } Log.LogInfo((object)((obj != null) ? ("Startup: " + obj) : "Startup: preloader not installed (BepInEx/patchers/BeegOptimizations), TypeLookupIndex inactive")); } catch (Exception ex) { Log.LogWarning((object)("Startup stats: " + ex.Message)); } } private static void LogFeatureStats() { try { string text = TheComplexProcTextures.Stats() + "; " + FairAIConfigCache.Stats(); if (!(text == _lastStats)) { _lastStats = text; Log.LogInfo((object)text); } } catch { } } internal static void Verbose(string msg) { if (VerboseLogging.Value) { Log.LogInfo((object)msg); } } } internal abstract class Feature { internal abstract string Name { get; } internal abstract bool Bind(ConfigFile cfg); internal abstract void Apply(); } internal sealed class SceneScanRegistry : Feature { private sealed class Tracked { public Type Type; public readonly Dictionary<int, Component> Items = new Dictionary<int, Component>(); public int ValidateLeft; public bool Disabled; public long Served; } private ConfigEntry<bool> _enabled; private static ConfigEntry<string> _types; private static ConfigEntry<bool> _auto; private static ConfigEntry<int> _autoCalls; private static ConfigEntry<float> _autoWindow; private static ConfigEntry<int> _validate; private static readonly Dictionary<Type, Tracked> TrackedTypes = new Dictionary<Type, Tracked>(); private static Tracked[] _trackedList = Array.Empty<Tracked>(); private static readonly Dictionary<Type, (float start, int n)> Counts = new Dictionary<Type, (float, int)>(); private static readonly HashSet<Type> Rejected = new HashSet<Type>(); private static readonly HashSet<MethodBase> HookedAwakes = new HashSet<MethodBase>(); private static HashSet<string> _configured = new HashSet<string>(); private static readonly List<int> Dead = new List<int>(); private static readonly List<KeyValuePair<int, Component>> Buf = new List<KeyValuePair<int, Component>>(); [ThreadStatic] private static bool _bypass; internal override string Name => "SceneScanRegistry"; internal override bool Bind(ConfigFile cfg) { _enabled = cfg.Bind<bool>("SceneScans", "Enabled", true, "Answer repeated FindObjectsOfType scans for hot types from a live-instance registry instead of walking every loaded object."); _types = cfg.Bind<string>("SceneScans", "Types", "SandSpiderWebTrap, LCVR.Physics.Interactions.ShipLever, LCVR.Physics.Interactions.Car.GearStick", "Types (name or full name) to track from their first scan. Known periodic scanners: High Quota Fixes (webs), LCVR Fixes (lever / gear stick)."); _auto = cfg.Bind<bool>("SceneScans", "AutoTrack", true, "Also track any MonoBehaviour type that gets scanned repeatedly (see AutoTrackCalls / AutoTrackWindow)."); _autoCalls = cfg.Bind<int>("SceneScans", "AutoTrackCalls", 6, "Scans of the same type within AutoTrackWindow seconds before it is tracked."); _autoWindow = cfg.Bind<float>("SceneScans", "AutoTrackWindow", 10f, "Window in seconds for AutoTrackCalls."); _validate = cfg.Bind<int>("SceneScans", "ValidateScans", 1, "After each scene load, cross-check this many registry answers per type against a real scan (a mismatch hands the type back to Unity)."); return _enabled.Value; } internal override void Apply() { //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Expected O, but got Unknown _configured = new HashSet<string>(from s in _types.Value.Split(',') select s.Trim() into s where s.Length > 0 select s); Harmony harmony = Plugin.Harmony; MethodInfo methodInfo = AccessTools.Method(typeof(Object), "FindObjectsOfType", new Type[2] { typeof(Type), typeof(bool) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(Object), "FindObjectsByType", new Type[3] { typeof(Type), typeof(FindObjectsInactive), typeof(FindObjectsSortMode) }, (Type[])null); harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(SceneScanRegistry), "FindObjectsOfTypePrefix", (Type[])null) { priority = 300 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(SceneScanRegistry), "FindObjectsByTypePrefix", (Type[])null) { priority = 300 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); SceneManager.sceneLoaded += delegate { Tracked[] trackedList = _trackedList; for (int i = 0; i < trackedList.Length; i++) { trackedList[i].ValidateLeft = _validate.Value; } }; } private static bool FindObjectsOfTypePrefix(Type type, bool includeInactive, bool __runOriginal, ref Object[] __result) { if (!__runOriginal) { return false; } return !TryServe(type, includeInactive, ref __result); } private static bool FindObjectsByTypePrefix(Type type, FindObjectsInactive findObjectsInactive, bool __runOriginal, ref Object[] __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if (!__runOriginal) { return false; } return !TryServe(type, (int)findObjectsInactive == 1, ref __result); } private static bool TryServe(Type type, bool includeInactive, ref Object[] result) { if (_bypass || includeInactive || type == null) { return false; } try { if (!TrackedTypes.TryGetValue(type, out var value)) { if (Rejected.Contains(type) || !ShouldTrack(type)) { return false; } value = StartTracking(type); if (value == null) { return false; } } if (value.Disabled) { return false; } if (value.ValidateLeft > 0) { Object[] array = NativeScan(type, includeInactive: false); if (Validate(value, array)) { value.ValidateLeft--; } result = array; return true; } result = Collect(value); value.Served++; return true; } catch (Exception ex) { Plugin.Log.LogWarning((object)("SceneScanRegistry: " + type?.FullName + " failed (" + ex.Message + "); handing it back to Unity.")); if (type != null) { Rejected.Add(type); if (TrackedTypes.TryGetValue(type, out var value2)) { value2.Disabled = true; } } return false; } } private static bool ShouldTrack(Type type) { if (_configured.Contains(type.FullName) || _configured.Contains(type.Name)) { return true; } if (!_auto.Value) { return false; } float realtimeSinceStartup = Time.realtimeSinceStartup; Counts.TryGetValue(type, out (float, int) value); if (value.Item2 == 0 || realtimeSinceStartup - value.Item1 > _autoWindow.Value) { value = (realtimeSinceStartup, 0); } value.Item2++; Counts[type] = value; return value.Item2 >= _autoCalls.Value; } private static Object[] NativeScan(Type type, bool includeInactive) { _bypass = true; try { return Object.FindObjectsOfType(type, includeInactive); } finally { _bypass = false; } } private static Tracked StartTracking(Type type) { Counts.Remove(type); if (!typeof(MonoBehaviour).IsAssignableFrom(type) || type.ContainsGenericParameters) { Reject(type, "not a MonoBehaviour type"); return null; } MethodInfo methodInfo = FindAwake(type); if (methodInfo == null) { Reject(type, "no Awake to hook"); return null; } Hook(methodInfo); Tracked tracked = new Tracked { Type = type, ValidateLeft = Math.Max(1, _validate.Value) }; Object[] array = NativeScan(type, includeInactive: true); foreach (Object obj in array) { Component val = (Component)(object)((obj is Component) ? obj : null); if (val != null && (Object)(object)val != (Object)null) { tracked.Items[((Object)val).GetInstanceID()] = val; } } TrackedTypes[type] = tracked; _trackedList = TrackedTypes.Values.ToArray(); Plugin.Log.LogInfo((object)$"SceneScanRegistry: tracking {type.FullName} (hooked {methodInfo.DeclaringType?.Name}.Awake, {tracked.Items.Count} live)"); return tracked; } private static void Reject(Type type, string why) { Rejected.Add(type); Plugin.Verbose("SceneScanRegistry: not tracking " + type.FullName + ": " + why); } private static MethodInfo FindAwake(Type t) { Type type = t; while (type != null && type != typeof(MonoBehaviour) && type != typeof(Behaviour)) { MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "Awake", Type.EmptyTypes, (Type[])null); if (methodInfo != null && !methodInfo.IsAbstract && methodInfo.GetMethodBody() != null) { return methodInfo; } type = type.BaseType; } return null; } private static void Hook(MethodInfo awake) { //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_003d: Expected O, but got Unknown if (HookedAwakes.Add(awake)) { Plugin.Harmony.Patch((MethodBase)awake, new HarmonyMethod(typeof(SceneScanRegistry), "AwakePrefix", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } private static void AwakePrefix(Component __instance) { if ((Object)(object)__instance == (Object)null) { return; } Tracked[] trackedList = _trackedList; foreach (Tracked tracked in trackedList) { if (!tracked.Disabled && tracked.Type.IsInstanceOfType(__instance)) { tracked.Items[((Object)__instance).GetInstanceID()] = __instance; } } } private static Object[] Collect(Tracked tr) { Dead.Clear(); Buf.Clear(); foreach (KeyValuePair<int, Component> item in tr.Items) { Component value = item.Value; if ((Object)(object)value == (Object)null) { Dead.Add(item.Key); } else if (value.gameObject.activeInHierarchy) { Buf.Add(item); } } foreach (int item2 in Dead) { tr.Items.Remove(item2); } Buf.Sort((KeyValuePair<int, Component> a, KeyValuePair<int, Component> b) => a.Key.CompareTo(b.Key)); Object[] array = (Object[])Array.CreateInstance(tr.Type, Buf.Count); for (int num = 0; num < Buf.Count; num++) { array[num] = (Object)(object)Buf[num].Value; } Buf.Clear(); return array; } private static bool Validate(Tracked tr, Object[] real) { //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Expected O, but got Unknown HashSet<int> hashSet = new HashSet<int>(from o in Collect(tr) select o.GetInstanceID()); HashSet<int> realIds = new HashSet<int>(); bool flag = false; foreach (Object val in real) { if (val == (Object)null) { continue; } int instanceID = val.GetInstanceID(); realIds.Add(instanceID); if (!hashSet.Contains(instanceID)) { MethodInfo methodInfo = ((val is Component) ? FindAwake(((object)val).GetType()) : null); if (methodInfo == null || HookedAwakes.Contains(methodInfo)) { Disable(tr, "registry missed " + ((object)val).GetType().FullName + " '" + val.name + "'"); return false; } Hook(methodInfo); tr.Items[instanceID] = (Component)val; flag = true; } } int num2 = hashSet.Count((int id) => !realIds.Contains(id)); if (num2 > 0) { Disable(tr, $"registry had {num2} object(s) Unity doesn't return"); return false; } if (flag) { Plugin.Verbose("SceneScanRegistry: " + tr.Type.Name + ": hooked a subclass Awake, re-validating"); return false; } Plugin.Verbose($"SceneScanRegistry: {tr.Type.Name} validated ({realIds.Count} live, {tr.Served} served so far)"); return true; } private static void Disable(Tracked tr, string why) { tr.Disabled = true; tr.Items.Clear(); Rejected.Add(tr.Type); Plugin.Log.LogWarning((object)("SceneScanRegistry: stopped tracking " + tr.Type.FullName + ": " + why + ". Scans of it go to Unity again.")); } } internal sealed class TheComplexProcTextures : Feature { private sealed class State { public string File; public long T0; public bool Hit; } private const int Magic = 1480806466; private const int Version = 1; private static readonly (string type, string method)[] Generators = new(string, string)[7] { ("BackroomsLevel0.GrimeTextures", "Make"), ("BackroomsLevel0.GrimeTextures", "MakeTear"), ("BackroomsLevel0.GrimeTextures", "MakeFloor"), ("BackroomsLevel0.GrimeTextures", "MakeWear"), ("BackroomsLevel0.L0Carpet", "StainTexture"), ("BackroomsLevel0.PoolroomsLight", "MakeCaustics"), ("BackroomsLevel0.PoolroomsLight", "MakeHaze") }; private static string _dir; private static long _dllLen; private static long _dllTicks; private static bool _patched; private static int _depth; private static readonly List<Texture2D> Captured = new List<Texture2D>(); private static int _hits; private static int _misses; private static double _hitMs; private static double _missMs; internal override string Name => "TheComplexProcTextures"; internal override bool Bind(ConfigFile cfg) { return cfg.Bind<bool>("Mods", "TheComplexProcTextures", true, "The Complex: keep its procedurally painted grime, carpet-stain and pool-caustic textures on disk (BepInEx/cache/BeegOptimizations) instead of re-painting them pixel by pixel on every launch (seconds during lobby load, ~1.4 s hitch on the first Poolrooms landing). Identical textures; refreshed automatically when The Complex updates.").Value; } internal override void Apply() { AppDomain.CurrentDomain.AssemblyLoad += delegate(object _, AssemblyLoadEventArgs e) { TryPatch(e.LoadedAssembly); }; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int num = 0; num < assemblies.Length; num++) { TryPatch(assemblies[num]); } } private static void TryPatch(Assembly a) { //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Expected O, but got Unknown //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Expected O, but got Unknown //IL_01a7: Expected O, but got Unknown //IL_01a7: Expected O, but got Unknown if (_patched) { return; } string name; try { name = a.GetName().Name; } catch { return; } if (name != "BackroomsLevel0") { return; } _patched = true; try { FileInfo fileInfo = new FileInfo(a.Location); _dllLen = fileInfo.Length; _dllTicks = fileInfo.LastWriteTimeUtc.Ticks; _dir = Path.Combine(Paths.CachePath, "BeegOptimizations", "TheComplex"); int num = 0; (string, string)[] generators = Generators; for (int i = 0; i < generators.Length; i++) { (string, string) tuple = generators[i]; string item = tuple.Item1; string item2 = tuple.Item2; MethodInfo methodInfo = a.GetType(item, throwOnError: false)?.GetMethod(item2, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (!(methodInfo == null) && (!(methodInfo.ReturnType != typeof(Texture2D)) || !(methodInfo.ReturnType != typeof(Texture2D[])))) { bool flag = true; ParameterInfo[] parameters = methodInfo.GetParameters(); foreach (ParameterInfo parameterInfo in parameters) { flag &= parameterInfo.ParameterType == typeof(int); } if (flag) { Plugin.Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(TheComplexProcTextures), (methodInfo.ReturnType == typeof(Texture2D)) ? "SinglePrefix" : "ArrayPrefix", (Type[])null), new HarmonyMethod(typeof(TheComplexProcTextures), "GenPostfix", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(TheComplexProcTextures), "GenFinalizer", (Type[])null), (HarmonyMethod)null); num++; } } } if (num == 0) { Plugin.Log.LogInfo((object)"TheComplexProcTextures: The Complex looks different in this version; not patching."); return; } MethodInfo methodInfo2 = AccessTools.Method(typeof(Texture2D), "Apply", new Type[2] { typeof(bool), typeof(bool) }, (Type[])null); Plugin.Harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(TheComplexProcTextures), "ApplyPrefix", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.Log.LogInfo((object)$"TheComplexProcTextures: caching {num} texture generators"); } catch (Exception ex) { Plugin.Log.LogWarning((object)("TheComplexProcTextures: not patched: " + ex.Message)); } } internal static string Stats() { return FormattableString.Invariant($"TheComplexProcTextures: {_hits} restored from cache in {_hitMs:F0} ms, {_misses} generated in {_missMs:F0} ms"); } private static string FileFor(MethodBase m, object[] args) { string text = m.DeclaringType.Name + "." + m.Name; for (int i = 0; i < args.Length; i++) { text = text + "_" + args[i]; } return Path.Combine(_dir, text + ".bin"); } private static bool SinglePrefix(MethodBase __originalMethod, object[] __args, ref Texture2D __result, out State __state, bool __runOriginal) { Texture2D[] array = Begin(__originalMethod, __args, out __state, __runOriginal); if (array == null) { return __state != null; } if (array.Length != 1) { _depth++; __state.Hit = false; return true; } __result = array[0]; return false; } private static bool ArrayPrefix(MethodBase __originalMethod, object[] __args, ref Texture2D[] __result, out State __state, bool __runOriginal) { Texture2D[] array = Begin(__originalMethod, __args, out __state, __runOriginal); if (array == null) { return __state != null; } __result = array; return false; } private static Texture2D[] Begin(MethodBase m, object[] args, out State state, bool runOriginal) { state = null; if (!runOriginal) { return null; } state = new State { File = FileFor(m, args), T0 = Stopwatch.GetTimestamp() }; try { Texture2D[] array = TryLoad(state.File); if (array != null && array.Length != 0) { state.Hit = true; return array; } } catch (Exception ex) { Plugin.Verbose("TheComplexProcTextures: cache read failed: " + ex.Message); } _depth++; return null; } private static void ApplyPrefix(Texture2D __instance, ref bool __1) { if (_depth > 0 && __1) { __1 = false; Captured.Add(__instance); } } private static void GenPostfix(object __result, State __state) { if (__state == null || __state.Hit) { return; } try { object obj = __result as Texture2D[]; if (obj == null) { Texture2D val = (Texture2D)((__result is Texture2D) ? __result : null); obj = ((val == null) ? null : new Texture2D[1] { val }); } Texture2D[] array = (Texture2D[])obj; if (array != null) { Save(__state.File, array); } } catch (Exception ex) { Plugin.Verbose("TheComplexProcTextures: cache write failed: " + ex.Message); } } private static Exception GenFinalizer(Exception __exception, State __state) { if (__state == null) { return __exception; } double num = (double)(Stopwatch.GetTimestamp() - __state.T0) * 1000.0 / (double)Stopwatch.Frequency; if (__state.Hit) { _hits++; _hitMs += num; return __exception; } _misses++; _missMs += num; if (--_depth <= 0) { _depth = 0; foreach (Texture2D item in Captured) { try { if ((Object)(object)item != (Object)null && ((Texture)item).isReadable) { item.Apply(false, true); } } catch { } } Captured.Clear(); } return __exception; } private static Texture2D[] TryLoad(string file) { //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: 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_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Expected O, but got Unknown if (!File.Exists(file)) { return null; } using BinaryReader binaryReader = new BinaryReader(File.OpenRead(file)); if (binaryReader.ReadInt32() != 1480806466 || binaryReader.ReadInt32() != 1 || binaryReader.ReadInt64() != _dllLen || binaryReader.ReadInt64() != _dllTicks) { return null; } int num = binaryReader.ReadInt32(); if (num <= 0 || num > 4096) { return null; } (string, int, int, int, int, bool, int, int, int, int, int, float, int, byte[])[] array = new(string, int, int, int, int, bool, int, int, int, int, int, float, int, byte[])[num]; for (int i = 0; i < num; i++) { (string, int, int, int, int, bool, int, int, int, int, int, float, int, byte[]) tuple = (binaryReader.ReadString(), binaryReader.ReadInt32(), binaryReader.ReadInt32(), binaryReader.ReadInt32(), binaryReader.ReadInt32(), binaryReader.ReadBoolean(), binaryReader.ReadInt32(), binaryReader.ReadInt32(), binaryReader.ReadInt32(), binaryReader.ReadInt32(), binaryReader.ReadInt32(), binaryReader.ReadSingle(), binaryReader.ReadInt32(), null); int num2 = binaryReader.ReadInt32(); tuple.Item14 = binaryReader.ReadBytes(num2); if (tuple.Rest.Item7.Length != num2) { return null; } array[i] = tuple; } Texture2D[] array2 = (Texture2D[])(object)new Texture2D[num]; for (int j = 0; j < num; j++) { (string, int, int, int, int, bool, int, int, int, int, int, float, int, byte[]) tuple2 = array[j]; Texture2D val = new Texture2D(tuple2.Item2, tuple2.Item3, (TextureFormat)tuple2.Item4, tuple2.Item5, tuple2.Item6) { name = tuple2.Item1, wrapModeU = (TextureWrapMode)tuple2.Item7, wrapModeV = (TextureWrapMode)tuple2.Rest.Item1, wrapModeW = (TextureWrapMode)tuple2.Rest.Item2, filterMode = (FilterMode)tuple2.Rest.Item3, anisoLevel = tuple2.Rest.Item4, mipMapBias = tuple2.Rest.Item5 }; val.LoadRawTextureData(tuple2.Rest.Item7); val.Apply(false, true); ((Object)val).hideFlags = (HideFlags)tuple2.Rest.Item6; array2[j] = val; } return array2; } private static void Save(string file, Texture2D[] texs) { //IL_009d: 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_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Expected I4, but got Unknown //IL_00e9: Expected I4, but got Unknown //IL_00e9: Expected I4, but got Unknown //IL_00e9: Expected I4, but got Unknown //IL_00ee: Expected I4, but got Unknown //IL_00ee: Expected I4, but got Unknown List<(Texture2D t, byte[] raw)> data = new List<(Texture2D, byte[])>(); foreach (Texture2D val in texs) { if ((Object)(object)val == (Object)null || !((Texture)val).isReadable) { return; } data.Add((val, val.GetRawTextureData())); } List<(string, int, int, int, int, bool, int, int, int, int, int, float, int)> meta = new List<(string, int, int, int, int, bool, int, int, int, int, int, float, int)>(); foreach (var item2 in data) { Texture2D item = item2.t; meta.Add((((Object)item).name, ((Texture)item).width, ((Texture)item).height, (int)item.format, ((Texture)item).mipmapCount, !((Texture)item).isDataSRGB, (int)((Texture)item).wrapModeU, (int)((Texture)item).wrapModeV, (int)((Texture)item).wrapModeW, (int)((Texture)item).filterMode, ((Texture)item).anisoLevel, ((Texture)item).mipMapBias, (int)((Object)item).hideFlags)); } long len = _dllLen; long ticks = _dllTicks; Task.Run(delegate { try { Directory.CreateDirectory(Path.GetDirectoryName(file)); string text = file + ".part"; using (BinaryWriter binaryWriter = new BinaryWriter(File.Create(text))) { binaryWriter.Write(1480806466); binaryWriter.Write(1); binaryWriter.Write(len); binaryWriter.Write(ticks); binaryWriter.Write(data.Count); for (int j = 0; j < data.Count; j++) { (string, int, int, int, int, bool, int, int, int, int, int, float, int) tuple = meta[j]; binaryWriter.Write(tuple.Item1 ?? ""); binaryWriter.Write(tuple.Item2); binaryWriter.Write(tuple.Item3); binaryWriter.Write(tuple.Item4); binaryWriter.Write(tuple.Item5); binaryWriter.Write(tuple.Item6); binaryWriter.Write(tuple.Item7); binaryWriter.Write(tuple.Rest.Item1); binaryWriter.Write(tuple.Rest.Item2); binaryWriter.Write(tuple.Rest.Item3); binaryWriter.Write(tuple.Rest.Item4); binaryWriter.Write(tuple.Rest.Item5); binaryWriter.Write(tuple.Rest.Item6); binaryWriter.Write(data[j].raw.Length); binaryWriter.Write(data[j].raw); } } if (File.Exists(file)) { File.Delete(file); } File.Move(text, file); } catch (Exception) { } }); } } internal sealed class UnityStackTraces : Feature { private ConfigEntry<bool> _enabled; internal override string Name => "UnityStackTraces"; internal override bool Bind(ConfigFile cfg) { _enabled = cfg.Bind<bool>("Logging", "SkipLogStackTraces", true, "Stop Unity from capturing a stack trace for every Debug.Log/LogWarning (errors and exceptions keep theirs)."); return _enabled.Value; } internal override void Apply() { //IL_0006: 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_001c: Unknown result type (might be due to invalid IL or missing references) Plugin.Verbose($"Stack trace types before: Log={Application.GetStackTraceLogType((LogType)3)} Warning={Application.GetStackTraceLogType((LogType)2)} Error={Application.GetStackTraceLogType((LogType)0)}"); Application.SetStackTraceLogType((LogType)3, (StackTraceLogType)0); Application.SetStackTraceLogType((LogType)2, (StackTraceLogType)0); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "beeg.optimizations"; public const string PLUGIN_NAME = "BeegOptimizations"; public const string PLUGIN_VERSION = "1.0.0"; } }
BepInEx/patchers/BeegOptimizations/BeegOptimizations.Preloader.dll
Decompiled 2 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Mono.Cecil; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("TheDrillTeam")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BeegOptimizations")] [assembly: AssemblyTitle("BeegOptimizations.Preloader")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BeegOptimizations.Preloader { internal static class LcvrStartup { private static readonly string[] RuntimeProcesses = new string[16] { "vrserver", "vrmonitor", "vrcompositor", "VirtualDesktop.Streamer", "VirtualDesktop.Service", "OVRServer_x64", "OVRServiceLauncher", "MixedRealityPortal", "WindowsMixedReality", "ALVR Dashboard", "alvr_dashboard", "alvr_server", "Streaming Assistant", "PICO Connect", "VIVEPORT Desktop", "ViveStreamingServer" }; private static bool _patched; private static PropertyInfo _flags; internal static void Watch(Harmony h) { AppDomain.CurrentDomain.AssemblyLoad += delegate(object _, AssemblyLoadEventArgs e) { TryPatch(e.LoadedAssembly); }; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assemblies) { TryPatch(a); } void TryPatch(Assembly assembly) { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown if (_patched || assembly.GetName().Name != "LCVR") { return; } _patched = true; try { Type? type = assembly.GetType("LCVR.Plugin", throwOnError: false); MethodInfo methodInfo = type?.GetMethod("InitializeVR", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); _flags = type?.GetProperty("Flags", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (methodInfo == null || methodInfo.ReturnType != typeof(bool) || _flags == null) { Patcher.Log.LogInfo((object)"SkipIdleOpenXR: LCVR looks different in this version; not patching."); } else { h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(LcvrStartup), "InitializeVRPrefix", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Patcher.Log.LogInfo((object)"SkipIdleOpenXR: on"); } } catch (Exception ex) { Patcher.Log.LogWarning((object)("SkipIdleOpenXR: not patched: " + ex.Message)); } } } private static bool InitializeVRPrefix(ref bool __result) { try { if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("XR_RUNTIME_JSON"))) { return true; } if (Environment.GetCommandLineArgs().Any((string a) => a.StartsWith("--lcvr", StringComparison.OrdinalIgnoreCase) && a.IndexOf("runtime", StringComparison.OrdinalIgnoreCase) >= 0)) { return true; } Stopwatch stopwatch = Stopwatch.StartNew(); Process[] processes = Process.GetProcesses(); string text = null; Process[] array = processes; foreach (Process process in array) { try { string n = process.ProcessName; if (RuntimeProcesses.Any((string r) => string.Equals(r, n, StringComparison.OrdinalIgnoreCase))) { text = n; break; } } catch { } finally { process.Dispose(); } } if (text != null) { Patcher.Log.LogInfo((object)$"SkipIdleOpenXR: VR runtime '{text}' is running, letting LCVR start VR ({stopwatch.ElapsedMilliseconds} ms check)."); return true; } Patcher.Log.LogWarning((object)"SkipIdleOpenXR: no VR runtime is running (SteamVR, Virtual Desktop, Oculus, WMR, ALVR, Pico, Vive), so LCVR starts in flat mode without its ~6 s OpenXR attempt. To play in VR, start your VR runtime before the game, or set [Startup] SkipIdleOpenXR = false in beeg.optimizations.cfg."); int num2 = Convert.ToInt32(_flags.GetValue(null)); _flags.SetValue(null, Enum.ToObject(_flags.PropertyType, num2 | 0x10)); __result = false; return false; } catch (Exception ex) { Patcher.Log.LogWarning((object)("SkipIdleOpenXR: check failed, letting LCVR try VR: " + ex.Message)); return true; } } } public static class Patcher { internal static ManualLogSource Log; public const string ConfigFileName = "beeg.optimizations.cfg"; public const string TypeIndexKey = "TypeLookupIndex"; public const string TypeIndexDescription = "Answer Harmony's AccessTools.TypeByName / GetTypesFromAssembly from a per-assembly index instead of re-listing every type of every loaded assembly on each call (seconds of startup in big packs). Same results, same search order. Applies at next launch."; public const string ComplexKey = "TheComplexTextureCache"; public const string ComplexDescription = "The Complex: keep a pre-compressed copy of each cached texture next to its own cache so later launches skip re-compressing ~500 textures on the main thread. Identical textures; costs some extra disk in BepInEx/cache/TheComplex. Applies at next launch."; public const string MeshKey = "TheComplexFastMeshAppend"; public const string MeshDescription = "The Complex: faster MeshBuilder.Append while it builds its room templates at boot (same arithmetic written out inline, lists sized up front; bit-identical geometry). Applies at next launch."; public const string LcvrKey = "SkipIdleOpenXR"; public const string LcvrDescription = "LCVR: when no VR runtime (SteamVR, Virtual Desktop, Oculus, WMR, ALVR, Pico, Vive) is running at launch, skip its OpenXR start-up attempt (~6 s, always fails without a headset) and go straight to flat mode. Start your VR runtime before the game to play in VR."; public static IEnumerable<string> TargetDLLs { get; } = Array.Empty<string>(); public static void Patch(AssemblyDefinition assembly) { } public static void Finish() { //IL_001f: 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_002f: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) Log = Logger.CreateLogSource("BeegOptimizations.Preloader"); try { ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "beeg.optimizations.cfg"), true); Harmony h = new Harmony("beeg.optimizations.preloader"); if (val.Bind<bool>("Startup", "TypeLookupIndex", true, "Answer Harmony's AccessTools.TypeByName / GetTypesFromAssembly from a per-assembly index instead of re-listing every type of every loaded assembly on each call (seconds of startup in big packs). Same results, same search order. Applies at next launch.").Value) { TypeIndex.Install(h); } else { Log.LogInfo((object)"TypeLookupIndex: off"); } if (val.Bind<bool>("Startup", "TheComplexTextureCache", true, "The Complex: keep a pre-compressed copy of each cached texture next to its own cache so later launches skip re-compressing ~500 textures on the main thread. Identical textures; costs some extra disk in BepInEx/cache/TheComplex. Applies at next launch.").Value) { TheComplexTextures.Watch(h); } else { Log.LogInfo((object)"TheComplexTextureCache: off"); } if (val.Bind<bool>("Startup", "TheComplexFastMeshAppend", true, "The Complex: faster MeshBuilder.Append while it builds its room templates at boot (same arithmetic written out inline, lists sized up front; bit-identical geometry). Applies at next launch.").Value) { TheComplexMeshes.Watch(h); } else { Log.LogInfo((object)"TheComplexFastMeshAppend: off"); } if (val.Bind<bool>("Startup", "SkipIdleOpenXR", true, "LCVR: when no VR runtime (SteamVR, Virtual Desktop, Oculus, WMR, ALVR, Pico, Vive) is running at launch, skip its OpenXR start-up attempt (~6 s, always fails without a headset) and go straight to flat mode. Start your VR runtime before the game to play in VR.").Value) { LcvrStartup.Watch(h); } else { Log.LogInfo((object)"SkipIdleOpenXR: off"); } } catch (Exception ex) { Log.LogError((object)("Startup optimizations failed to install and were skipped: " + ex)); } } } public static class TheComplexMeshes { private static class Raw<T> { internal static readonly FieldInfo Items; internal static readonly FieldInfo Size; internal static readonly FieldInfo Version; internal static readonly bool Ok; static Raw() { Items = typeof(List<T>).GetField("_items", BindingFlags.Instance | BindingFlags.NonPublic); Size = typeof(List<T>).GetField("_size", BindingFlags.Instance | BindingFlags.NonPublic); Version = typeof(List<T>).GetField("_version", BindingFlags.Instance | BindingFlags.NonPublic); Ok = Items?.FieldType == typeof(T[]) && Size?.FieldType == typeof(int) && Version?.FieldType == typeof(int); } internal static T[] Open(List<T> list, int extra) { int num = list.Count + extra; if (list.Capacity < num) { list.Capacity = Math.Max(num, list.Capacity * 2); } return (T[])Items.GetValue(list); } internal static void Commit(List<T> list, int newSize) { Size.SetValue(list, newSize); Version.SetValue(list, (int)Version.GetValue(list) + 1); } } [StructLayout(LayoutKind.Explicit)] private struct Bits { [FieldOffset(0)] public float F; [FieldOffset(0)] public int I; } private static FieldInfo _verts; private static FieldInfo _normals; private static FieldInfo _uvs; private static FieldInfo _tris; private static bool _patched; internal static long Calls; internal static long Fallbacks; internal static long Ticks; private static int _checksLeft = 64; private static bool _disabled; private static long _checked; internal static void Watch(Harmony h) { AppDomain.CurrentDomain.AssemblyLoad += delegate(object _, AssemblyLoadEventArgs e) { TryPatch(e.LoadedAssembly); }; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assemblies) { TryPatch(a); } void TryPatch(Assembly assembly) { //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown if (!_patched) { string name; try { name = assembly.GetName().Name; } catch { return; } if (!(name != "BackroomsLevel0")) { _patched = true; try { Type type = assembly.GetType("BackroomsLevel0.MeshBuilder", throwOnError: false); MethodInfo methodInfo = type?.GetMethod("Append", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { type, typeof(Matrix4x4) }, null); _verts = type?.GetField("verts", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _normals = type?.GetField("normals", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _uvs = type?.GetField("uvs", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _tris = type?.GetField("tris", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (methodInfo == null || _verts?.FieldType != typeof(List<Vector3>) || _normals?.FieldType != typeof(List<Vector3>) || _uvs?.FieldType != typeof(List<Vector2>) || _tris?.FieldType != typeof(List<int>)) { Patcher.Log.LogInfo((object)"TheComplexFastMeshAppend: The Complex's MeshBuilder looks different in this version; not patching."); } else { h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(TheComplexMeshes), "AppendPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Patcher.Log.LogInfo((object)"TheComplexFastMeshAppend: on"); } } catch (Exception ex) { Patcher.Log.LogWarning((object)("TheComplexFastMeshAppend: not patched: " + ex.Message)); } } } } } public static string Stats() { return FormattableString.Invariant(FormattableStringFactory.Create("TheComplexFastMeshAppend: {0} appends in {1:F0} ms ({2} via original, {3} vertices verified bit-identical{4})", Calls, (double)Ticks * 1000.0 / (double)Stopwatch.Frequency, Fallbacks, _checked, _disabled ? ", DISABLED after a mismatch" : "")); } private static bool AppendPrefix(object __instance, object other, Matrix4x4 m, bool __runOriginal) { //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01da: 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_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_021a: 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_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: 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_02e1: Unknown result type (might be due to invalid IL or missing references) //IL_02ec: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) //IL_0363: Unknown result type (might be due to invalid IL or missing references) if (!__runOriginal) { return false; } if (_disabled) { return true; } if (other == null || other == __instance) { Fallbacks++; return true; } long timestamp = Stopwatch.GetTimestamp(); List<Vector3> list; List<Vector3> list2; List<Vector2> list3; List<int> list4; List<Vector3> list5; List<Vector3> list6; List<Vector2> list7; List<int> list8; try { list = (List<Vector3>)_verts.GetValue(__instance); list2 = (List<Vector3>)_normals.GetValue(__instance); list3 = (List<Vector2>)_uvs.GetValue(__instance); list4 = (List<int>)_tris.GetValue(__instance); list5 = (List<Vector3>)_verts.GetValue(other); list6 = (List<Vector3>)_normals.GetValue(other); list7 = (List<Vector2>)_uvs.GetValue(other); list8 = (List<int>)_tris.GetValue(other); } catch { Fallbacks++; return true; } int count = list5.Count; if (list == null || list2 == null || list3 == null || list4 == null || list8 == null || list6.Count < count || list7.Count < count) { Fallbacks++; return true; } if (_checksLeft > 0 && !Verify(list5, list6, m)) { Fallbacks++; return true; } int count2 = list.Count; if (Raw<Vector3>.Ok && Raw<Vector2>.Ok && Raw<int>.Ok && list2.Count == count2 && list3.Count == count2) { AppendRaw(list, list2, list3, list4, list5, list6, list7, list8, count, count2, ref m); Calls++; Ticks += Stopwatch.GetTimestamp() - timestamp; return false; } Reserve(list, count); Reserve(list2, count); Reserve(list3, count); Reserve(list4, list8.Count); float m2 = m.m00; float m3 = m.m01; float m4 = m.m02; float m5 = m.m03; float m6 = m.m10; float m7 = m.m11; float m8 = m.m12; float m9 = m.m13; float m10 = m.m20; float m11 = m.m21; float m12 = m.m22; float m13 = m.m23; for (int i = 0; i < count; i++) { Vector3 val = list5[i]; list.Add(new Vector3(m2 * val.x + m3 * val.y + m4 * val.z + m5, m6 * val.x + m7 * val.y + m8 * val.z + m9, m10 * val.x + m11 * val.y + m12 * val.z + m13)); Vector3 val2 = list6[i]; float num = m2 * val2.x + m3 * val2.y + m4 * val2.z; float num2 = m6 * val2.x + m7 * val2.y + m8 * val2.z; float num3 = m10 * val2.x + m11 * val2.y + m12 * val2.z; float num4 = (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3); list2.Add((Vector3)((num4 > 1E-05f) ? new Vector3(num / num4, num2 / num4, num3 / num4) : Vector3.zero)); list3.Add(list7[i]); } int count3 = list8.Count; for (int j = 0; j < count3; j++) { list4.Add(count2 + list8[j]); } Calls++; Ticks += Stopwatch.GetTimestamp() - timestamp; return false; } private static void AppendRaw(List<Vector3> verts, List<Vector3> normals, List<Vector2> uvs, List<int> tris, List<Vector3> ov, List<Vector3> on, List<Vector2> ou, List<int> ot, int n, int count, ref Matrix4x4 m) { //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: 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_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: 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_0161: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) Vector3[] array = Raw<Vector3>.Open(verts, n); Vector3[] array2 = Raw<Vector3>.Open(normals, n); Vector2[] destinationArray = Raw<Vector2>.Open(uvs, n); Vector3[] array3 = (Vector3[])Raw<Vector3>.Items.GetValue(ov); Vector3[] array4 = (Vector3[])Raw<Vector3>.Items.GetValue(on); Vector2[] sourceArray = (Vector2[])Raw<Vector2>.Items.GetValue(ou); float m2 = m.m00; float m3 = m.m01; float m4 = m.m02; float m5 = m.m03; float m6 = m.m10; float m7 = m.m11; float m8 = m.m12; float m9 = m.m13; float m10 = m.m20; float m11 = m.m21; float m12 = m.m22; float m13 = m.m23; for (int i = 0; i < n; i++) { Vector3 val = array3[i]; array[count + i] = new Vector3(m2 * val.x + m3 * val.y + m4 * val.z + m5, m6 * val.x + m7 * val.y + m8 * val.z + m9, m10 * val.x + m11 * val.y + m12 * val.z + m13); Vector3 val2 = array4[i]; float num = m2 * val2.x + m3 * val2.y + m4 * val2.z; float num2 = m6 * val2.x + m7 * val2.y + m8 * val2.z; float num3 = m10 * val2.x + m11 * val2.y + m12 * val2.z; float num4 = (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3); array2[count + i] = (Vector3)((num4 > 1E-05f) ? new Vector3(num / num4, num2 / num4, num3 / num4) : Vector3.zero); } Array.Copy(sourceArray, 0, destinationArray, count, n); Raw<Vector3>.Commit(verts, count + n); Raw<Vector3>.Commit(normals, count + n); Raw<Vector2>.Commit(uvs, count + n); int count2 = ot.Count; int count3 = tris.Count; int[] array5 = Raw<int>.Open(tris, count2); int[] array6 = (int[])Raw<int>.Items.GetValue(ot); for (int j = 0; j < count2; j++) { array5[count3 + j] = count + array6[j]; } Raw<int>.Commit(tris, count3 + count2); } private static bool Verify(List<Vector3> ov, List<Vector3> on, Matrix4x4 m) { //IL_000c: 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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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_0040: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0058: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: 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_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: 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_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) _checksLeft--; float m2 = m.m00; float m3 = m.m01; float m4 = m.m02; float m5 = m.m03; float m6 = m.m10; float m7 = m.m11; float m8 = m.m12; float m9 = m.m13; float m10 = m.m20; float m11 = m.m21; float m12 = m.m22; float m13 = m.m23; Vector3 val4 = default(Vector3); for (int i = 0; i < ov.Count; i++) { Vector3 val = ov[i]; Vector3 val2 = on[i]; Vector3 val3 = ((Matrix4x4)(ref m)).MultiplyPoint3x4(val); ((Vector3)(ref val4))..ctor(m2 * val.x + m3 * val.y + m4 * val.z + m5, m6 * val.x + m7 * val.y + m8 * val.z + m9, m10 * val.x + m11 * val.y + m12 * val.z + m13); Vector3 val5 = ((Matrix4x4)(ref m)).MultiplyVector(val2); Vector3 normalized = ((Vector3)(ref val5)).normalized; float num = m2 * val2.x + m3 * val2.y + m4 * val2.z; float num2 = m6 * val2.x + m7 * val2.y + m8 * val2.z; float num3 = m10 * val2.x + m11 * val2.y + m12 * val2.z; float num4 = (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3); Vector3 b = (Vector3)((num4 > 1E-05f) ? new Vector3(num / num4, num2 / num4, num3 / num4) : Vector3.zero); if (!Same(val3, val4) || !Same(normalized, b)) { _disabled = true; Patcher.Log.LogWarning((object)FormattableString.Invariant($"TheComplexFastMeshAppend: result differs from Unity's math ({val3.x:R},{val3.y:R},{val3.z:R} vs {val4.x:R},{val4.y:R},{val4.z:R}); using The Complex's own code.")); return false; } _checked++; } return true; } private static int B(float f) { Bits bits = new Bits { F = f }; return bits.I; } private static bool Same(Vector3 a, Vector3 b) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0018: 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_0030: 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) if (B(a.x) == B(b.x) && B(a.y) == B(b.y)) { return B(a.z) == B(b.z); } return false; } private static void Reserve<T>(List<T> list, int extra) { int num = list.Count + extra; if (list.Capacity < num) { list.Capacity = Math.Max(num, list.Capacity * 2); } } } internal static class TheComplexTextures { private sealed class Entry { public string Path; public long SrcLen; public long SrcTicks; public int W; public int H; public int Filter; public int WrapU; public int WrapV; public int Aniso; public bool Srgb; public bool Mips; public bool Compressed; public bool Readable; public string Name; public byte[] Rgba; public int Format; public int MipCount; public byte[] Raw; } private const int SidecarMagic = 1112823875; private const int SidecarVersion = 1; private const int TexMagic = 826497090; private static MethodInfo _dirGetter; private static MethodInfo _original; private static int _fromSidecar; private static int _compressed; private static int _plain; private static long _tSet; private static long _tApplyMips; private static long _tCompress; private static long _tUpload; private static long _tSidecarLoad; private static long _bytes; private static readonly List<Task> Writes = new List<Task>(); private static long Now => Stopwatch.GetTimestamp(); private static double Ms(long ticks) { return (double)ticks * 1000.0 / (double)Stopwatch.Frequency; } internal static void Watch(Harmony h) { AppDomain.CurrentDomain.AssemblyLoad += delegate(object _, AssemblyLoadEventArgs e) { TryPatch(e.LoadedAssembly); }; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assemblies) { TryPatch(a); } void TryPatch(Assembly assembly) { //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown if (_original != null || assembly.GetName().Name != "BackroomsLevel0") { return; } try { Type type = assembly.GetType("BackroomsLevel0.TexCache", throwOnError: false); MethodInfo methodInfo = type?.GetMethod("LoadAll", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(IEnumerable<string>) }, null); MethodInfo methodInfo2 = type?.GetProperty("Dir", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetGetMethod(nonPublic: true); if (methodInfo == null || methodInfo2 == null || methodInfo.ReturnType != typeof(Dictionary<string, Texture2D>)) { Patcher.Log.LogInfo((object)"TheComplexTextureCache: The Complex's TexCache looks different in this version; not patching."); } else { _original = methodInfo; _dirGetter = methodInfo2; h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(TheComplexTextures), "LoadAllPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Patcher.Log.LogInfo((object)"TheComplexTextureCache: on"); } } catch (Exception ex) { Patcher.Log.LogWarning((object)("TheComplexTextureCache: not patched: " + ex.Message)); } } } private static bool LoadAllPrefix(IEnumerable<string> keys, ref Dictionary<string, Texture2D> __result) { try { __result = LoadAll(keys); return false; } catch (Exception ex) { Patcher.Log.LogWarning((object)("TheComplexTextureCache: falling back to The Complex's own loader: " + ex.Message)); return true; } } private static string FileOf(string dir, string key) { StringBuilder stringBuilder = new StringBuilder(); foreach (char c in key) { stringBuilder.Append((char.IsLetterOrDigit(c) || c == '_') ? c : '-'); } return Path.Combine(dir, stringBuilder?.ToString() + ".tex"); } private static Dictionary<string, Texture2D> LoadAll(IEnumerable<string> keys) { Stopwatch stopwatch = Stopwatch.StartNew(); string dir = (string)_dirGetter.Invoke(null, null); Dictionary<string, string> dictionary = new Dictionary<string, string>(); try { string[] array = File.ReadAllLines(Path.Combine(dir, "index.txt")); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0) { dictionary[text.Substring(0, num)] = text.Substring(num + 1); } } } catch (Exception) { } List<string> list = new List<string>(keys); List<string> names = new List<string>(); foreach (string item in list) { if (dictionary.TryGetValue(item, out var value) && !names.Contains(value)) { names.Add(value); } } Entry[] entries = new Entry[names.Count]; Parallel.For(0, names.Count, delegate(int num3) { try { entries[num3] = Read(FileOf(dir, names[num3])); } catch (Exception) { } }); long elapsedMilliseconds = stopwatch.ElapsedMilliseconds; Dictionary<string, Texture2D> dictionary2 = new Dictionary<string, Texture2D>(); for (int num2 = 0; num2 < names.Count; num2++) { Entry entry = entries[num2]; if (entry != null) { try { dictionary2[names[num2]] = ((entry.Raw != null) ? FromSidecar(entry) : Build(entry)); } catch (Exception ex2) { Patcher.Log.LogWarning((object)("[TexCache] '" + names[num2] + "' could not be restored: " + ex2.Message)); } } } Dictionary<string, Texture2D> dictionary3 = new Dictionary<string, Texture2D>(); foreach (string item2 in list) { if (dictionary.TryGetValue(item2, out var value2) && dictionary2.TryGetValue(value2, out var value3)) { dictionary3[item2] = value3; } } Patcher.Log.LogInfo((object)($"TheComplexTextureCache: {dictionary2.Count} textures in {stopwatch.ElapsedMilliseconds} ms " + $"({_fromSidecar} from pre-compressed cache, {_compressed} compressed now, {_plain} uncompressed; {_bytes / 1048576} MB RGBA). " + FormattableString.Invariant($"read+inflate {elapsedMilliseconds} ms, SetPixelData {Ms(_tSet):F0}, Apply+mips {Ms(_tApplyMips):F0}, Compress {Ms(_tCompress):F0}, final upload {Ms(_tUpload):F0}, sidecar load {Ms(_tSidecarLoad):F0} ms"))); return dictionary3; } private static Entry Read(string path) { if (!File.Exists(path)) { return null; } FileInfo fileInfo = new FileInfo(path); Entry entry = new Entry { Path = path, SrcLen = fileInfo.Length, SrcTicks = fileInfo.LastWriteTimeUtc.Ticks }; using FileStream stream = File.OpenRead(path); using DeflateStream input = new DeflateStream(stream, CompressionMode.Decompress); using BinaryReader binaryReader = new BinaryReader(input); if (binaryReader.ReadInt32() != 826497090) { return null; } entry.W = binaryReader.ReadInt32(); entry.H = binaryReader.ReadInt32(); entry.Srgb = binaryReader.ReadBoolean(); entry.Mips = binaryReader.ReadBoolean(); entry.Compressed = binaryReader.ReadBoolean(); entry.Readable = binaryReader.ReadBoolean(); entry.Filter = binaryReader.ReadInt32(); entry.WrapU = binaryReader.ReadInt32(); entry.WrapV = binaryReader.ReadInt32(); entry.Aniso = binaryReader.ReadInt32(); entry.Name = binaryReader.ReadString(); if (entry.Compressed && TryReadSidecar(entry)) { return entry; } int num = entry.W * entry.H * 4; entry.Rgba = binaryReader.ReadBytes(num); if (entry.Rgba.Length != num) { return null; } return entry; } private static string SidecarOf(Entry e) { return e.Path + ".dxt"; } private static bool TryReadSidecar(Entry e) { string path = SidecarOf(e); if (!File.Exists(path)) { return false; } try { using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)); if (binaryReader.ReadInt32() != 1112823875 || binaryReader.ReadInt32() != 1) { return false; } if (binaryReader.ReadInt64() != e.SrcLen || binaryReader.ReadInt64() != e.SrcTicks) { return false; } if (binaryReader.ReadInt32() != e.W || binaryReader.ReadInt32() != e.H) { return false; } e.Format = binaryReader.ReadInt32(); e.MipCount = binaryReader.ReadInt32(); int num = binaryReader.ReadInt32(); byte[] array = binaryReader.ReadBytes(num); if (array.Length != num) { return false; } e.Raw = array; return true; } catch (Exception) { return false; } } private static Texture2D FromSidecar(Entry e) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown Texture2D val = new Texture2D(e.W, e.H, (TextureFormat)e.Format, e.MipCount, !e.Srgb) { name = e.Name, filterMode = (FilterMode)e.Filter, wrapModeU = (TextureWrapMode)e.WrapU, wrapModeV = (TextureWrapMode)e.WrapV, anisoLevel = e.Aniso }; long now = Now; val.LoadRawTextureData(e.Raw); val.Apply(false, !e.Readable); _tSidecarLoad += Now - now; _fromSidecar++; return val; } private static Texture2D Build(Entry e) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown Texture2D val = new Texture2D(e.W, e.H, (TextureFormat)4, e.Mips, !e.Srgb) { name = e.Name }; long now = Now; val.SetPixelData<byte>(e.Rgba, 0, 0); _tSet += Now - now; _bytes += e.Rgba.Length; ((Texture)val).filterMode = (FilterMode)e.Filter; ((Texture)val).wrapModeU = (TextureWrapMode)e.WrapU; ((Texture)val).wrapModeV = (TextureWrapMode)e.WrapV; ((Texture)val).anisoLevel = e.Aniso; if (e.Compressed && e.W % 4 == 0 && e.H % 4 == 0) { now = Now; val.Apply(e.Mips, false); _tApplyMips += Now - now; now = Now; val.Compress(false); _tCompress += Now - now; SaveSidecar(e, val); now = Now; val.Apply(false, !e.Readable); _tUpload += Now - now; _compressed++; } else { now = Now; val.Apply(e.Mips, !e.Readable); _tApplyMips += Now - now; _plain++; } return val; } private static void SaveSidecar(Entry e, Texture2D tex) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected I4, but got Unknown int format = (int)tex.format; int mips = ((Texture)tex).mipmapCount; byte[] raw; try { raw = tex.GetRawTextureData(); } catch (Exception) { return; } string p = SidecarOf(e); Writes.Add(Task.Run(delegate { try { string text = p + ".part"; using (BinaryWriter binaryWriter = new BinaryWriter(File.Create(text))) { binaryWriter.Write(1112823875); binaryWriter.Write(1); binaryWriter.Write(e.SrcLen); binaryWriter.Write(e.SrcTicks); binaryWriter.Write(e.W); binaryWriter.Write(e.H); binaryWriter.Write(format); binaryWriter.Write(mips); binaryWriter.Write(raw.Length); binaryWriter.Write(raw); } if (File.Exists(p)) { File.Delete(p); } File.Move(text, p); } catch (Exception) { } })); } } public static class TypeIndex { private sealed class AsmIndex { public Type[] Types; public Dictionary<string, Type> ByFullName; public Dictionary<string, Type> ByName; } private static readonly Dictionary<Assembly, AsmIndex> Cache = new Dictionary<Assembly, AsmIndex>(); private static readonly object Lock = new object(); private static Assembly _harmonyAsm; private static Action<string> _harmonyWarn; private static long _lookups; private static long _misses; private static long _getTypes; private static long _indexed; private static long _indexedTypes; private static double _lookupMs; private static double _buildMs; private static readonly double TicksToMs = 1000.0 / (double)Stopwatch.Frequency; internal static void Install(Harmony h) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Expected O, but got Unknown _harmonyAsm = typeof(AccessTools).Assembly; SetupHarmonyWarn(); MethodInfo methodInfo = AccessTools.Method(typeof(AccessTools), "TypeByName", new Type[1] { typeof(string) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(AccessTools), "GetTypesFromAssembly", new Type[1] { typeof(Assembly) }, (Type[])null); h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(TypeIndex), "TypeByNamePrefix", (Type[])null) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(TypeIndex), "GetTypesFromAssemblyPrefix", (Type[])null) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Patcher.Log.LogInfo((object)"TypeLookupIndex: on"); } public static string Stats() { lock (Lock) { return FormattableString.Invariant($"TypeByName {_lookups} calls ({_misses} not found) in {_lookupMs:F0} ms, GetTypesFromAssembly {_getTypes} calls; indexed {_indexed} assemblies / {_indexedTypes} types in {_buildMs:F0} ms"); } } private static bool TypeByNamePrefix(string name, ref Type __result, bool __runOriginal) { if (!__runOriginal || name == null) { return __runOriginal; } long timestamp = Stopwatch.GetTimestamp(); bool result; try { Type type = Type.GetType(name, throwOnError: false); if (type == null && _harmonyAsm != null) { type = _harmonyAsm.GetType(name, throwOnError: false); } if (type == null) { type = Find(name, fullName: true) ?? Find(name, fullName: false); } if (type == null) { lock (Lock) { _misses++; } _harmonyWarn?.Invoke("AccessTools.TypeByName: Could not find type named " + name); } __result = type; result = false; } catch (Exception ex) { Patcher.Log.LogWarning((object)("TypeLookupIndex: lookup of '" + name + "' failed (" + ex.Message + "), using Harmony's own search")); result = true; } finally { lock (Lock) { _lookups++; _lookupMs += (double)(Stopwatch.GetTimestamp() - timestamp) * TicksToMs; } } return result; } private static bool GetTypesFromAssemblyPrefix(Assembly assembly, ref Type[] __result, bool __runOriginal) { if (!__runOriginal || assembly == null || assembly.IsDynamic) { return __runOriginal; } try { AsmIndex asmIndex = Get(assembly); __result = (Type[])asmIndex.Types.Clone(); lock (Lock) { _getTypes++; } return false; } catch (Exception ex) { Patcher.Log.LogWarning((object)("TypeLookupIndex: indexing " + assembly.GetName().Name + " failed (" + ex.Message + "), using Harmony's own path")); return true; } } private static Type Find(string name, bool fullName) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (assembly.FullName.StartsWith("Microsoft.VisualStudio")) { continue; } if (assembly.IsDynamic) { Type[] array = LoadableTypes(assembly, warn: true); foreach (Type type in array) { if ((fullName ? type.FullName : type.Name) == name) { return type; } } } else if (fullName && IsPlainName(name)) { Type type2 = null; try { type2 = assembly.GetType(name, throwOnError: false); } catch { } if (type2 != null && type2.FullName == name) { return type2; } } else { AsmIndex asmIndex = Maps(Get(assembly)); if ((fullName ? asmIndex.ByFullName : asmIndex.ByName).TryGetValue(name, out var value)) { return value; } } } return null; } private static bool IsPlainName(string name) { for (int i = 0; i < name.Length; i++) { bool flag; switch (name[i]) { case ' ': case '&': case '*': case ',': case '[': case '\\': case ']': case '`': flag = true; break; default: flag = false; break; } if (flag) { return false; } } return name.Length > 0; } private static AsmIndex Maps(AsmIndex idx) { lock (Lock) { if (idx.ByName != null) { return idx; } long timestamp = Stopwatch.GetTimestamp(); Dictionary<string, Type> dictionary = new Dictionary<string, Type>(idx.Types.Length, StringComparer.Ordinal); Dictionary<string, Type> dictionary2 = new Dictionary<string, Type>(idx.Types.Length, StringComparer.Ordinal); Type[] types = idx.Types; foreach (Type type in types) { string fullName = type.FullName; if (fullName != null && !dictionary.ContainsKey(fullName)) { dictionary[fullName] = type; } string name = type.Name; if (name != null && !dictionary2.ContainsKey(name)) { dictionary2[name] = type; } } idx.ByFullName = dictionary; idx.ByName = dictionary2; _buildMs += (double)(Stopwatch.GetTimestamp() - timestamp) * TicksToMs; return idx; } } private static AsmIndex Get(Assembly a) { lock (Lock) { if (Cache.TryGetValue(a, out var value)) { return value; } long timestamp = Stopwatch.GetTimestamp(); Type[] array = LoadableTypes(a, warn: true); value = new AsmIndex { Types = array }; Cache[a] = value; _indexed++; _indexedTypes += array.Length; _buildMs += (double)(Stopwatch.GetTimestamp() - timestamp) * TicksToMs; return value; } } private static Type[] LoadableTypes(Assembly a, bool warn) { try { return a.GetTypes(); } catch (ReflectionTypeLoadException ex) { if (warn) { _harmonyWarn?.Invoke($"AccessTools.GetTypesFromAssembly: assembly {a} => {ex}"); } return ex.Types.Where((Type t) => t != null).ToArray(); } } private static void SetupHarmonyWarn() { try { Type type = _harmonyAsm.GetType("HarmonyLib.Tools.Logger"); Type type2 = type?.GetNestedType("LogChannel"); MethodInfo log = type?.GetMethod("Log", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[2] { type2, typeof(Func<string>) }, null); if (log == null) { return; } object warn = Enum.Parse(type2, "Warn"); _harmonyWarn = delegate(string msg) { log.Invoke(null, new object[2] { warn, (Func<string>)(() => msg) }); }; } catch { } } } public static class MyPluginInfo { public const string PLUGIN_GUID = "BeegOptimizations.Preloader"; public const string PLUGIN_NAME = "BeegOptimizations"; public const string PLUGIN_VERSION = "1.0.0"; } }