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 LethalPerformance v1.5.3
BepInEx/plugins/LethalPerformance/LethalPerformance.dll
Decompiled 3 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dissonance; using Dissonance.Audio.Playback; using DunGen; using DunGen.Generation; using DunGen.Graph; using DunGenPlus.Generation; using DunGenPlus.Patches; using EasyTextEffects; using GameNetcodeStuff; using HarmonyLib; using HarmonyLib.Tools; using LethalLevelLoader; using LethalPerformance.Audio; using LethalPerformance.Caching; using LethalPerformance.Caching.References; using LethalPerformance.Configuration; using LethalPerformance.Dungen; using LethalPerformance.Extensions; using LethalPerformance.Patcher; using LethalPerformance.Patcher.API; using LethalPerformance.Patcher.Patches; using LethalPerformance.Patcher.Utilities; using LethalPerformance.Patches.Mods; using LethalPerformance.Unity; using LethalPerformance.Utilities; using LethalPerformance.Validation; using Microsoft.CodeAnalysis; using MonoMod.RuntimeDetour; using MonoMod.Utils; using NAudio.Wave; using TMPro; using Unity.AI.Navigation; using Unity.Burst.LowLevel; using Unity.Mathematics; using Unity.Netcode; using Unity.Profiling; using UnityEngine; using UnityEngine.Audio; using UnityEngine.EventSystems; using UnityEngine.InputSystem; using UnityEngine.Pool; using UnityEngine.ProBuilder; using UnityEngine.Profiling; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("DissonanceVoip")] [assembly: IgnoresAccessChecksTo("DunGen")] [assembly: IgnoresAccessChecksTo("DunGenPlus")] [assembly: IgnoresAccessChecksTo("EasyTextEffects")] [assembly: IgnoresAccessChecksTo("LethalLevelLoader")] [assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")] [assembly: IgnoresAccessChecksTo("UnityEngine.CoreModule")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalPerformance")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.5.3.0")] [assembly: AssemblyInformationalVersion("1.5.3+151346b169f2366a1dfd952cb9e5730d227c92ca")] [assembly: AssemblyProduct("LethalPerformance")] [assembly: AssemblyTitle("LethalPerformance")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.5.3.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [CompilerGenerated] internal unsafe delegate void <>f__AnonymousDelegate0(AudioMixerConstant* arg1, IntPtr arg2); [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [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 LethalPerformance { internal static class Dependencies { public const string MoreCompany = "me.swipez.melonloader.morecompany"; public const string Loadstone = "com.adibtw.loadstone"; public const string MoreSuits = "x753.More_Suits"; public const string LethalCompanyVR = "io.daxcess.lcvr"; public const string LethalLevelLoader = "imabatby.lethallevelloader"; public const string LobbyControl = "mattymatty.LobbyControl"; public const string LethalLib = "LethalLib"; public const string DawnLib = "com.github.teamxiaolan.dawnlib"; public const string DungenPlus = "dev.ladyalice.dungenplus"; public static bool IsModLoaded(string id) { if (!Chainloader.PluginInfos.ContainsKey(id)) { return Patch_Chainloader.IsModWillBeLoaded(id); } return true; } } [BepInPlugin("LethalPerformance", "LethalPerformance", "1.5.3")] public class LethalPerformancePlugin : BaseUnityPlugin { public static LethalPerformancePlugin Instance { get; private set; } internal ManualLogSource Logger { get; private set; } internal string WorkingDirectory { get; private set; } internal ConfigManager Configuration { get; private set; } internal Harmony? Harmony { get; private set; } internal ES3SaverTask ES3SaverTask { get; } = new ES3SaverTask(); protected void Awake() { Instance = this; Logger = ((BaseUnityPlugin)this).Logger; WorkingDirectory = new FileInfo(((BaseUnityPlugin)this).Info.Location).DirectoryName; Configuration = new ConfigManager(((BaseUnityPlugin)this).Config); LoadGameBurstLib(); InitializeHarmony(); CallInitializeOnAwake(); InitializeSaveScheduler(); LethalPerformancePatcher.OnModsLoaded += LethalPerformancePatcher_OnModsLoaded; } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void LethalPerformancePatcher_OnModsLoaded() { Harmony harmony = Harmony; if (Dependencies.IsModLoaded("imabatby.lethallevelloader")) { harmony.Unpatch((MethodBase)AccessTools.Method(typeof(DoorwayPairFinder), "GetDoorwayPairs", (Type[])null, (Type[])null), (HarmonyPatchType)1, "imabatby.lethallevelloader"); Patch_Dungeon.PatchAll(); harmony.PatchAll(typeof(Patch_LethalLevelLoader)); } if (Dependencies.IsModLoaded("dev.ladyalice.dungenplus")) { harmony.PatchAll(typeof(Patch_DungeonPlus)); } if (Dependencies.IsModLoaded("me.swipez.melonloader.morecompany")) { harmony.PatchAll(typeof(Patch_MoreCompany)); } if (Dependencies.IsModLoaded("x753.More_Suits")) { harmony.PatchAll(typeof(Patch_MoreSuits)); } } private void InitializeSaveScheduler() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown GameObject val = new GameObject("Lethal Performance Configuration Scheduler", new Type[1] { typeof(SaveScheduleComponent) }); ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val); } private void InitializeHarmony() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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_0008: 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_0021: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) LogChannel channelFilter = Logger.ChannelFilter; if ((channelFilter & 4) == 0) { Logger.ChannelFilter = (LogChannel)0; } Harmony = new Harmony("LethalPerformance"); try { Harmony.PatchAll(typeof(LethalPerformancePlugin).Assembly); } catch (Exception ex) { Logger.LogError((object)ex); } Logger.ChannelFilter = channelFilter; } private void CallInitializeOnAwake() { Type[] array = Array.Empty<Type>(); try { array = typeof(LethalPerformancePlugin).Assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { array = ex.Types.Where((Type t) => t != null).ToArray(); } foreach (MethodInfo item in from m in array.SelectMany((Type t) => t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) where ((MemberInfo)m).GetCustomAttribute<InitializeOnAwakeAttribute>() != null select m) { try { Logger.LogInfo((object)("Initializating " + GeneralExtensions.FullDescription((MethodBase)item))); item.Invoke(null, null); } catch (Exception ex2) { Logger.LogError((object)("Failed to initialize\n" + ex2)); } } } private void LoadGameBurstLib() { string text = Path.Combine(WorkingDirectory, "lib_burst_generated.data"); if (!File.Exists(text)) { Logger.LogFatal((object)"Failed to find \"lib_burst_generated.data\""); } else if (!BurstCompilerService.LoadBurstLibrary(text)) { Logger.LogFatal((object)"Failed to load burst library. Probably machine architecture is not x64 or CPU doesn't support AVX2 and SSE2 instructions"); } } } internal sealed class SaveScheduleComponent : MonoBehaviour { public void LateUpdate() { LethalPerformancePatcher.ConfigSaverTask.ScheduleSave(); LethalPerformancePlugin.Instance.ES3SaverTask.SaveIfDirty(); } public void OnDisable() { LethalPerformancePatcher.ConfigSaverTask.Save(); LethalPerformancePlugin.Instance.ES3SaverTask.SaveIfDirty(); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "LethalPerformance"; public const string PLUGIN_NAME = "LethalPerformance"; public const string PLUGIN_VERSION = "1.5.3"; } } namespace LethalPerformance.Validation { [HarmonyPatch(typeof(StartOfRound))] internal static class EntranceTeleportValidation { [HarmonyPatch("OnShipLandedMiscEvents")] [HarmonyPostfix] private static void ShowWarningTip() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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_001a: 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) Scene lastLoadedScene = SceneUtilities.GetLastLoadedScene(); if (!((Scene)(ref lastLoadedScene)).IsValid()) { return; } List<GameObject> list = default(List<GameObject>); PooledObject<List<GameObject>> val = CollectionPool<List<GameObject>, GameObject>.Get(ref list); try { List<EntranceTeleport> list2 = default(List<EntranceTeleport>); PooledObject<List<EntranceTeleport>> val2 = CollectionPool<List<EntranceTeleport>, EntranceTeleport>.Get(ref list2); try { ((Scene)(ref lastLoadedScene)).GetRootGameObjects(list); bool flag = false; foreach (GameObject item in list) { list2.Clear(); item.GetComponentsInChildren<EntranceTeleport>(list2); foreach (EntranceTeleport item2 in list2) { if (!((NetworkBehaviour)item2).IsSpawned) { flag = true; LethalPerformancePlugin.Instance.Logger.LogWarning((object)("Entrance is not spawned, path:" + ((Component)item2).transform.GetScenePath())); goto end_IL_00ae; } } continue; end_IL_00ae: break; } if (flag) { HUDManager.Instance.DisplayTip("Lethal Performance", "Entrance teleport mismatch. Expect 'The entrance appears to be blocked'.", true, false, "LP_ETBAD"); } } finally { ((IDisposable)val2/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)val/*cast due to .constrained prefix*/).Dispose(); } } } internal static class MixerConstantValidaton { internal static bool Enabled; public unsafe static void LogMixer(AudioMixerConstant* constant) { if (Enabled && constant != null) { StringBuilder stringBuilder = new StringBuilder(); LogCounts(stringBuilder, constant); LogGroupNames(stringBuilder, constant); LogGroups(stringBuilder, constant); LogEffects(stringBuilder, constant); LogExposed(stringBuilder, constant); LogSnapshots(stringBuilder, constant); LethalPerformancePlugin.Instance.Logger.LogInfo((object)stringBuilder.ToString()); } } private unsafe static void LogCounts(StringBuilder sb, AudioMixerConstant* c) { sb.Append("Counts: Groups=").Append(c->GroupCount.ToString(CultureInfo.InvariantCulture)).Append(" Effects=") .Append(c->EffectCount.ToString(CultureInfo.InvariantCulture)) .Append(" Snapshots=") .Append(c->SnapshotCount.ToString(CultureInfo.InvariantCulture)) .Append(" Exposed=") .Append(c->ExposedCount.ToString(CultureInfo.InvariantCulture)) .Append(" GroupNameBufSize=") .Append(c->GroupNameBufferSize.ToString(CultureInfo.InvariantCulture)) .AppendLine(); } private unsafe static void LogGroupNames(StringBuilder sb, AudioMixerConstant* c) { sb.Append("Group names: "); if (c->GroupNameBufferSize <= 0 || c->GroupNames.IsEmpty) { sb.Append("<empty>").AppendLine(); return; } string[] value = ReadPackedNames(OffsetPtrExtensions.Get(ref c->GroupNames), c->GroupNameBufferSize); sb.Append(string.Join(", ", value)).AppendLine(); } private unsafe static string[] ReadPackedNames(byte* names, int count) { string[] array = new string[count]; byte* ptr = names; for (int i = 0; i < count; i++) { array[i] = Marshal.PtrToStringAnsi((IntPtr)ptr) ?? string.Empty; ptr += Encoding.ASCII.GetByteCount(array[i]) + 1; } return array; } private unsafe static void LogGroups(StringBuilder sb, AudioMixerConstant* c) { sb.Append("Groups:").AppendLine(); if (c->GroupCount > 0 && !c->Groups.IsEmpty) { GroupConstant* ptr = OffsetPtrExtensions.Get(ref c->Groups); for (int i = 0; i < c->GroupCount; i++) { GroupConstant* ptr2 = ptr + i; sb.Append(" [").Append(i.ToString(CultureInfo.InvariantCulture)).Append("] ") .Append("parent=") .Append(ptr2->ParentConstantIndex.ToString(CultureInfo.InvariantCulture)) .Append(" volIndex=") .Append(ptr2->VolumeIndex.ToString(CultureInfo.InvariantCulture)) .Append(" pitchIndex=") .Append(ptr2->PitchIndex.ToString(CultureInfo.InvariantCulture)) .Append(" mute=") .Append(ptr2->Mute.ToString(CultureInfo.InvariantCulture)) .Append(" solo=") .Append(ptr2->Solo.ToString(CultureInfo.InvariantCulture)) .Append(" bypass=") .Append(ptr2->BypassEffects.ToString(CultureInfo.InvariantCulture)) .AppendLine(); } } } private unsafe static void LogEffects(StringBuilder sb, AudioMixerConstant* c) { sb.Append("Effects:").AppendLine(); if (c->EffectCount <= 0 || c->Effects.IsEmpty) { return; } EffectConstant* ptr = OffsetPtrExtensions.Get(ref c->Effects); for (int i = 0; i < c->EffectCount; i++) { EffectConstant* ptr2 = ptr + i; sb.Append(" [").Append(i.ToString(CultureInfo.InvariantCulture)).Append("] ") .Append("type=") .Append(ptr2->Type.ToString(CultureInfo.InvariantCulture)) .Append(" group=") .Append(ptr2->GroupConstantIndex.ToString(CultureInfo.InvariantCulture)) .Append(" send=") .Append(ptr2->SendTargetEffectIndex.ToString(CultureInfo.InvariantCulture)) .Append(" wet=") .Append(ptr2->WetMixLevelIndex.ToString(CultureInfo.InvariantCulture)) .Append(" prev=") .Append(ptr2->PrevEffectIndex.ToString(CultureInfo.InvariantCulture)) .Append(" bypass=") .Append(ptr2->Bypass.ToString(CultureInfo.InvariantCulture)) .Append(" paramCount=") .Append(ptr2->ParameterCount.ToString(CultureInfo.InvariantCulture)) .Append(" params=["); if (ptr2->ParameterCount > 0 && !ptr2->ParameterIndices.IsEmpty) { uint* ptr3 = OffsetPtrExtensions.Get(ref ptr2->ParameterIndices); for (int j = 0; j < ptr2->ParameterCount; j++) { if (j > 0) { sb.Append(','); } sb.Append(ptr3[j].ToString(CultureInfo.InvariantCulture)); } } sb.Append(']').AppendLine(); } } private unsafe static void LogExposed(StringBuilder sb, AudioMixerConstant* c) { sb.Append("Exposed:").AppendLine(); if (c->ExposedCount > 0) { uint* ptr = (c->ExposedHashes.IsEmpty ? null : OffsetPtrExtensions.Get(ref c->ExposedHashes)); uint* ptr2 = (c->ExposedIndices.IsEmpty ? null : OffsetPtrExtensions.Get(ref c->ExposedIndices)); for (int i = 0; i < c->ExposedCount; i++) { uint num = ((ptr != null) ? ptr[i] : 0u); uint num2 = ((ptr2 != null) ? ptr2[i] : 0u); sb.Append(" [").Append(i.ToString(CultureInfo.InvariantCulture)).Append("] hash=0x") .Append(num.ToString("X8", CultureInfo.InvariantCulture)) .Append(" index=") .Append(num2.ToString(CultureInfo.InvariantCulture)) .AppendLine(); } } } private unsafe static void LogSnapshots(StringBuilder sb, AudioMixerConstant* c) { sb.Append("Snapshots:").AppendLine(); if (c->SnapshotCount <= 0 || c->Snapshots.IsEmpty) { return; } SnapshotConstant* ptr = OffsetPtrExtensions.Get(ref c->Snapshots); for (int i = 0; i < c->SnapshotCount; i++) { SnapshotConstant* ptr2 = ptr + i; sb.Append(" [").Append(i.ToString(CultureInfo.InvariantCulture)).Append("] hash=0x") .Append(ptr2->NameHash.ToString("X8", CultureInfo.InvariantCulture)) .Append(" valueCount=") .Append(ptr2->ValueCount.ToString(CultureInfo.InvariantCulture)) .Append(" transitionCount=") .Append(ptr2->TransitionCount.ToString(CultureInfo.InvariantCulture)) .AppendLine(); if (ptr2->ValueCount <= 0 || ptr2->Values.IsEmpty) { continue; } float* ptr3 = OffsetPtrExtensions.Get(ref ptr2->Values); for (int j = 0; j < ptr2->ValueCount; j += 12) { int num = Math.Min(j + 12, ptr2->ValueCount); sb.Append(" [").Append(j.ToString(CultureInfo.InvariantCulture)).Append("..") .Append((num - 1).ToString(CultureInfo.InvariantCulture)) .Append("] "); for (int k = j; k < num; k++) { if (k > j) { sb.Append(", "); } sb.Append(ptr3[k].ToString("G6", CultureInfo.InvariantCulture)); } sb.AppendLine(); } } } } } namespace LethalPerformance.Utilities { internal static class CRC32 { private static readonly uint[] s_CrcTable = CreateCrcTable(); public static uint Crc32Ascii(string value) { uint num = uint.MaxValue; for (int i = 0; i < value.Length; i++) { num = s_CrcTable[(num ^ (byte)value[i]) & 0xFF] ^ (num >> 8); } return num ^ 0xFFFFFFFFu; } private static uint[] CreateCrcTable() { uint[] array = new uint[256]; for (uint num = 0u; num < 256; num++) { uint num2 = num; for (int i = 0; i < 8; i++) { num2 = (((num2 & 1) != 0) ? ((num2 >> 1) ^ 0xEDB88320u) : (num2 >> 1)); } array[num] = num2; } return array; } } internal class ES3SaverTask { private readonly HashSet<ES3File> m_ChangedSaves = new HashSet<ES3File>(); public void ScheduleSaveFor(ES3File file) { m_ChangedSaves.Add(file); } public void SaveIfDirty() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown if (m_ChangedSaves.Count == 0) { return; } int num = 0; foreach (ES3File changedSafe in m_ChangedSaves) { if (!TryGetPath(changedSafe, out string path)) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)"Got unknown cached save"); continue; } num++; changedSafe.Sync(new ES3Settings(path, (ES3Settings)null) { encryptionType = (EncryptionType)1, _location = (Location)0 }); } LethalPerformancePlugin.Instance.Logger.LogInfo((object)$"Saved {num} save(s)"); m_ChangedSaves.Clear(); } private static bool TryGetPath(ES3File file, out string? path) { foreach (KeyValuePair<string, ES3File> cachedFile in ES3File.cachedFiles) { if (cachedFile.Value == file) { path = cachedFile.Key; return true; } } path = null; return false; } } internal static class HDCameraFrameSettingsOptimizer { private static readonly FrameSettingsField[] s_DisabledExtraCameraFields; public static void ApplyExtraCameraFrameSettings(HDAdditionalCameraData data) { //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_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected I4, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) data.customRenderingSettings = true; data.probeLayerMask = LayerMask.op_Implicit(0); ref FrameSettingsOverrideMask renderingPathCustomFrameSettingsOverrideMask = ref data.renderingPathCustomFrameSettingsOverrideMask; ref FrameSettings renderingPathCustomFrameSettings = ref data.renderingPathCustomFrameSettings; FrameSettingsField[] array = s_DisabledExtraCameraFields; foreach (FrameSettingsField val in array) { ((BitArray128)(ref renderingPathCustomFrameSettingsOverrideMask.mask))[(uint)(int)val] = true; ((FrameSettings)(ref renderingPathCustomFrameSettings)).SetEnabled(val, false); } } static HDCameraFrameSettingsOptimizer() { FrameSettingsField[] array = new FrameSettingsField[32]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); s_DisabledExtraCameraFields = (FrameSettingsField[])(object)array; } } internal static class HDRenderPipelineAssetOptimizer { [InitializeOnAwake] public static void Initialize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_000c: 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_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_004d: 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) HDRenderPipelineAsset val = (HDRenderPipelineAsset)GraphicsSettings.currentRenderPipeline; RenderPipelineSettings currentPlatformRenderPipelineSettings = val.currentPlatformRenderPipelineSettings; currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionProbeTexCacheSize = LethalPerformancePlugin.Instance.Configuration.ReflectionProbeCacheResolution.Value; currentPlatformRenderPipelineSettings.lightLoopSettings.cookieAtlasSize = (CookieAtlasResolution)LethalPerformancePlugin.Instance.Configuration.CookieAtlasResolution.Value; currentPlatformRenderPipelineSettings.supportDataDrivenLensFlare = false; bool flag = (currentPlatformRenderPipelineSettings.supportVolumetrics = SystemInfo.supportsRenderTargetArrayIndexFromVertexShader); val.currentPlatformRenderPipelineSettings = currentPlatformRenderPipelineSettings; HDRenderPipelineGlobalSettings instance = HDRenderPipelineGlobalSettings.instance; instance.rendererListCulling = true; instance.supportRuntimeDebugDisplay = false; ref FrameSettings defaultFrameSettings = ref instance.GetDefaultFrameSettings((FrameSettingsRenderType)0); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)80, false); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)1, true); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)21, false); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)35, false); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)97, false); if (!flag) { ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)28, false); LethalPerformancePlugin.Instance.Logger.LogInfo((object)"Disabled volumetric fog as hardware system doesn't support it"); } } } internal static class NetworkManagerUtilities { public static void FindAllSpawnedNetworkBehaviour<T>(List<T> spawnedObjects) where T : Object { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || singleton.SpawnManager == null) { return; } foreach (NetworkObject spawnedObjects2 in singleton.SpawnManager.SpawnedObjectsList) { if ((Object)(object)spawnedObjects2 == (Object)null) { continue; } foreach (NetworkBehaviour childNetworkBehaviour in spawnedObjects2.ChildNetworkBehaviours) { T val = (T)(object)((childNetworkBehaviour is T) ? childNetworkBehaviour : null); if (val != null && childNetworkBehaviour.IsSpawned && !((Object)(object)childNetworkBehaviour.NetworkObject != (Object)(object)spawnedObjects2)) { spawnedObjects.Add(val); } } } } } internal class OpenLogsFolderKeybind { private static InputActionAsset? s_InputActions; [InitializeOnAwake] private static void Initialize() { //IL_004b: 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_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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_0087: Unknown result type (might be due to invalid IL or missing references) InputActionAsset val = (s_InputActions = ScriptableObject.CreateInstance<InputActionAsset>()); ((Object)val).name = "LethalPerformance Input Asset"; ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val); InputActionMap val2 = InputActionSetupExtensions.AddActionMap(val, "LPActionMap"); InputAction val3 = InputActionSetupExtensions.AddAction(val2, "General", (InputActionType)1, (string)null, (string)null, (string)null, (string)null, (string)null); CompositeSyntax val4 = InputActionSetupExtensions.AddCompositeBinding(val3, "TwoModifiers", (string)null, (string)null); val4 = ((CompositeSyntax)(ref val4)).With("Binding", "<Keyboard>/l", (string)null, (string)null); val4 = ((CompositeSyntax)(ref val4)).With("Modifier1", "<Keyboard>/ctrl", (string)null, (string)null); ((CompositeSyntax)(ref val4)).With("Modifier2", "<Keyboard>/shift", (string)null, (string)null); val3.performed += OnOpenLogsPressed; SceneManager.activeSceneChanged += SceneManager_activeSceneChanged; } private static void SceneManager_activeSceneChanged(Scene arg0, Scene arg1) { SceneManager.activeSceneChanged -= SceneManager_activeSceneChanged; if ((Object)(object)s_InputActions != (Object)null) { s_InputActions.Enable(); } } private static void OnOpenLogsPressed(CallbackContext obj) { if (!((Object)(object)GameNetworkManager.Instance != (Object)null) || !((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null) || !GameNetworkManager.Instance.localPlayerController.isTypingChat) { Application.OpenURL("\"" + Application.persistentDataPath + "\""); } } } internal static class SceneUtilities { public static bool IsDontDestroyOnLoad(this Scene scene) { return ((Scene)(ref scene)).buildIndex == -1; } public static bool IsMainMenu(this Scene scene) { return ((Scene)(ref scene)).name == "MainMenu"; } public static bool IsSceneShip(this Scene scene) { return ((Scene)(ref scene)).name == "SampleSceneRelay"; } public static Scene GetLastLoadedScene() { //IL_0016: 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_0011: Unknown result type (might be due to invalid IL or missing references) int sceneCount = SceneManager.sceneCount; if (sceneCount == 0) { return default(Scene); } return SceneManager.GetSceneAt(sceneCount - 1); } } } namespace LethalPerformance.Patches { [HarmonyPatch(typeof(CreateObjectMessage))] internal static class Patch_CreateObjectMessage { private const byte c_Ok = 0; private const byte c_OkNoData = 1; private const byte c_Error = 2; private const int c_Priority = 399; private static readonly List<ushort> s_Indicies = new List<ushort>(); [HarmonyPatch("Serialize")] [HarmonyPriority(399)] [HarmonyPostfix] private static void Serialize(CreateObjectMessage __instance, FastBufferWriter writer) { //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) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) if (!TryGetGrabbableObject(__instance.ObjectInfo, out GrabbableObject grabbableObject)) { return; } if (Patch_RoundManager.s_AssignedRandomSpawn.TryGetValue(grabbableObject, out RandomScrapSpawn value) && !((Object)(object)value == (Object)null) && value.spawnedItemsCopyPosition && !((Object)(object)value.spawnWithParent == (Object)null)) { NetworkObject componentInParent = ((Component)value).GetComponentInParent<NetworkObject>(); if (!((Object)(object)componentInParent == (Object)null) && componentInParent.IsSpawned && !((Object)(object)((Component)componentInParent).transform.parent != (Object)null)) { s_Indicies.Clear(); Transform val = ((Component)value).transform; while (true) { if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)((Component)componentInParent).transform) { int siblingIndex = val.GetSiblingIndex(); if (siblingIndex > 65535) { break; } s_Indicies.Add((ushort)siblingIndex); val = val.parent; continue; } if ((Object)(object)val != (Object)(object)((Component)componentInParent).transform || s_Indicies.Count > 65535) { break; } s_Indicies.Reverse(); ((FastBufferWriter)(ref writer)).WriteByteSafe((byte)0); NetworkObjectReference val2 = NetworkObjectReference.op_Implicit(componentInParent); ((FastBufferWriter)(ref writer)).WriteNetworkSerializable<NetworkObjectReference>(ref val2); ushort num = (ushort)s_Indicies.Count; ((FastBufferWriter)(ref writer)).WriteValueSafe<ushort>(ref num, default(ForPrimitives)); foreach (ushort s_Indicy in s_Indicies) { ushort current = s_Indicy; ((FastBufferWriter)(ref writer)).WriteValueSafe<ushort>(ref current, default(ForPrimitives)); } return; } } ((FastBufferWriter)(ref writer)).WriteByteSafe((byte)2); } else { ((FastBufferWriter)(ref writer)).WriteByteSafe((byte)1); } } [HarmonyPatch("Deserialize")] [HarmonyPriority(399)] [HarmonyPostfix] public static void Handle(CreateObjectMessage __instance, bool __result) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_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_0072: 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_0093: 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) if (!__result || !TryGetGrabbableObject(__instance.ObjectInfo, out GrabbableObject grabbableObject)) { return; } FastBufferReader receivedNetworkVariableData = __instance.m_ReceivedNetworkVariableData; if (((FastBufferReader)(ref receivedNetworkVariableData)).Length - ((FastBufferReader)(ref receivedNetworkVariableData)).Position <= 0) { return; } byte b = default(byte); ((FastBufferReader)(ref receivedNetworkVariableData)).ReadByteSafe(ref b); switch (b) { case 1: Patch_RoundManager.s_AssignedRandomSpawn.AddOrUpdate(grabbableObject, null); break; case 0: { NetworkObjectReference val = default(NetworkObjectReference); ((FastBufferReader)(ref receivedNetworkVariableData)).ReadNetworkSerializable<NetworkObjectReference>(ref val); NetworkObject val2 = default(NetworkObject); if (!((NetworkObjectReference)(ref val)).TryGet(ref val2, (NetworkManager)null) || (Object)(object)val2 == (Object)null) { break; } ushort num = default(ushort); ((FastBufferReader)(ref receivedNetworkVariableData)).ReadValueSafe<ushort>(ref num, default(ForPrimitives)); Transform val3 = ((Component)val2).transform; ushort num2 = default(ushort); for (int i = 0; i < num; i++) { ((FastBufferReader)(ref receivedNetworkVariableData)).ReadValueSafe<ushort>(ref num2, default(ForPrimitives)); if (num2 >= val3.childCount) { return; } val3 = val3.GetChild((int)num2); } RandomScrapSpawn component = ((Component)val3).GetComponent<RandomScrapSpawn>(); if (!((Object)(object)component == (Object)null)) { Patch_RoundManager.s_AssignedRandomSpawn.Add(grabbableObject, component); } break; } } } private static bool TryGetGrabbableObject(SceneObject info, [NotNullWhen(true)] out GrabbableObject? grabbableObject) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) NetworkManager singleton = NetworkManager.Singleton; if (singleton.SpawnManager.SpawnedObjects.TryGetValue(info.NetworkObjectId, out var value)) { List<NetworkBehaviour> childNetworkBehaviours = value.ChildNetworkBehaviours; if (childNetworkBehaviours != null && childNetworkBehaviours.Count > 0) { NetworkBehaviour? obj = value.ChildNetworkBehaviours.Find((NetworkBehaviour b) => b is GrabbableObject); grabbableObject = (GrabbableObject?)(object)((obj is GrabbableObject) ? obj : null); return (Object)(object)grabbableObject != (Object)null; } } grabbableObject = null; return false; } } [HarmonyPatch(typeof(CustomPassVolume))] internal static class Patch_CustomPassVolume { [HarmonyPatch("Cull")] [HarmonyPrefix] public static bool Cull(out CullingResults? __result) { __result = null; return false; } } [HarmonyPatch(typeof(FoliageDetailDistance))] internal static class Patch_FoliageDetailDistance { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("Update")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> RemoveMaterialCheck(IEnumerable<CodeInstruction> instructions) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected O, but got Unknown //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); FieldInfo field = typeof(FoliageDetailDistance).GetField("allBushRenderers", AccessTools.all); CodeMatch[] matches = (CodeMatch[])(object)new CodeMatch[10] { new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, "start"), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)field, (string)null), new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Brfalse, (object)null, (string)null) }; val.MatchForward(false, matches).Repeat((Action<CodeMatcher>)delegate(CodeMatcher match) { match.RemoveInstructions(matches.Length); CodeInstructionExtensions.MoveLabelsTo(match.NamedMatch("start"), match.Instruction); }, (Action<string>)null); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(FrameSkipDetector))] internal static class Patch_FrameSkipDetector { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("IsFrameSkip")] [HarmonyPrefix] public static bool DisableCapturePipelineResetOnFrameSkip(ref bool __result) { __result = false; return false; } } [HarmonyPatch(typeof(GrabbableObject))] internal static class Patch_GrabbableObject { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("Start")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> UseCachedRandomSpawnScrap(IEnumerable<CodeInstruction> instructions) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); MethodInfo findObjectOfTypeMethod = typeof(Object).GetMethod("FindObjectsOfType", 1, AccessTools.all, null, CallingConventions.Any, Array.Empty<Type>(), Array.Empty<ParameterModifier>()).MakeGenericMethod(typeof(RandomScrapSpawn)); val.SearchForward((Func<CodeInstruction, bool>)((CodeInstruction c) => CodeInstructionExtensions.Calls(c, findObjectOfTypeMethod))).Operand = SymbolExtensions.GetMethodInfo((LambdaExpression)(Expression<Func<Func<GrabbableObject, RandomScrapSpawn[]>>>)(() => GetAssignedRandomScrapSpawn)); val.Insert((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldarg_0, (object)null) }); return val.InstructionEnumeration(); } public static RandomScrapSpawn[] GetAssignedRandomScrapSpawn(GrabbableObject item) { if (Patch_RoundManager.s_AssignedRandomSpawn.TryGetValue(item, out RandomScrapSpawn value)) { Patch_RoundManager.s_AssignedRandomSpawn.Remove(item); if ((Object)(object)value != (Object)null) { LethalPerformancePlugin.Instance.Logger.LogDebug((object)((item?.itemProperties?.itemName ?? "NULL") + " used random scrap spawn")); return (RandomScrapSpawn[])(object)new RandomScrapSpawn[1] { value }; } return Array.Empty<RandomScrapSpawn>(); } if (!NetworkManager.Singleton.IsHost) { return Object.FindObjectsByType<RandomScrapSpawn>((FindObjectsInactive)0, (FindObjectsSortMode)0); } return Array.Empty<RandomScrapSpawn>(); } } [HarmonyPatch(typeof(HangarShipDoor))] internal static class Patch_HangarShipDoor { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("Update")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> FixFormatAllocation(IEnumerable<CodeInstruction> instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Box, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null) }).SetInstructionAndAdvance(new CodeInstruction(OpCodes.Conv_R4, (object)null)).RemoveInstruction() .Set(OpCodes.Call, (object)typeof(TMP_Text).GetMethod("SetText", new Type[2] { typeof(string), typeof(float) })); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(HDAdditionalCameraData))] internal static class Patch_HDAdditionalCameraData { [HarmonyPatch("RegisterDebug")] [HarmonyPrefix] public static bool DisableRegisteringDebugData() { return false; } } [HarmonyPatch(typeof(HDCachedShadowAtlas))] internal static class Patch_HDCachedShadowAtlas { private sealed class AtlasState { public readonly HashSet<int> FailedLightIds = new HashSet<int>(); public bool ForceFullPack = true; } private static readonly ConditionalWeakTable<HDCachedShadowAtlas, AtlasState> s_States = new ConditionalWeakTable<HDCachedShadowAtlas, AtlasState>(); [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } private static AtlasState GetState(HDCachedShadowAtlas atlas) { return s_States.GetValue(atlas, (HDCachedShadowAtlas _) => new AtlasState()); } [HarmonyPrefix] [HarmonyPatch("AssignOffsetsInAtlas")] public static bool AssignOffsetsInAtlas(HDCachedShadowAtlas __instance, HDShadowInitParameters initParameters) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) Dictionary<int, HDAdditionalLightData> registeredLightDataPendingPlacement = __instance.m_RegisteredLightDataPendingPlacement; if (registeredLightDataPendingPlacement.Count == 0 || !__instance.m_CanTryPlacement) { return false; } AtlasState state = GetState(__instance); List<CachedShadowRecord> tempListForPlacement = __instance.m_TempListForPlacement; tempListForPlacement.Clear(); if (state.ForceFullPack) { state.FailedLightIds.Clear(); tempListForPlacement.AddRange(__instance.m_RecordsPendingPlacement.Values); __instance.AddLightListToRecordList(registeredLightDataPendingPlacement, initParameters, ref tempListForPlacement); state.ForceFullPack = false; } else { AddLightsNotYetFailed(__instance, registeredLightDataPendingPlacement, initParameters, state.FailedLightIds); if (tempListForPlacement.Count == 0) { __instance.m_CanTryPlacement = false; return false; } } if (__instance.m_NeedOptimalPacking) { __instance.InsertionSort(ref tempListForPlacement, 0, tempListForPlacement.Count); __instance.m_NeedOptimalPacking = false; } __instance.PerformPlacement(); __instance.m_CanTryPlacement = false; foreach (int key in registeredLightDataPendingPlacement.Keys) { state.FailedLightIds.Add(key); } return false; } [HarmonyPrefix] [HarmonyPatch("InitAtlas")] public static void InitAtlas(HDCachedShadowAtlas __instance) { AtlasState state = GetState(__instance); state.FailedLightIds.Clear(); state.ForceFullPack = true; } [HarmonyPrefix] [HarmonyPatch("EvictLight")] public static void EvictLight(HDCachedShadowAtlas __instance, HDAdditionalLightData lightData) { int lightIdxForCachedShadows = lightData.lightIdxForCachedShadows; if (lightIdxForCachedShadows >= 0 && __instance.m_PlacedShadows.ContainsKey(lightIdxForCachedShadows)) { AtlasState state = GetState(__instance); state.FailedLightIds.Clear(); state.ForceFullPack = true; } } [HarmonyPrefix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] public unsafe static bool FindSlotInAtlas(HDCachedShadowAtlas __instance, int resolution, bool tempFill, out int x, out int y, ref bool __result) { int num = HDUtils.DivRoundUp(resolution, 64); int atlasResolutionInSlots = __instance.m_AtlasResolutionInSlots; int num2 = atlasResolutionInSlots - num; if (num2 < 0) { x = 0; y = 0; __result = false; return false; } List<SlotValue> atlasSlots = __instance.m_AtlasSlots; bool flag; fixed (SlotValue* ptr = NoAllocHelpers.ExtractArrayFromListT<SlotValue>(atlasSlots)) { int count = atlasSlots.Count; flag = CachedShadowAtlasBurst.FindFreeSlot((byte*)ptr, ref count, ref atlasResolutionInSlots, ref num, ref x, ref y); } if (!flag) { x = 0; y = 0; __result = false; return false; } if (tempFill) { __instance.MarkEntries(x, y, num, (SlotValue)2); } __result = true; return false; } [HarmonyPrefix] [HarmonyPatch("PlaceMultipleShadows")] public unsafe static bool PlaceMultipleShadows(HDCachedShadowAtlas __instance, int startIdx, int numberOfShadows, ref bool __result) { //IL_0007: 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_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) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0116: 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_0102: Unknown result type (might be due to invalid IL or missing references) int viewportSize = __instance.m_TempListForPlacement[startIdx].viewportSize; int num = HDUtils.DivRoundUp(viewportSize, 64); Span<Vector2Int> span = new Span<Vector2Int>(stackalloc Vector2Int[6], 6); Span<Vector2Int> span2 = span; int num2 = 0; int num3 = default(int); int num4 = default(int); for (int i = 0; i < numberOfShadows && __instance.GetSlotInAtlas(__instance.m_TempListForPlacement[startIdx + i].viewportSize, ref num3, ref num4); i++) { span2[i] = new Vector2Int(num3, num4); num2++; } if (num2 == numberOfShadows) { for (int j = 0; j < numberOfShadows; j++) { CachedShadowRecord val = __instance.m_TempListForPlacement[startIdx + j]; val.offsetInAtlas = new Vector4((float)(((Vector2Int)(ref span2[j])).x * 64), (float)(((Vector2Int)(ref span2[j])).y * 64), (float)((Vector2Int)(ref span2[j])).x, (float)((Vector2Int)(ref span2[j])).y); if (val.rendersOnPlacement) { __instance.m_ShadowsPendingRendering.Add(val.shadowIndex, val); } __instance.m_PlacedShadows.Add(val.shadowIndex, val); } __result = true; return false; } if (num2 > 0) { for (int k = 0; k < num2; k++) { __instance.MarkEntries(((Vector2Int)(ref span2[k])).x, ((Vector2Int)(ref span2[k])).y, num, (SlotValue)0); } } __result = false; return false; } private static void AddLightsNotYetFailed(HDCachedShadowAtlas atlas, Dictionary<int, HDAdditionalLightData> lightList, HDShadowInitParameters initParams, HashSet<int> failedLightIds) { //IL_002e: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Invalid comparison between Unknown and I4 //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: 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) foreach (HDAdditionalLightData value in lightList.Values) { int lightIdxForCachedShadows = value.lightIdxForCachedShadows; if (!failedLightIds.Contains(lightIdxForCachedShadows)) { int resolutionFromSettings = value.GetResolutionFromSettings(atlas.m_ShadowType, initParams); int num = (((int)value.type != 2) ? 1 : 6); for (int i = 0; i < num; i++) { CachedShadowRecord item = new CachedShadowRecord { shadowIndex = lightIdxForCachedShadows + i, viewportSize = resolutionFromSettings, offsetInAtlas = new Vector4(-1f, -1f, -1f, -1f), rendersOnPlacement = ((int)value.shadowUpdateMode != 2 || value.forceRenderOnPlacement || value.onDemandShadowRenderOnPlacement) }; value.forceRenderOnPlacement = false; atlas.m_TempListForPlacement.Add(item); } } } } } [HarmonyPatch(typeof(HDCamera))] internal static class Patch_HDCamera { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPrefix] [HarmonyPatch("UpdateShaderVariablesXRCB")] public unsafe static bool Prefix(HDCamera __instance, ref ShaderVariablesXR cb) { fixed (ShaderVariablesXR* ptr = &cb) { void* ptr2 = ptr; fixed (ViewConstants* xRViewConstants = __instance.m_XRViewConstants) { void* ptr3 = xRViewConstants; ReadableViewConstants* ptr4 = (ReadableViewConstants*)ptr3; int viewCount = __instance.viewCount; CameraBurst.UpdateShaderVariablesXRCB(ref ptr4, ref viewCount, (ReadableShaderVariablesXR*)ptr2); return false; } } } [HarmonyPrefix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] public unsafe static bool UpdateShaderVariablesGlobalCB(HDCamera __instance, ref ShaderVariablesGlobal cb, int frameCount) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: 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_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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_0068: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: 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_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: 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_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_0146: 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_012b: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0163: 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_015c: 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_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) fixed (ShaderVariablesGlobal* ptr = &cb) { void* ptr2 = ptr; fixed (ViewConstants* mainViewConstants = &__instance.mainViewConstants) { void* ptr3 = mainViewConstants; fixed (Vector4* frustumPlaneEquations = __instance.frustumPlaneEquations) { void* ptr4 = frustumPlaneEquations; float4x4 val = default(float4x4); ((float4x4)(ref val))..ctor(float4.op_Implicit(__instance.screenSize), float4.op_Implicit(__instance.postProcessScreenSize), float4.op_Implicit(RTHandles.rtHandleProperties.rtHandleScale), float4.op_Implicit(__instance.m_HistoryRTSystem.rtHandleProperties.rtHandleScale)); float4x4 val2 = default(float4x4); ((float4x4)(ref val2))..ctor(float4.op_Implicit(__instance.m_PostProcessRTScales), float4.op_Implicit(__instance.m_PostProcessRTScalesHistory), new float4((float)__instance.actualWidth, ((Rect)(ref __instance.finalViewport)).width, (float)__instance.actualHeight, ((Rect)(ref __instance.finalViewport)).height), float4.op_Implicit(__instance.zBufferParams)); float4x4 val3 = default(float4x4); ((float4x4)(ref val3))..ctor(float4.op_Implicit(__instance.projectionParams), float4.op_Implicit(__instance.unity_OrthoParams), float4.op_Implicit(__instance.screenParams), float4.op_Implicit(__instance.taaJitter)); bool flag = (Object)(object)__instance.m_AdditionalCameraData == (Object)null; float num = (flag ? 1f : __instance.m_AdditionalCameraData.deExposureMultiplier); float4 val4 = (float4)(flag ? new float4(1f, 1f, 0f, 0f) : float4.op_Implicit(__instance.m_AdditionalCameraData.screenCoordScaleBias)); float4 val5 = (flag ? float4.zero : float4.op_Implicit(__instance.m_AdditionalCameraData.screenSizeOverride)); FrameSettings frameSettings = __instance.frameSettings; AntialiasingMode antialiasing = __instance.antialiasing; CameraType cameraType = __instance.camera.cameraType; ReadableViewConstants* ptr5 = (ReadableViewConstants*)ptr3; float4* ptr6 = (float4*)ptr4; ref float taaSharpenStrength = ref __instance.taaSharpenStrength; ref int taaFrameIndex = ref __instance.taaFrameIndex; ref int colorPyramidHistoryMipCount = ref __instance.colorPyramidHistoryMipCount; float globalMipBias = __instance.globalMipBias; ref float time = ref __instance.time; ref float lastTime = ref __instance.lastTime; int viewCount = __instance.viewCount; float probeRangeCompressionFactor = __instance.probeRangeCompressionFactor; bool flag2 = !flag; CameraBurst.UpdateShaderVariablesGlobalCB((ReadableShaderVariablesGlobal*)ptr2, ref frameSettings, ref antialiasing, ref cameraType, ref ptr5, ref val, ref val2, ref val3, ref ptr6, ref taaSharpenStrength, ref taaFrameIndex, ref colorPyramidHistoryMipCount, ref globalMipBias, ref time, ref lastTime, ref frameCount, ref viewCount, ref probeRangeCompressionFactor, ref num, ref val4, ref flag2, ref val5); return false; } } } } } [HarmonyPatch(typeof(HDRenderPipeline))] internal static class Patch_HDRenderPipeline { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPrefix] [HarmonyPatch("ApplyCameraMipBias")] [HarmonyPatch("ResetCameraMipBias")] public static bool SkipApplyCameraMipBias(HDCamera hdCamera) { return hdCamera.globalMipBias != 0f; } } [HarmonyPatch(typeof(PlayerControllerB))] internal static class Patch_PlayerControllerB { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPrefix] [HarmonyPatch("ShowNameBillboard")] public static bool FixLocalBillBoardIsEnabling(PlayerControllerB __instance, bool __runOriginal) { if (!__runOriginal) { return __runOriginal; } bool flag = (Object)(object)__instance == (Object)(object)StartOfRound.Instance.localPlayerController; return !flag; } } [HarmonyPatch(typeof(RoundManager))] internal static class Patch_RoundManager { internal static readonly ConditionalWeakTable<GrabbableObject, RandomScrapSpawn?> s_AssignedRandomSpawn = new ConditionalWeakTable<GrabbableObject, RandomScrapSpawn>(); private static RandomScrapSpawn? s_RandomScrapSpawn; [HarmonyCleanup] private static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("SpawnScrapInLevel")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> CatchRandomScrapSpawn(IEnumerable<CodeInstruction> instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Expected O, but got Unknown //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Expected O, but got Unknown //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Expected O, but got Unknown //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); LocalBuilder localBuilder = val.SearchForward((Func<CodeInstruction, bool>)((CodeInstruction ci) => ci.operand is LocalBuilder localBuilder3 && localBuilder3.LocalType == typeof(RandomScrapSpawn))).ThrowIfInvalid("Failed to find localbuilder of RandomScrapSpawn").Operand as LocalBuilder; FieldInfo field = typeof(RandomScrapSpawn).GetField("spawnWithParent", AccessTools.all); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[6] { new CodeMatch((OpCode?)OpCodes.Ldloc_S, (object)localBuilder, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)field, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Stloc_S, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Br, (object)null, (string)null) }).ThrowIfInvalid("Failed to find patch point").Insert((CodeInstruction[])(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldloc, (object)localBuilder), CodeInstruction.Call((LambdaExpression)(Expression<Func<Action<RandomScrapSpawn>>>)(() => CaptureScrapSpawn)) }); LocalBuilder localBuilder2 = val.SearchForward((Func<CodeInstruction, bool>)((CodeInstruction ci) => ci.operand is LocalBuilder localBuilder3 && localBuilder3.LocalType == typeof(GrabbableObject))).ThrowIfInvalid("Failed to find localbuilder of GrabbableObject").Operand as LocalBuilder; val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldloc_S, (object)localBuilder2, (string)null) }).Insert((CodeInstruction[])(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldloc, (object)localBuilder2), CodeInstruction.Call((LambdaExpression)(Expression<Func<Action<GrabbableObject>>>)(() => AssignScrapSpawnToObject)) }); return val.InstructionEnumeration(); } private static void CaptureScrapSpawn(RandomScrapSpawn randomScrapSpawn) { s_RandomScrapSpawn = randomScrapSpawn; } private static void AssignScrapSpawnToObject(GrabbableObject grabbableObject) { if (!((Object)(object)s_RandomScrapSpawn == (Object)null)) { s_AssignedRandomSpawn.AddOrUpdate(grabbableObject, s_RandomScrapSpawn); s_RandomScrapSpawn = null; } } } [HarmonyPatch(typeof(SoundManager))] internal static class Patch_SoundManager { private static AudioMixerGroup[]? s_VoiceGroups; private static bool[]? s_VoiceBypass; private static readonly List<AudioMixerGroup> s_UnusedVoiceGroups = new List<AudioMixerGroup>(); [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("Start")] [HarmonyPostfix] [HarmonyAfter(new string[] { "me.swipez.melonloader.morecompany" })] private static void Start(SoundManager __instance) { if (Dependencies.IsModLoaded("me.swipez.melonloader.morecompany")) { ApplyExtraVoiceGroups(__instance); } if (UnityAudioMixerNative.TryInitialize()) { BypassUnusedVoiceGroups(); s_VoiceGroups = __instance.playerVoiceMixers; s_VoiceBypass = new bool[s_VoiceGroups.Length]; LethalPerformancePlugin.Instance.Logger.LogDebug((object)("Registered " + s_VoiceGroups.Length + " voice mixer groups")); ApplyVoiceBypass(__instance, force: true); } } [HarmonyPatch("SetPlayerPitch")] [HarmonyPostfix] private static void SetPlayerPitch(SoundManager __instance) { ApplyVoiceBypass(__instance, force: false); } [HarmonyPatch("SetPlayerVoiceFilters")] [HarmonyPostfix] private static void SetPlayerVoiceFilters(SoundManager __instance) { ApplyVoiceBypass(__instance, force: false); } private static void ApplyExtraVoiceGroups(SoundManager instance) { AudioMixerGroup[] extraVoiceGroups = DiageticVoiceMixerNative.ExtraVoiceGroups; if (extraVoiceGroups != null && extraVoiceGroups.Length != 0) { AudioMixerGroup[] playerVoiceMixers = instance.playerVoiceMixers; int num = Math.Clamp(playerVoiceMixers.Length - 4, 0, extraVoiceGroups.Length); for (int i = 0; i < num; i++) { playerVoiceMixers[i + 4] = extraVoiceGroups[i]; } s_UnusedVoiceGroups.Clear(); for (int j = num; j < extraVoiceGroups.Length; j++) { s_UnusedVoiceGroups.Add(extraVoiceGroups[j]); } } } private static void BypassUnusedVoiceGroups() { for (int i = 0; i < s_UnusedVoiceGroups.Count; i++) { UnityAudioMixerNative.TrySetEffectBypass(s_UnusedVoiceGroups[i], MixerEffect.PitchShifter, bypass: true); } } private static void ApplyVoiceBypass(SoundManager instance, bool force) { if (s_VoiceGroups == null || s_VoiceBypass == null) { return; } float[] playerVoicePitches = instance.playerVoicePitches; float[] pitchOffsets = instance.pitchOffsets; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; int num = Math.Min(s_VoiceGroups.Length, (playerVoicePitches != null) ? playerVoicePitches.Length : 0); for (int i = 0; i < num; i++) { float num2 = playerVoicePitches[i]; if (i < pitchOffsets.Length && pitchOffsets[i] != 0f && i < allPlayerScripts.Length && (Object)(object)allPlayerScripts[i] != (Object)null) { num2 += pitchOffsets[i] * Mathf.Abs((float)allPlayerScripts[i].health / 100f - 1f); } bool flag = Mathf.Abs(num2 - 1f) <= 0.025f; if ((force || flag != s_VoiceBypass[i]) && UnityAudioMixerNative.TrySetEffectBypass(s_VoiceGroups[i], MixerEffect.PitchShifter, flag)) { s_VoiceBypass[i] = flag; } } } } [HarmonyPatch(typeof(StartOfRound))] internal static class Patch_StartOfRound { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("SetPlayerSafeInShip")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> ReplaceFindOfObjectOfType(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Expected O, but got Unknown //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected O, but got Unknown //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Expected O, but got Unknown //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Expected O, but got Unknown //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Expected O, but got Unknown //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Expected O, but got Unknown //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Expected O, but got Unknown //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); LocalBuilder countLocal = generator.DeclareLocal(typeof(int), pinned: false); MethodInfo findObjectOfTypeMethod = typeof(Object).GetMethod("FindObjectsOfType", 1, AccessTools.all, null, CallingConventions.Any, Array.Empty<Type>(), Array.Empty<ParameterModifier>()).MakeGenericMethod(typeof(EnemyAI)); MethodInfo getMethod = typeof(RoundManager).GetProperty("Instance", AccessTools.all).GetGetMethod(); FieldInfo field = typeof(RoundManager).GetField("SpawnedEnemies", AccessTools.all); FieldInfo field2 = typeof(List<EnemyAI>).GetField("_items", AccessTools.all); MethodInfo getMethod2 = typeof(List<EnemyAI>).GetProperty("Count", AccessTools.all).GetGetMethod(); val.SearchForward((Func<CodeInstruction, bool>)((CodeInstruction c) => CodeInstructionExtensions.Calls(c, findObjectOfTypeMethod))).Set(OpCodes.Call, (object)getMethod).Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldfld, (object)field), new CodeInstruction(OpCodes.Ldfld, (object)field2) }) .Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[4] { new CodeInstruction(OpCodes.Call, (object)getMethod), new CodeInstruction(OpCodes.Ldfld, (object)field), new CodeInstruction(OpCodes.Callvirt, (object)getMethod2), new CodeInstruction(OpCodes.Stloc, (object)countLocal) }); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[2] { new CodeMatch((OpCode?)OpCodes.Ldloc_1, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldlen, (object)null, (string)null) }).Repeat((Action<CodeMatcher>)delegate(CodeMatcher m) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown m.RemoveInstructions(2).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldloc, (object)countLocal) }); }, (Action<string>)null); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(TextEffect))] internal static class Patch_TextEffect { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPrefix] [HarmonyPatch("Update")] public static bool Update(TextEffect __instance) { //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: 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) TMP_Text text = __instance.text; if (!Object.op_Implicit((Object)(object)text)) { return false; } float time = TimeUtil.GetTime(); if (time < __instance.nextUpdateTime_) { return false; } __instance.nextUpdateTime_ = time + 1f / (float)__instance.updatesPerSecond; text.ForceMeshUpdate(false, false); TMP_TextInfo textInfo = text.textInfo; List<GlobalTextEffectEntry> onStartEffects_ = __instance.onStartEffects_; List<GlobalTextEffectEntry> manualEffects_ = __instance.manualEffects_; List<TextEffectEntry> onStartTagEffects_ = __instance.onStartTagEffects_; List<TextEffectEntry> manualTagEffects_ = __instance.manualTagEffects_; for (int i = 0; i < textInfo.characterCount; i++) { if (textInfo.characterInfo[i].isVisible) { ApplyGlobalEffects(onStartEffects_, textInfo, i, overrideTagEffects: false); ApplyGlobalEffects(manualEffects_, textInfo, i, overrideTagEffects: false); ApplyTagEffects(onStartTagEffects_, textInfo, i); ApplyTagEffects(manualTagEffects_, textInfo, i); ApplyGlobalEffects(onStartEffects_, textInfo, i, overrideTagEffects: true); ApplyGlobalEffects(manualEffects_, textInfo, i, overrideTagEffects: true); } } TMP_MeshInfo[] meshInfo = textInfo.meshInfo; for (int j = 0; j < meshInfo.Length; j++) { TMP_MeshInfo val = meshInfo[j]; val.mesh.colors32 = val.colors32; val.mesh.vertices = val.vertices; text.UpdateGeometry(val.mesh, j); } return false; } private static void ApplyGlobalEffects(List<GlobalTextEffectEntry> effects, TMP_TextInfo textInfo, int charIndex, bool overrideTagEffects) { for (int i = 0; i < effects.Count; i++) { GlobalTextEffectEntry val = effects[i]; if (val.overrideTagEffects == overrideTagEffects) { ((TextEffect_Base)((TextEffectEntry)val).effect).ApplyEffect(textInfo, charIndex, 0, 3); } } } private static void ApplyTagEffects(List<TextEffectEntry> effects, TMP_TextInfo textInfo, int charIndex) { for (int i = 0; i < effects.Count; i++) { ((TextEffect_Base)effects[i].effect).ApplyEffect(textInfo, charIndex, 0, 3); } } } [HarmonyPatch(typeof(TimeOfDay))] [HarmonyPriority(0)] internal static class Patch_TimeOfDay { [HarmonyPatch("Start")] [HarmonyPostfix] public static void FixParticleSubEmitters(TimeOfDay __instance) { //IL_0036: 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) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) WeatherEffect[] effects = __instance.effects; foreach (WeatherEffect val in effects) { if (val == null || (Object)(object)val.effectObject == (Object)null) { continue; } ParticleSystem componentInChildren = val.effectObject.GetComponentInChildren<ParticleSystem>(); if ((Object)(object)componentInChildren == (Object)null) { continue; } SubEmittersModule subEmitters = componentInChildren.subEmitters; if (((SubEmittersModule)(ref subEmitters)).enabled) { int subEmittersCount = ((SubEmittersModule)(ref subEmitters)).subEmittersCount; for (int j = 0; j < subEmittersCount; j++) { ParticleSystem subEmitterSystem = ((SubEmittersModule)(ref subEmitters)).GetSubEmitterSystem(j); MainModule main = subEmitterSystem.main; ((MainModule)(ref main)).stopAction = (ParticleSystemStopAction)0; } } } } } [HarmonyPatch(typeof(VehicleController))] internal static class Patch_VehicleController { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("FixedUpdate")] [HarmonyTranspiler] internal static IEnumerable<CodeInstruction> NotSearchDropshipAfterDelivery(IEnumerable<CodeInstruction> instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Brtrue, (object)null, "branch") }); object operand = val.NamedMatch("branch").operand; FieldInfo field = typeof(VehicleController).GetField("hasBeenSpawned", AccessTools.all); val.Advance(1).Insert((CodeInstruction[])(object)new CodeInstruction[3] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldfld, (object)field), new CodeInstruction(OpCodes.Brtrue, operand) }); return val.Instructions(); } } [HarmonyPatch(typeof(VolumeComponent))] internal static class Patch_VolumeComponent { private struct CodeInstruction { public OpCode opCode; public FieldInfo? field; public readonly void Emit(ILGenerator il) { if (field == null) { il.Emit(opCode); } else { il.Emit(opCode, field); } } } private static readonly MethodInfo s_ListAdd = typeof(List<VolumeParameter>).GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); private static readonly Dictionary<Type, Action<VolumeComponent, List<VolumeParameter>>?> s_FindParametersDelegates = new Dictionary<Type, Action<VolumeComponent, List<VolumeParameter>>>(); [HarmonyPatch("FindParameters")] [HarmonyPrefix] private static bool FindParametersFast(object o, List<VolumeParameter> parameters) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown VolumeComponent arg = (VolumeComponent)o; Type type = o.GetType(); if (!s_FindParametersDelegates.TryGetValue(type, out Action<VolumeComponent, List<VolumeParameter>> value)) { value = CreateFindParameters(type); s_FindParametersDelegates[type] = value; } if (value == null) { return true; } value(arg, parameters); return false; } public static Action<VolumeComponent, List<VolumeParameter>>? CreateFindParameters(Type type) { DynamicMethod dynamicMethod = new DynamicMethod("FindParametersFast", null, new Type[2] { typeof(VolumeComponent), typeof(List<VolumeParameter>) }, type, skipVisibility: true); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); List<CodeInstruction> codeInstructions = new List<CodeInstruction> { new CodeInstruction { opCode = OpCodes.Ldarg_0 } }; EmitAddItem(type, iLGenerator, codeInstructions); iLGenerator.Emit(OpCodes.Ret); try { return (Action<VolumeComponent, List<VolumeParameter>>)dynamicMethod.CreateDelegate(typeof(Action<VolumeComponent, List<VolumeParameter>>)); } catch (Exception ex) { LethalPerformancePlugin.Instance.Logger.LogError((object)ex); } return null; } private static void EmitAddItem(Type type, ILGenerator il, List<CodeInstruction> codeInstructions) { Label? label = null; if (codeInstructions.Count > 1) { foreach (CodeInstruction codeInstruction in codeInstructions) { codeInstruction.Emit(il); } label = il.DefineLabel(); il.Emit(OpCodes.Brfalse_S, label.Value); } foreach (FieldInfo item in from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) orderby f.MetadataToken select f) { Type fieldType = item.FieldType; if (fieldType.IsSubclassOf(typeof(VolumeParameter))) { il.Emit(OpCodes.Ldarg_1); foreach (CodeInstruction codeInstruction2 in codeInstructions) { codeInstruction2.Emit(il); } il.Emit(OpCodes.Ldfld, item); il.Emit(OpCodes.Callvirt, s_ListAdd); } else { if (fieldType.IsArray || !fieldType.IsClass || typeof(ICollection).IsAssignableFrom(fieldType)) { continue; } codeInstructions.Add(new CodeInstruction { opCode = OpCodes.Ldfld, field = item }); if (codeInstructions.Count > 30) { codeInstructions.ForEach(delegate(CodeInstruction c) { Console.WriteLine(c.field?.DeclaringType.Name + " " + c.field?.Name); }); } EmitAddItem(fieldType, il, codeInstructions); codeInstructions.RemoveAt(codeInstructions.Count - 1); } } if (label.HasValue) { il.Emit(OpCodes.Nop); il.MarkLabel(label.Value); } } } [HarmonyPatch] internal static class Patch_WaveFileWriter { private static readonly byte[] s_RIFF = "RIFF"u8.ToArray(); private static readonly byte[] s_WAVE = "WAVE"u8.ToArray(); private static readonly byte[] s_Fmt = "fmt "u8.ToArray(); private static readonly byte[] s_Data = "data"u8.ToArray(); private static readonly byte[] s_Fact = "fact"u8.ToArray(); private static readonly Dictionary<string, FieldInfo> s_StringToFieldMapping = new Dictionary<string, FieldInfo> { ["RIFF"] = typeof(Patch_WaveFileWriter).GetField("s_RIFF", AccessTools.all), ["WAVE"] = typeof(Patch_WaveFileWriter).GetField("s_WAVE", AccessTools.all), ["fmt "] = typeof(Patch_WaveFileWriter).GetField("s_Fmt", AccessTools.all), ["data"] = typeof(Patch_WaveFileWriter).GetField("s_Data", AccessTools.all), ["fact"] = typeof(Patch_WaveFileWriter).GetField("s_Fact", AccessTools.all) }; [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPatch(typeof(WaveFileWriter), "WriteDataChunkHeader")] [HarmonyPatch(typeof(WaveFileWriter), "CreateFactChunk")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> ReplaceASCIICallToStaticField(IEnumerable<CodeInstruction> instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldstr, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null) }).Repeat((Action<CodeMatcher>)delegate(CodeMatcher m) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown string key = (string)m.InstructionAt(1).operand; FieldInfo fieldInfo = s_StringToFieldMapping[key]; m.RemoveInstructions(3).Insert((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo) }); }, (Action<string>)null); return val.InstructionEnumeration(); } [HarmonyPatch(typeof(WaveFileWriter), "WriteSamples")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> FixWriterFloatAllocation(IEnumerable<CodeInstruction> _) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown return new <>z__ReadOnlyArray<CodeInstruction>((CodeInstruction[])(object)new CodeInstruction[6] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), new CodeInstruction(OpCodes.Ldarg_2, (object)null), new CodeInstruction(OpCodes.Ldarg_3, (object)null), CodeInstruction.Call((LambdaExpression)(Expression<Func<Action<WaveFileWriter, float[], int, int>>>)(() => WriteSamples)), new CodeInstruction(OpCodes.Ret, (object)null) }); } private static void WriteSamples(WaveFileWriter waveFileWriter, float[] samples, int offset, int count) { Span<byte> span = stackalloc byte[4]; for (int i = 0; i < count; i++) { BinaryPrimitivesExtension.WriteSingleLittleEndian(span, samples[offset + i]); waveFileWriter._outStream.Write(span); waveFileWriter._dataChunkSize += 4; } } } } namespace LethalPerformance.Patches.ReferenceHolder { internal static class MoonCachingPatch { [HarmonyPatch(typeof(NavMeshSurface))] private static class Patch_NavMeshSurface { private static readonly string[] s_AnimatedSunPaths = new string[2] { "/Environment/Lighting/BrightDay/Sun/SunAnimContainer", "/Environment/Lighting/BrightDay/Sun/BlizzardSunAnimContainer" }; [HarmonyPatch("OnEnable")] [HarmonyPostfix] public static void OnEnable() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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_002f: Unknown result type (might be due to invalid IL or missing references) Scene lastLoadedScene = SceneUtilities.GetLastLoadedScene(); if (!((Scene)(ref lastLoadedScene)).IsValid()) { return; } int handle = ((Scene)(ref lastLoadedScene)).handle; if (handle != s_LastCalledSceneId) { bool flag = FindDropship(lastLoadedScene); bool flag2 = FindDungeon(lastLoadedScene); bool flag3 = FindAnimatedSun(lastLoadedScene); LethalPerformancePlugin.Instance.Logger.LogInfo((object)$"Found Dropship:{flag}, Dungeon:{flag2}, Sun:{flag3}"); if (flag || flag2 || flag3) { s_LastCalledSceneId = handle; } } } private static bool FindDungeon(Scene scene) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("/Systems/LevelGeneration/DungeonGenerator"); RuntimeDungeon instance = default(RuntimeDungeon); if ((Object)(object)val != (Object)null && val.TryGetComponent<RuntimeDungeon>(ref instance)) { s_RuntimeDungeon.SetInstance(instance); return true; } List<GameObject> list = default(List<GameObject>); PooledObject<List<GameObject>> val2 = CollectionPool<List<GameObject>, GameObject>.Get(ref list); try { ((Scene)(ref scene)).GetRootGameObjects(list); foreach (GameObject item in list) { instance = item.GetComponentInChildren<RuntimeDungeon>(false); if (!((Object)(object)instance == (Object)null)) { s_RuntimeDungeon.SetInstance(instance); return true; } } s_RuntimeDungeon.SetInstance(null); return false; } finally { ((IDisposable)val2/*cast due to .constrained prefix*/).Dispose(); } } private static bool FindDropship(Scene scene) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("/Systems/ItemShipAnimContainer/ItemShip"); ItemDropship instance = default(ItemDropship); if ((Object)(object)val != (Object)null && val.TryGetComponent<ItemDropship>(ref instance)) { s_ItemDropship.SetInstance(instance); return true; } List<GameObject> list = default(List<GameObject>); PooledObject<List<GameObject>> val2 = CollectionPool<List<GameObject>, GameObject>.Get(ref list); try { ((Scene)(ref scene)).GetRootGameObjects(list); foreach (GameObject item in list) { instance = item.GetComponentInChildren<ItemDropship>(false); if (!((Object)(object)instance == (Object)null)) { s_ItemDropship.SetInstance(instance); return true; } } s_ItemDropship.SetInstance(null); return false; } finally { ((IDisposable)val2/*cast due to .constrained prefix*/).Dispose(); } } private static bool FindAnimatedSun(Scene scene) { //IL_004b: 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) string[] array = s_AnimatedSunPaths; animatedSun instance = default(animatedSun); foreach (string text in array) { GameObject val = GameObject.Find(text); if ((Object)(object)val != (Object)null && val.TryGetComponent<animatedSun>(ref instance)) { s_AnimatedSun.SetInstance(instance); return true; } } List<GameObject> list = default(List<GameObject>); PooledObject<List<GameObject>> val2 = CollectionPool<List<GameObject>, GameObject>.Get(ref list); try { ((Scene)(ref scene)).GetRootGameObjects(list); foreach (GameObject item in list) { instance = item.GetComponentInChildren<animatedSun>(false); if (!((Object)(object)instance == (Object)null)) { s_AnimatedSun.SetInstance(instance); return true; } } s_AnimatedSun.SetInstance(null); return false; } finally { ((IDisposable)val2/*cast due to .constrained prefix*/).Dispose(); } } } [HarmonyPatch(typeof(ElevatorAnimationEvents))] private static class Patch_ElevatorAnimationEvents { [HarmonyPatch("ElevatorFullyRunning")] [HarmonyPrefix] private static void ElevatorFullyRunning() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) Scene lastLoadedScene = SceneUtilities.GetLastLoadedScene(); if (((Scene)(ref lastLoadedScene)).IsValid()) { int handle = ((Scene)(ref lastLoadedScene)).handle; if (handle == s_LastCalledSceneId) { s_LastCalledSceneId = -1; s_ItemDropship.SetInstance(null); s_RuntimeDungeon.SetInstance(null); s_AnimatedSun.SetInstance(null); } } } } private static readonly UnsafeCachedInstance<ItemDropship> s_ItemDropship = UnsafeCacheManager.AddReferenceToMap<ItemDropship>((UnsafeCachedInstance<ItemDropship>)new ManualCachedInstance<ItemDropship>()); internal static readonly UnsafeCachedInstance<RuntimeDungeon> s_RuntimeDungeon = UnsafeCacheManager.AddReferenceToMap<RuntimeDungeon>((UnsafeCachedInstance<RuntimeDungeon>)new ManualCachedInstance<RuntimeDungeon>()); private static readonly UnsafeCachedInstance<animatedSun> s_AnimatedSun = UnsafeCacheManager.AddReferenceToMap<animatedSun>((UnsafeCachedInstance<animatedSun>)new ManualCachedInstance<animatedSun>()); private static int s_LastCalledSceneId = -1; } [HarmonyPatch(typeof(EventSystem))] internal static class Patch_EventSystem { private static readonly string[] s_CameraPaths = new string[3] { "/Systems/GameSystems/ItemSystems/MapCamera", "/Environment/HangarShip/Cameras/FrontDoorSecurityCam/SecurityCamera", "/Environment/HangarShip/Cameras/ShipCamera" }; [HarmonyPatch("OnEnable")] [HarmonyPrefix] public static void FindReferences(EventSystem __instance) { //IL_0006: 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_000c: Unknown result type (might be due to invalid IL or missing references) Scene scene = ((Component)__instance).gameObject.scene; if (!scene.IsSceneShip()) { return; } try { UnsafeCacheManager.CacheInstances(); DeleteUnusedStuff(); } catch (Exception arg) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)$"Failed to get references. Probably other mod destroyed object.\n{arg}"); } } private static void DeleteUnusedStuff() { //IL_002b: 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) GameObject val = GameObject.Find("/PlayersContainer"); if ((Object)(object)val == (Object)null) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)"Failed to find Player container"); return; } List<PlayerControllerB> list = default(List<PlayerControllerB>); PooledObject<List<PlayerControllerB>> val2 = ListPool<PlayerControllerB>.Get(ref list); try { val.GetComponentsInChildren<PlayerControllerB>(list); CanvasScaler val3 = default(CanvasScaler); GraphicRaycaster val4 = default(GraphicRaycaster); foreach (PlayerControllerB item in list) { if (((Component)item.usernameCanvas).TryGetComponent<CanvasScaler>(ref val3)) { Object.Destroy((Object)(object)val3); } if (((Component)item.usernameCanvas).TryGetComponent<GraphicRaycaster>(ref val4)) { Object.Destroy((Object)(object)val4); } } val = GameObject.Find("/Systems/GameSystems/ItemSystems/MapScreenUIWorldSpace"); if ((Object)(object)val != (Object)null) { GraphicRaycaster val5 = default(GraphicRaycaster); if (val.TryGetComponent<GraphicRaycaster>(ref val5)) { Object.Destroy((Object)(object)val5); } CanvasScaler val6 = default(CanvasScaler); if (val.TryGetComponent<CanvasScaler>(ref val6)) { Object.Destroy((Object)(object)val6); } } val = GameObject.Find("/Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)"); if ((Object)(object)val != (Object)null) { GraphicRaycaster val7 = default(GraphicRaycaster); if (val.TryGetComponent<GraphicRaycaster>(ref val7)) { Object.Destroy((Object)(object)val7); } CanvasScaler val8 = default(CanvasScaler); if (val.TryGetComponent<CanvasScaler>(ref val8)) { Object.Destroy((Object)(object)val8); } } ChangeUICameraSettings(); RemoveAudioSpecializerPlugin(); DisableCameraCleanup(); } finally { ((IDisposable)val2/*cast due to .constrained prefix*/).Dispose(); } } private static void DisableCameraCleanup() { string[] array = s_CameraPaths; HDAdditionalCameraData val2 = default(HDAdditionalCameraData); foreach (string text in array) { GameObject val = GameObject.Find(text); if (!((Object)(object)val == (Object)null) && val.TryGetComponent<HDAdditionalCameraData>(ref val2)) { val2.hasPersistentHistory = true; HDCameraFrameSettingsOptimizer.ApplyExtraCameraFrameSettings(val2); } } } private static void RemoveAudioSpecializerPlugin() { if (!Dependencies.IsModLoaded("imabatby.lethallevelloader") && !Dependencies.IsModLoaded("mattymatty.LobbyControl")) { AudioSource[] array = Resources.FindObjectsOfTypeAll<AudioSource>(); AudioSource[] array2 = array; foreach (AudioSource val in array2) { val.spatialize = false; } LethalPerformancePlugin.Instance.Logger.LogInfo((object)$"Disabled spatialize for {array.Length} audio sources"); } } private static void ChangeUICameraSettings() { if (!Dependencies.IsModLoaded("io.daxcess.lcvr")) { GameObject val = GameObject.Find("/Systems/UI/UICamera"); HDAdditionalCameraData data = default(HDAdditionalCameraData); if (!((Object)(object)val == (Object)null) && val.TryGetComponent<HDAdditionalCameraData>(ref data)) { HDCameraFrameSettingsOptimizer.ApplyExtraCameraFrameSettings(data); } } } } } namespace LethalPerformance.Patches.Mods { internal static class Patch_LethalLevelLoader { private static readonly MethodInfo? s_MethodToPatch; static Patch_LethalLevelLoader() { if (Chainloader.PluginInfos.TryGetValue("imabatby.lethallevelloader", out var value) && !((Object)(object)value.Instance == (Object)null)) { Type type = ((object)value.Instance).GetType().Assembly.GetType("LethalLevelLoader.Patches"); if (type != null) { s_MethodToPatch = Acce
BepInEx/plugins/LethalPerformance/LethalPerformance.Unity.dll
Decompiled 3 weeks agousing System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using LethalPerformance.Unity; using Unity.Burst; using Unity.Collections.LowLevel.Unsafe; using Unity.Mathematics; using UnityEngine; using UnityEngine.Rendering.HighDefinition; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: StaticTypeReinit(typeof(LethalPerformance.Unity.FindFreeSlot_00000003$BurstDirectCall))] [assembly: StaticTypeReinit(typeof(LethalPerformance.Unity.CountFreeSlots_00000004$BurstDirectCall))] [assembly: StaticTypeReinit(typeof(LethalPerformance.Unity.UpdateShaderVariablesXRCB_00000006$BurstDirectCall))] [assembly: StaticTypeReinit(typeof(LethalPerformance.Unity.UpdateShaderVariablesGlobalCB_00000007$BurstDirectCall))] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [CompilerGenerated] [EditorBrowsable(EditorBrowsableState.Never)] [GeneratedCode("Unity.MonoScriptGenerator.MonoScriptInfoGenerator", null)] internal class UnitySourceGeneratedAssemblyMonoScriptTypes_v1 { private struct MonoScriptData { public byte[] FilePathsData; public byte[] TypesData; public int TotalTypes; public int TotalFiles; public bool IsEditorOnly; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static MonoScriptData Get() { return new MonoScriptData { FilePathsData = new byte[107] { 0, 0, 0, 1, 0, 0, 0, 51, 92, 65, 115, 115, 101, 116, 115, 92, 76, 101, 116, 104, 97, 108, 80, 101, 114, 102, 111, 114, 109, 97, 110, 99, 101, 92, 67, 97, 99, 104, 101, 100, 83, 104, 97, 100, 111, 119, 65, 116, 108, 97, 115, 66, 117, 114, 115, 116, 46, 99, 115, 0, 0, 0, 4, 0, 0, 0, 40, 92, 65, 115, 115, 101, 116, 115, 92, 76, 101, 116, 104, 97, 108, 80, 101, 114, 102, 111, 114, 109, 97, 110, 99, 101, 92, 67, 97, 109, 101, 114, 97, 66, 117, 114, 115, 116, 46, 99, 115 }, TypesData = new byte[289] { 0, 0, 0, 0, 46, 76, 101, 116, 104, 97, 108, 80, 101, 114, 102, 111, 114, 109, 97, 110, 99, 101, 46, 85, 110, 105, 116, 121, 124, 67, 97, 99, 104, 101, 100, 83, 104, 97, 100, 111, 119, 65, 116, 108, 97, 115, 66, 117, 114, 115, 116, 0, 0, 0, 0, 35, 76, 101, 116, 104, 97, 108, 80, 101, 114, 102, 111, 114, 109, 97, 110, 99, 101, 46, 85, 110, 105, 116, 121, 124, 67, 97, 109, 101, 114, 97, 66, 117, 114, 115, 116, 0, 0, 0, 0, 57, 76, 101, 116, 104, 97, 108, 80, 101, 114, 102, 111, 114, 109, 97, 110, 99, 101, 46, 85, 110, 105, 116, 121, 46, 67, 97, 109, 101, 114, 97, 66, 117, 114, 115, 116, 124, 82, 101, 97, 100, 97, 98, 108, 101, 86, 105, 101, 119, 67, 111, 110, 115, 116, 97, 110, 116, 115, 0, 0, 0, 0, 61, 76, 101, 116, 104, 97, 108, 80, 101, 114, 102, 111, 114, 109, 97, 110, 99, 101, 46, 85, 110, 105, 116, 121, 46, 67, 97, 109, 101, 114, 97, 66, 117, 114, 115, 116, 124, 82, 101, 97, 100, 97, 98, 108, 101, 83, 104, 97, 100, 101, 114, 86, 97, 114, 105, 97, 98, 108, 101, 115, 88, 82, 0, 0, 0, 0, 65, 76, 101, 116, 104, 97, 108, 80, 101, 114, 102, 111, 114, 109, 97, 110, 99, 101, 46, 85, 110, 105, 116, 121, 46, 67, 97, 109, 101, 114, 97, 66, 117, 114, 115, 116, 124, 82, 101, 97, 100, 97, 98, 108, 101, 83, 104, 97, 100, 101, 114, 86, 97, 114, 105, 97, 98, 108, 101, 115, 71, 108, 111, 98, 97, 108 }, TotalFiles = 2, TotalTypes = 5, IsEditorOnly = false }; } } namespace LethalPerformance.Unity; [BurstCompile] public static class CachedShadowAtlasBurst { public unsafe delegate bool FindFreeSlot_00000003$PostfixBurstDelegate(byte* slots, in int slotCount, in int res, in int numEntries, out int x, out int y); internal static class FindFreeSlot_00000003$BurstDirectCall { private static IntPtr Pointer; private static IntPtr DeferredCompilation; [BurstDiscard] private unsafe static void GetFunctionPointerDiscard(ref IntPtr P_0) { if (Pointer == (IntPtr)0) { Pointer = (nint)BurstCompiler.GetILPPMethodFunctionPointer2(DeferredCompilation, (RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/, typeof(FindFreeSlot_00000003$PostfixBurstDelegate).TypeHandle); } P_0 = Pointer; } private static IntPtr GetFunctionPointer() { nint result = 0; GetFunctionPointerDiscard(ref result); return result; } public static void Constructor() { DeferredCompilation = BurstCompiler.CompileILPPMethod2((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/); } public static void Initialize() { } static FindFreeSlot_00000003$BurstDirectCall() { Constructor(); } public unsafe static bool Invoke(byte* slots, in int slotCount, in int res, in int numEntries, out int x, out int y) { if (BurstCompiler.IsEnabled) { IntPtr functionPointer = GetFunctionPointer(); if (functionPointer != (IntPtr)0) { return ((delegate* unmanaged[Cdecl]<byte*, ref int, ref int, ref int, ref int, ref int, bool>)functionPointer)(slots, ref slotCount, ref res, ref numEntries, ref x, ref y); } } return FindFreeSlot$BurstManaged(slots, in slotCount, in res, in numEntries, out x, out y); } } public unsafe delegate int CountFreeSlots_00000004$PostfixBurstDelegate(byte* slots, in int slotCount); internal static class CountFreeSlots_00000004$BurstDirectCall { private static IntPtr Pointer; private static IntPtr DeferredCompilation; [BurstDiscard] private unsafe static void GetFunctionPointerDiscard(ref IntPtr P_0) { if (Pointer == (IntPtr)0) { Pointer = (nint)BurstCompiler.GetILPPMethodFunctionPointer2(DeferredCompilation, (RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/, typeof(CountFreeSlots_00000004$PostfixBurstDelegate).TypeHandle); } P_0 = Pointer; } private static IntPtr GetFunctionPointer() { nint result = 0; GetFunctionPointerDiscard(ref result); return result; } public static void Constructor() { DeferredCompilation = BurstCompiler.CompileILPPMethod2((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/); } public static void Initialize() { } static CountFreeSlots_00000004$BurstDirectCall() { Constructor(); } public unsafe static int Invoke(byte* slots, in int slotCount) { if (BurstCompiler.IsEnabled) { IntPtr functionPointer = GetFunctionPointer(); if (functionPointer != (IntPtr)0) { return ((delegate* unmanaged[Cdecl]<byte*, ref int, int>)functionPointer)(slots, ref slotCount); } } return CountFreeSlots$BurstManaged(slots, in slotCount); } } public const byte SlotFree = 0; [BurstCompile] public unsafe static bool FindFreeSlot(byte* slots, in int slotCount, in int res, in int numEntries, out int x, out int y) { return FindFreeSlot_00000003$BurstDirectCall.Invoke(slots, in slotCount, in res, in numEntries, out x, out y); } [BurstCompile] public unsafe static int CountFreeSlots(byte* slots, in int slotCount) { return CountFreeSlots_00000004$BurstDirectCall.Invoke(slots, in slotCount); } private unsafe static bool IsBlockFree(byte* slots, int res, int x, int y, int numEntries) { int num = y + numEntries; int num2 = x + numEntries; for (int i = y; i < num; i++) { int num3 = i * res; for (int j = x; j < num2; j++) { if (slots[num3 + j] != 0) { return false; } } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [BurstCompile] public unsafe static bool FindFreeSlot$BurstManaged(byte* slots, in int slotCount, in int res, in int numEntries, out int x, out int y) { int num = res - numEntries; if (slots == null || num < 0 || slotCount < res * res) { x = 0; y = 0; return false; } for (int i = 0; i <= num; i++) { int num2 = i * res; for (int j = 0; j <= num; j++) { if (slots[num2 + j] == 0 && IsBlockFree(slots, res, j, i, numEntries)) { x = j; y = i; return true; } } } x = 0; y = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [BurstCompile] public unsafe static int CountFreeSlots$BurstManaged(byte* slots, in int slotCount) { int num = 0; for (int i = 0; i < slotCount; i++) { if (slots[i] == 0) { num++; } } return num; } } [BurstCompile] public static class CameraBurst { public readonly struct ReadableViewConstants { public readonly Matrix4x4 viewMatrix; public readonly Matrix4x4 invViewMatrix; public readonly Matrix4x4 projMatrix; public readonly Matrix4x4 invProjMatrix; public readonly Matrix4x4 viewProjMatrix; public readonly Matrix4x4 invViewProjMatrix; public readonly Matrix4x4 nonJitteredViewProjMatrix; public readonly Matrix4x4 prevViewMatrix; public readonly Matrix4x4 prevViewProjMatrix; public readonly Matrix4x4 prevInvViewProjMatrix; public readonly Matrix4x4 prevViewProjMatrixNoCameraTrans; public readonly Matrix4x4 pixelCoordToViewDirWS; public readonly Matrix4x4 viewProjectionNoCameraTrans; public readonly Vector3 worldSpaceCameraPos; internal readonly float pad0; public readonly Vector3 worldSpaceCameraPosViewOffset; internal readonly float pad1; public readonly Vector3 prevWorldSpaceCameraPos; internal readonly float pad2; } public struct ReadableShaderVariablesXR { public unsafe fixed float _XRViewMatrix[32]; public unsafe fixed float _XRInvViewMatrix[32]; public unsafe fixed float _XRProjMatrix[32]; public unsafe fixed float _XRInvProjMatrix[32]; public unsafe fixed float _XRViewProjMatrix[32]; public unsafe fixed float _XRInvViewProjMatrix[32]; public unsafe fixed float _XRNonJitteredViewProjMatrix[32]; public unsafe fixed float _XRPrevViewProjMatrix[32]; public unsafe fixed float _XRPrevInvViewProjMatrix[32]; public unsafe fixed float _XRPrevViewProjMatrixNoCameraTrans[32]; public unsafe fixed float _XRViewProjMatrixNoCameraTrans[32]; public unsafe fixed float _XRPixelCoordToViewDirWS[32]; public unsafe fixed float _XRWorldSpaceCameraPos[8]; public unsafe fixed float _XRWorldSpaceCameraPosViewOffset[8]; public unsafe fixed float _XRPrevWorldSpaceCameraPos[8]; } public struct ReadableShaderVariablesGlobal { public Matrix4x4 _ViewMatrix; public Matrix4x4 _CameraViewMatrix; public Matrix4x4 _InvViewMatrix; public Matrix4x4 _ProjMatrix; public Matrix4x4 _InvProjMatrix; public Matrix4x4 _ViewProjMatrix; public Matrix4x4 _CameraViewProjMatrix; public Matrix4x4 _InvViewProjMatrix; public Matrix4x4 _NonJitteredViewProjMatrix; public Matrix4x4 _PrevViewProjMatrix; public Matrix4x4 _PrevInvViewProjMatrix; public Vector4 _WorldSpaceCameraPos_Internal; public Vector4 _PrevCamPosRWS_Internal; public Vector4 _ScreenSize; public Vector4 _PostProcessScreenSize; public Vector4 _RTHandleScale; public Vector4 _RTHandleScaleHistory; public Vector4 _RTHandlePostProcessScale; public Vector4 _RTHandlePostProcessScaleHistory; public Vector4 _DynamicResolutionFullscreenScale; public Vector4 _ZBufferParams; public Vector4 _ProjectionParams; public Vector4 unity_OrthoParams; public Vector4 _ScreenParams; public unsafe fixed float _FrustumPlanes[24]; public unsafe fixed float _ShadowFrustumPlanes[24]; public Vector4 _TaaFrameInfo; public Vector4 _TaaJitterStrength; public Vector4 _Time; public Vector4 _SinTime; public Vector4 _CosTime; public Vector4 unity_DeltaTime; public Vector4 _TimeParameters; public Vector4 _LastTimeParameters; public int _FogEnabled; public int _PBRFogEnabled; public int _EnableVolumetricFog; public float _MaxFogDistance; public Vector4 _FogColor; public float _FogColorMode; public float _GlobalMipBias; public float _GlobalMipBiasPow2; public float _Pad0; public Vector4 _MipFogParameters; public Vector4 _HeightFogBaseScattering; public float _HeightFogBaseExtinction; public float _HeightFogBaseHeight; public float _GlobalFogAnisotropy; public int _VolumetricFilteringEnabled; public Vector2 _HeightFogExponents; public int _FogDirectionalOnly; public float _FogGIDimmer; public Vector4 _VBufferViewportSize; public Vector4 _VBufferLightingViewportScale; public Vector4 _VBufferLightingViewportLimit; public Vector4 _VBufferDistanceEncodingParams; public Vector4 _VBufferDistanceDecodingParams; public uint _VBufferSliceCount; public float _VBufferRcpSliceCount; public float _VBufferRcpInstancedViewCount; public float _VBufferLastSliceDist; public Vector4 _ShadowAtlasSize; public Vector4 _CascadeShadowAtlasSize; public Vector4 _AreaShadowAtlasSize; public Vector4 _CachedShadowAtlasSize; public Vector4 _CachedAreaShadowAtlasSize; public int _ReflectionsMode; public int _UnusedPadding0; public int _UnusedPadding1; public int _UnusedPadding2; public uint _DirectionalLightCount; public uint _PunctualLightCount; public uint _AreaLightCount; public uint _EnvLightCount; public int _EnvLightSkyEnabled; public uint _CascadeShadowCount; public int _DirectionalShadowIndex; public uint _EnableLightLayers; public uint _EnableSkyReflection; public uint _EnableSSRefraction; public float _SSRefractionInvScreenWeightDistance; public float _ColorPyramidLodCount; public float _DirectionalTransmissionMultiplier; public float _ProbeExposureScale; public float _ContactShadowOpacity; public float _ReplaceDiffuseForIndirect; public Vector4 _AmbientOcclusionParam; public float _IndirectDiffuseLightingMultiplier; public uint _IndirectDiffuseLightingLayers; public float _ReflectionLightingMultiplier; public uint _ReflectionLightingLayers; public float _MicroShadowOpacity; public uint _EnableProbeVolumes; public uint _ProbeVolumeCount; public float _SlopeScaleDepthBias; public Vector4 _CookieAtlasSize; public Vector4 _CookieAtlasData; public Vector4 _ReflectionAtlasCubeData; public Vector4 _ReflectionAtlasPlanarData; public uint _NumTileFtplX; public uint _NumTileFtplY; public float g_fClustScale; public float g_fClustBase; public float g_fNearPlane; public float g_fFarPlane; public int g_iLog2NumClusters; public uint g_isLogBaseBufferEnabled; public uint _NumTileClusteredX; public uint _NumTileClusteredY; public int _EnvSliceSize; public uint _EnableDecalLayers; public unsafe fixed float _ShapeParamsAndMaxScatterDists[64]; public unsafe fixed float _TransmissionTintsAndFresnel0[64]; public unsafe fixed float _WorldScalesAndFilterRadiiAndThicknessRemaps[64]; public unsafe fixed float _DiffusionProfileHashTable[64]; public uint _EnableSubsurfaceScattering; public uint _TexturingModeFlags; public uint _TransmissionFlags; public uint _DiffusionProfileCount; public Vector2 _DecalAtlasResolution; public uint _EnableDecals; public uint _DecalCount; public float _OffScreenDownsampleFactor; public uint _OffScreenRendering; public uint _XRViewCount; public int _FrameCount; public Vector4 _CoarseStencilBufferSize; public int _IndirectDiffuseMode; public int _EnableRayTracedReflections; public int _RaytracingFrameIndex; public uint _EnableRecursiveRayTracing; public int _TransparentCameraOnlyMotionVectors; public float _GlobalTessellationFactorMultiplier; public float _SpecularOcclusionBlend; public float _DeExposureMultiplier; public Vector4 _ScreenSizeOverride; public Vector4 _ScreenCoordScaleBias; } public unsafe delegate void UpdateShaderVariablesXRCB_00000006$PostfixBurstDelegate(in ReadableViewConstants* xrViewConstants, in int viewCount, ReadableShaderVariablesXR* cb); internal static class UpdateShaderVariablesXRCB_00000006$BurstDirectCall { private static IntPtr Pointer; private static IntPtr DeferredCompilation; [BurstDiscard] private unsafe static void GetFunctionPointerDiscard(ref IntPtr P_0) { if (Pointer == (IntPtr)0) { Pointer = (nint)BurstCompiler.GetILPPMethodFunctionPointer2(DeferredCompilation, (RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/, typeof(UpdateShaderVariablesXRCB_00000006$PostfixBurstDelegate).TypeHandle); } P_0 = Pointer; } private static IntPtr GetFunctionPointer() { nint result = 0; GetFunctionPointerDiscard(ref result); return result; } public static void Constructor() { DeferredCompilation = BurstCompiler.CompileILPPMethod2((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/); } public static void Initialize() { } static UpdateShaderVariablesXRCB_00000006$BurstDirectCall() { Constructor(); } public unsafe static void Invoke(in ReadableViewConstants* xrViewConstants, in int viewCount, ReadableShaderVariablesXR* cb) { if (BurstCompiler.IsEnabled) { IntPtr functionPointer = GetFunctionPointer(); if (functionPointer != (IntPtr)0) { ((delegate* unmanaged[Cdecl]<ref ReadableViewConstants*, ref int, ReadableShaderVariablesXR*, void>)functionPointer)(ref xrViewConstants, ref viewCount, cb); return; } } UpdateShaderVariablesXRCB$BurstManaged(in xrViewConstants, in viewCount, cb); } } public unsafe delegate void UpdateShaderVariablesGlobalCB_00000007$PostfixBurstDelegate(ReadableShaderVariablesGlobal* cb, in FrameSettings frameSettings, in AntialiasingMode antialiasingMode, in CameraType cameraType, in ReadableViewConstants* mainViewConstants, in float4x4 vectorParams, in float4x4 vectorParams2, in float4x4 vectorParams3, in float4* frustumPlaneEquations, in float taaSharpenStrength, in int taaFrameIndex, in int colorPyramidHistoryMipCount, in float globalMipBias, in float time, in float lastTime, in int frameCount, in int viewCount, in float probeRangeCompressionFactor, in float deExposureMultiplier, in float4 screenCoordScaleBias, in bool useScreenSizeOverride, in float4 screenSizeOverride); internal static class UpdateShaderVariablesGlobalCB_00000007$BurstDirectCall { private static IntPtr Pointer; private static IntPtr DeferredCompilation; [BurstDiscard] private unsafe static void GetFunctionPointerDiscard(ref IntPtr P_0) { if (Pointer == (IntPtr)0) { Pointer = (nint)BurstCompiler.GetILPPMethodFunctionPointer2(DeferredCompilation, (RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/, typeof(UpdateShaderVariablesGlobalCB_00000007$PostfixBurstDelegate).TypeHandle); } P_0 = Pointer; } private static IntPtr GetFunctionPointer() { nint result = 0; GetFunctionPointerDiscard(ref result); return result; } public static void Constructor() { DeferredCompilation = BurstCompiler.CompileILPPMethod2((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/); } public static void Initialize() { } static UpdateShaderVariablesGlobalCB_00000007$BurstDirectCall() { Constructor(); } public unsafe static void Invoke(ReadableShaderVariablesGlobal* cb, in FrameSettings frameSettings, in AntialiasingMode antialiasingMode, in CameraType cameraType, in ReadableViewConstants* mainViewConstants, in float4x4 vectorParams, in float4x4 vectorParams2, in float4x4 vectorParams3, in float4* frustumPlaneEquations, in float taaSharpenStrength, in int taaFrameIndex, in int colorPyramidHistoryMipCount, in float globalMipBias, in float time, in float lastTime, in int frameCount, in int viewCount, in float probeRangeCompressionFactor, in float deExposureMultiplier, in float4 screenCoordScaleBias, in bool useScreenSizeOverride, in float4 screenSizeOverride) { if (BurstCompiler.IsEnabled) { IntPtr functionPointer = GetFunctionPointer(); if (functionPointer != (IntPtr)0) { ((delegate* unmanaged[Cdecl]<ReadableShaderVariablesGlobal*, ref FrameSettings, ref AntialiasingMode, ref CameraType, ref ReadableViewConstants*, ref float4x4, ref float4x4, ref float4x4, ref float4*, ref float, ref int, ref int, ref float, ref float, ref float, ref int, ref int, ref float, ref float, ref float4, ref bool, ref float4, void>)functionPointer)(cb, ref frameSettings, ref antialiasingMode, ref cameraType, ref mainViewConstants, ref vectorParams, ref vectorParams2, ref vectorParams3, ref frustumPlaneEquations, ref taaSharpenStrength, ref taaFrameIndex, ref colorPyramidHistoryMipCount, ref globalMipBias, ref time, ref lastTime, ref frameCount, ref viewCount, ref probeRangeCompressionFactor, ref deExposureMultiplier, ref screenCoordScaleBias, ref useScreenSizeOverride, ref screenSizeOverride); return; } } UpdateShaderVariablesGlobalCB$BurstManaged(cb, in frameSettings, in antialiasingMode, in cameraType, in mainViewConstants, in vectorParams, in vectorParams2, in vectorParams3, in frustumPlaneEquations, in taaSharpenStrength, in taaFrameIndex, in colorPyramidHistoryMipCount, in globalMipBias, in time, in lastTime, in frameCount, in viewCount, in probeRangeCompressionFactor, in deExposureMultiplier, in screenCoordScaleBias, in useScreenSizeOverride, in screenSizeOverride); } } [BurstCompile] public unsafe static void UpdateShaderVariablesXRCB(in ReadableViewConstants* xrViewConstants, in int viewCount, ReadableShaderVariablesXR* cb) { UpdateShaderVariablesXRCB_00000006$BurstDirectCall.Invoke(in xrViewConstants, in viewCount, cb); } [BurstCompile] public unsafe static void UpdateShaderVariablesGlobalCB(ReadableShaderVariablesGlobal* cb, in FrameSettings frameSettings, in AntialiasingMode antialiasingMode, in CameraType cameraType, in ReadableViewConstants* mainViewConstants, in float4x4 vectorParams, in float4x4 vectorParams2, in float4x4 vectorParams3, in float4* frustumPlaneEquations, in float taaSharpenStrength, in int taaFrameIndex, in int colorPyramidHistoryMipCount, in float globalMipBias, in float time, in float lastTime, in int frameCount, in int viewCount, in float probeRangeCompressionFactor, in float deExposureMultiplier, in float4 screenCoordScaleBias, in bool useScreenSizeOverride, in float4 screenSizeOverride) { UpdateShaderVariablesGlobalCB_00000007$BurstDirectCall.Invoke(cb, in frameSettings, in antialiasingMode, in cameraType, in mainViewConstants, in vectorParams, in vectorParams2, in vectorParams3, in frustumPlaneEquations, in taaSharpenStrength, in taaFrameIndex, in colorPyramidHistoryMipCount, in globalMipBias, in time, in lastTime, in frameCount, in viewCount, in probeRangeCompressionFactor, in deExposureMultiplier, in screenCoordScaleBias, in useScreenSizeOverride, in screenSizeOverride); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [BurstCompile] public unsafe static void UpdateShaderVariablesXRCB$BurstManaged(in ReadableViewConstants* xrViewConstants, in int viewCount, ReadableShaderVariablesXR* cb) { for (int i = 0; i < viewCount; i++) { UnsafeUtility.MemCpy((void*)(cb->_XRViewMatrix + i * 16), (void*)(&xrViewConstants[i].viewMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRInvViewMatrix + i * 16), (void*)(&xrViewConstants[i].invViewMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRProjMatrix + i * 16), (void*)(&xrViewConstants[i].projMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRInvProjMatrix + i * 16), (void*)(&xrViewConstants[i].invProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRViewProjMatrix + i * 16), (void*)(&xrViewConstants[i].viewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRInvViewProjMatrix + i * 16), (void*)(&xrViewConstants[i].invViewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRNonJitteredViewProjMatrix + i * 16), (void*)(&xrViewConstants[i].nonJitteredViewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPrevViewProjMatrix + i * 16), (void*)(&xrViewConstants[i].prevViewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPrevInvViewProjMatrix + i * 16), (void*)(&xrViewConstants[i].prevInvViewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRViewProjMatrixNoCameraTrans + i * 16), (void*)(&xrViewConstants[i].viewProjectionNoCameraTrans), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPrevViewProjMatrixNoCameraTrans + i * 16), (void*)(&xrViewConstants[i].prevViewProjMatrixNoCameraTrans), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPixelCoordToViewDirWS + i * 16), (void*)(&xrViewConstants[i].pixelCoordToViewDirWS), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRWorldSpaceCameraPos + i * 4), (void*)(&xrViewConstants[i].worldSpaceCameraPos), (long)Unsafe.SizeOf<float4>()); UnsafeUtility.MemCpy((void*)(cb->_XRWorldSpaceCameraPosViewOffset + i * 4), (void*)(&xrViewConstants[i].worldSpaceCameraPosViewOffset), (long)Unsafe.SizeOf<float4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPrevWorldSpaceCameraPos + i * 4), (void*)(&xrViewConstants[i].prevWorldSpaceCameraPos), (long)Unsafe.SizeOf<float4>()); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [BurstCompile] public unsafe static void UpdateShaderVariablesGlobalCB$BurstManaged(ReadableShaderVariablesGlobal* cb, in FrameSettings frameSettings, in AntialiasingMode antialiasingMode, in CameraType cameraType, in ReadableViewConstants* mainViewConstants, in float4x4 vectorParams, in float4x4 vectorParams2, in float4x4 vectorParams3, in float4* frustumPlaneEquations, in float taaSharpenStrength, in int taaFrameIndex, in int colorPyramidHistoryMipCount, in float globalMipBias, in float time, in float lastTime, in int frameCount, in int viewCount, in float probeRangeCompressionFactor, in float deExposureMultiplier, in float4 screenCoordScaleBias, in bool useScreenSizeOverride, in float4 screenSizeOverride) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_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_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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: 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_0053: 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) //IL_0061: 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) //IL_006f: 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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_00be: 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_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: 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_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: 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_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: 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_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015f: 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_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0197: 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_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: 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_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: 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_0214: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0230: 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_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_027c: 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_0293: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02ed: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_036c: Unknown result type (might be due to invalid IL or missing references) //IL_03a4: Unknown result type (might be due to invalid IL or missing references) //IL_03a9: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Unknown result type (might be due to invalid IL or missing references) //IL_03e6: Unknown result type (might be due to invalid IL or missing references) //IL_03eb: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: Unknown result type (might be due to invalid IL or missing references) //IL_0406: Unknown result type (might be due to invalid IL or missing references) //IL_040b: Unknown result type (might be due to invalid IL or missing references) //IL_0410: Unknown result type (might be due to invalid IL or missing references) //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_0433: Unknown result type (might be due to invalid IL or missing references) //IL_0438: Unknown result type (might be due to invalid IL or missing references) //IL_0456: Unknown result type (might be due to invalid IL or missing references) //IL_045b: Unknown result type (might be due to invalid IL or missing references) //IL_0460: Unknown result type (might be due to invalid IL or missing references) //IL_049b: Unknown result type (might be due to invalid IL or missing references) //IL_04a0: Unknown result type (might be due to invalid IL or missing references) //IL_04ad: Unknown result type (might be due to invalid IL or missing references) //IL_04b2: Unknown result type (might be due to invalid IL or missing references) //IL_04ca: Unknown result type (might be due to invalid IL or missing references) //IL_04cf: Unknown result type (might be due to invalid IL or missing references) //IL_04d4: Unknown result type (might be due to invalid IL or missing references) //IL_04e9: Unknown result type (might be due to invalid IL or missing references) //IL_04ee: Unknown result type (might be due to invalid IL or missing references) //IL_04e0: Unknown result type (might be due to invalid IL or missing references) //IL_04f3: Unknown result type (might be due to invalid IL or missing references) FrameSettings val = frameSettings; bool flag = ((FrameSettings)(ref val)).IsEnabled((FrameSettingsField)15) && (int)antialiasingMode == 2 && (int)cameraType == 1; Unsafe.Write(&cb->_ViewMatrix, mainViewConstants->viewMatrix); Unsafe.Write(&cb->_CameraViewMatrix, mainViewConstants->viewMatrix); Unsafe.Write(&cb->_InvViewMatrix, mainViewConstants->invViewMatrix); Unsafe.Write(&cb->_ProjMatrix, mainViewConstants->projMatrix); Unsafe.Write(&cb->_InvProjMatrix, mainViewConstants->invProjMatrix); Unsafe.Write(&cb->_ViewProjMatrix, mainViewConstants->viewProjMatrix); Unsafe.Write(&cb->_CameraViewProjMatrix, mainViewConstants->viewProjMatrix); Unsafe.Write(&cb->_InvViewProjMatrix, mainViewConstants->invViewProjMatrix); Unsafe.Write(&cb->_NonJitteredViewProjMatrix, mainViewConstants->nonJitteredViewProjMatrix); Unsafe.Write(&cb->_PrevViewProjMatrix, mainViewConstants->prevViewProjMatrix); Unsafe.Write(&cb->_PrevInvViewProjMatrix, mainViewConstants->prevInvViewProjMatrix); Unsafe.Write(&cb->_WorldSpaceCameraPos_Internal, Vector4.op_Implicit(mainViewConstants->worldSpaceCameraPos)); Unsafe.Write(&cb->_PrevCamPosRWS_Internal, Vector4.op_Implicit(mainViewConstants->prevWorldSpaceCameraPos)); float4x4 val2 = vectorParams; Unsafe.Write(&cb->_ScreenSize, float4.op_Implicit(((float4x4)(ref val2))[0])); val2 = vectorParams; Unsafe.Write(&cb->_PostProcessScreenSize, float4.op_Implicit(((float4x4)(ref val2))[1])); val2 = vectorParams; Unsafe.Write(&cb->_RTHandleScale, float4.op_Implicit(((float4x4)(ref val2))[2])); val2 = vectorParams; Unsafe.Write(&cb->_RTHandleScaleHistory, float4.op_Implicit(((float4x4)(ref val2))[3])); val2 = vectorParams2; Unsafe.Write(&cb->_RTHandlePostProcessScale, float4.op_Implicit(((float4x4)(ref val2))[0])); val2 = vectorParams2; Unsafe.Write(&cb->_RTHandlePostProcessScaleHistory, float4.op_Implicit(((float4x4)(ref val2))[1])); val2 = vectorParams2; float num = ((float4)(ref ((float4x4)(ref val2))[2]))[0]; val2 = vectorParams2; float num2 = num / ((float4)(ref ((float4x4)(ref val2))[2]))[1]; val2 = vectorParams2; float num3 = ((float4)(ref ((float4x4)(ref val2))[2]))[2]; val2 = vectorParams2; Unsafe.Write(&cb->_DynamicResolutionFullscreenScale, float4.op_Implicit(new float4(num2, num3 / ((float4)(ref ((float4x4)(ref val2))[2]))[3], 0f, 0f))); val2 = vectorParams2; Unsafe.Write(&cb->_ZBufferParams, float4.op_Implicit(((float4x4)(ref val2))[3])); val2 = vectorParams3; Unsafe.Write(&cb->_ProjectionParams, float4.op_Implicit(((float4x4)(ref val2))[0])); val2 = vectorParams3; Unsafe.Write(&cb->unity_OrthoParams, float4.op_Implicit(((float4x4)(ref val2))[1])); val2 = vectorParams3; Unsafe.Write(&cb->_ScreenParams, float4.op_Implicit(((float4x4)(ref val2))[2])); UnsafeUtility.MemCpy((void*)cb->_FrustumPlanes, (void*)frustumPlaneEquations, (long)(Unsafe.SizeOf<float4>() * 6)); Unsafe.Write(&cb->_TaaFrameInfo, float4.op_Implicit(new float4(taaSharpenStrength, 0f, (float)taaFrameIndex, flag ? 1f : 0f))); val2 = vectorParams3; Unsafe.Write(&cb->_TaaJitterStrength, float4.op_Implicit(((float4x4)(ref val2))[3])); cb->_ColorPyramidLodCount = colorPyramidHistoryMipCount; cb->_GlobalMipBias = globalMipBias; cb->_GlobalMipBiasPow2 = (float)math.pow(2.0, (double)globalMipBias); float deltaTime = Time.deltaTime; float smoothDeltaTime = Time.smoothDeltaTime; Unsafe.Write(&cb->_Time, float4.op_Implicit(new float4(time * 0.05f, time, time * 2f, time * 3f))); Unsafe.Write(&cb->_SinTime, float4.op_Implicit(new float4(math.sin(time * 0.125f), math.sin(time * 0.25f), math.sin(time * 0.5f), math.sin(time)))); Unsafe.Write(&cb->_CosTime, float4.op_Implicit(new float4(math.cos(time * 0.125f), math.cos(time * 0.25f), math.cos(time * 0.5f), math.cos(time)))); Unsafe.Write(&cb->unity_DeltaTime, float4.op_Implicit(new float4(deltaTime, 1f / deltaTime, smoothDeltaTime, 1f / smoothDeltaTime))); Unsafe.Write(&cb->_TimeParameters, float4.op_Implicit(new float4(time, math.sin(time), math.cos(time), 0f))); Unsafe.Write(&cb->_LastTimeParameters, float4.op_Implicit(new float4(lastTime, math.sin(lastTime), math.cos(lastTime), 0f))); cb->_FrameCount = frameCount; cb->_XRViewCount = (uint)viewCount; cb->_ProbeExposureScale = 1f / math.max(probeRangeCompressionFactor, 1E-06f); cb->_DeExposureMultiplier = deExposureMultiplier; val = frameSettings; int transparentCameraOnlyMotionVectors; if (((FrameSettings)(ref val)).IsEnabled((FrameSettingsField)10)) { val = frameSettings; if (!((FrameSettings)(ref val)).IsEnabled((FrameSettingsField)16)) { transparentCameraOnlyMotionVectors = 1; goto IL_04c2; } } transparentCameraOnlyMotionVectors = 0; goto IL_04c2; IL_04c2: cb->_TransparentCameraOnlyMotionVectors = transparentCameraOnlyMotionVectors; Unsafe.Write(&cb->_ScreenCoordScaleBias, float4.op_Implicit(screenCoordScaleBias)); Unsafe.Write(&cb->_ScreenSizeOverride, useScreenSizeOverride ? float4.op_Implicit(screenSizeOverride) : cb->_ScreenSize); } } internal static class $BurstDirectCallInitializer { [RuntimeInitializeOnLoadMethod(/*Could not decode attribute arguments.*/)] private static void Initialize() { CachedShadowAtlasBurst.FindFreeSlot_00000003$BurstDirectCall.Initialize(); CachedShadowAtlasBurst.CountFreeSlots_00000004$BurstDirectCall.Initialize(); CameraBurst.UpdateShaderVariablesXRCB_00000006$BurstDirectCall.Initialize(); CameraBurst.UpdateShaderVariablesGlobalCB_00000007$BurstDirectCall.Initialize(); } }
BepInEx/patchers/LethalPerformance/LethalPerformance.Patcher.dll
Decompiled 3 weeks agousing System; using System.Collections; 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.Text.RegularExpressions; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using LethalPerformance.Patcher.AssemblyPatches; using LethalPerformance.Patcher.Helpers; using LethalPerformance.Patcher.TomlConverters; using LethalPerformance.Patcher.Utilities; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.RuntimeDetour; using MonoMod.Utils; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("BepInEx")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalPerformance.Patcher")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.5.3.0")] [assembly: AssemblyInformationalVersion("1.5.3+151346b169f2366a1dfd952cb9e5730d227c92ca")] [assembly: AssemblyProduct("LethalPerformance.Patcher")] [assembly: AssemblyTitle("LethalPerformance.Patcher")] [assembly: InternalsVisibleTo("LethalPerformance")] [assembly: InternalsVisibleTo("LethalPerformance.Dev")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.5.3.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [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 LethalPerformance.Patcher { public class LethalPerformancePatcher { internal static Harmony? Harmony { get; set; } internal static ManualLogSource Logger { get; } = Logger.CreateLogSource("LethalPerformance.Patcher"); public static ConfigSaverTask ConfigSaverTask { get; } = new ConfigSaverTask(); public static IEnumerable<string> TargetDLLs { get; } = new <>z__ReadOnlyArray<string>(new string[3] { "Assembly-CSharp.dll", "Assembly-CSharp-firstpass.dll", "DunGen.dll" }); public static event Action? OnModsLoaded; internal static void InvokeOnModsLoaded() { try { LethalPerformancePatcher.OnModsLoaded?.Invoke(); } catch (Exception ex) { Logger.LogError((object)ex); } } public static void Finish() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown Harmony = new Harmony("LethalPerformance.Patcher"); Harmony.PatchAll(typeof(LethalPerformancePatcher).Assembly); Harmony.UnpatchID("org.bepinex.fixes.harmonyinterop"); TomlTypeConverter.TypeConverters[typeof(string)] = (TypeConverter)(object)new StringTomlConverter(); TomlTypeConverter.TypeConverters[typeof(bool)] = (TypeConverter)(object)new BoolTomlConverter(); WarnIfTerbiumInstalled(); } private static void WarnIfTerbiumInstalled() { IList list = (IList)Type.GetType("BepInEx.Preloader.Patching.AssemblyPatcher,BepInEx.Preloader").GetProperty("PatcherPlugins", AccessTools.all).GetGetMethod() .Invoke(null, null); PropertyInfo property = list[0].GetType().GetProperty("TypeName", AccessTools.all); foreach (object item in list) { string text = (string)property.GetGetMethod().Invoke(item, null); if (text == "Terbium.TerbiumPreloader") { Logger.LogWarning((object)"Terbium mod installed, for better compatibility remove it."); break; } } } public static void Patch(AssemblyDefinition assembly) { switch (((AssemblyNameReference)assembly.Name).Name) { case "Assembly-CSharp-firstpass": Patch_ES3.Patch(assembly); break; case "DunGen": Patch_ProxyDoorwayConnection.Patch(assembly); break; case "Assembly-CSharp": Patch_AssemblyCSharp.Patch(assembly); break; } } } public static class MyPluginInfo { public const string PLUGIN_GUID = "LethalPerformance.Patcher"; public const string PLUGIN_NAME = "LethalPerformance.Patcher"; public const string PLUGIN_VERSION = "1.5.3"; } } namespace LethalPerformance.Patcher.Utilities { internal static class AssemblyPatcherUtilities { public static void RemoveMethod(AssemblyDefinition assembly, TypeDefinition type, string methodName) { //IL_0006: 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) Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; if (((MemberReference)current).Name == methodName) { type.Methods.Remove(current); break; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } public static void AddMethod(AssemblyDefinition assembly, TypeDefinition type, string methodName) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown if (!((IEnumerable<MethodDefinition>)type.Methods).Any((MethodDefinition m) => ((MemberReference)m).Name == methodName)) { MethodDefinition val = new MethodDefinition(methodName, (MethodAttributes)1, assembly.MainModule.TypeSystem.Void); ILProcessor iLProcessor = val.Body.GetILProcessor(); StubMethod(iLProcessor); type.Methods.Add(val); } } public static void StubMethod(ILProcessor processor) { //IL_0005: 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) for (int i = 0; i < 32; i++) { processor.Emit(OpCodes.Nop); } processor.Emit(OpCodes.Ret); } } public class ConfigSaverTask { private readonly HashSet<ConfigFile> m_ConfigFilesToSave = new HashSet<ConfigFile>(); private readonly HashSet<ConfigFile> m_IgnoredConfigFiles = new HashSet<ConfigFile>(); public void ScheduleSaveFor(ConfigFile configFile) { if (configFile == null) { LethalPerformancePatcher.Logger.LogWarning((object)("Null config file passed for save\n" + Environment.StackTrace)); } else if (!m_IgnoredConfigFiles.Contains(configFile)) { m_ConfigFilesToSave.Add(configFile); } } public void AddIgnoredConfigFile(ConfigFile configFile) { if (!m_IgnoredConfigFiles.Add(configFile)) { return; } foreach (ConfigFile ignoredConfigFile in m_IgnoredConfigFiles) { m_ConfigFilesToSave.Remove(ignoredConfigFile); } } public void ScheduleSave() { if (m_ConfigFilesToSave.Count != 0) { Queue<ConfigFile> param = new Queue<ConfigFile>(m_ConfigFilesToSave); m_ConfigFilesToSave.Clear(); AsyncHelper.Schedule(SaveAsync, param); } } public void Save() { if (m_ConfigFilesToSave.Count != 0) { Queue<ConfigFile> queue = new Queue<ConfigFile>(m_ConfigFilesToSave); m_ConfigFilesToSave.Clear(); SaveAsync(queue); } } private Task SaveAsync(Queue<ConfigFile> queue) { int count = queue.Count; ConfigFile result; while (queue.TryDequeue(out result)) { result.Save(); } LethalPerformancePatcher.Logger.LogInfo((object)$"Saved {count} config(s)"); return Task.CompletedTask; } } internal static class UnityPlayerModule { internal static IntPtr BaseAddress { get; private set; } internal static bool IsDebugBuild { get; private set; } internal static bool TryInitialize() { if (BaseAddress != IntPtr.Zero) { return true; } IsDebugBuild = Debug.isDebugBuild; ProcessModule processModule = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().FirstOrDefault((ProcessModule p) => p.ModuleName.Contains("UnityPlayer")); if (processModule == null) { return false; } BaseAddress = processModule.BaseAddress; return BaseAddress != IntPtr.Zero; } internal static IntPtr GetRva(int rva) { return BaseAddress + rva; } } } namespace LethalPerformance.Patcher.TomlConverters { internal class BoolTomlConverter : TypeConverter<bool> { public override bool ConvertToObject(string value) { return bool.Parse(value); } public override string ConvertToString(bool value) { if (!value) { return "false"; } return "true"; } } internal class StringTomlConverter : TypeConverter<string> { private static readonly Regex s_WindowsPathRegex = new Regex("^\"?\\w:\\\\(?!\\\\)(?!.+\\\\\\\\)", RegexOptions.Compiled); public override string ConvertToObject(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } if (s_WindowsPathRegex.IsMatch(value)) { return value; } return Unescape(value); } public override string ConvertToString(string value) { return Escape(value); } private static string Escape(string txt) { if (string.IsNullOrEmpty(txt)) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(txt.Length + 2); foreach (char c in txt) { switch (c) { case '\0': stringBuilder.Append("\\0"); break; case '\a': stringBuilder.Append("\\a"); break; case '\b': stringBuilder.Append("\\b"); break; case '\t': stringBuilder.Append("\\t"); break; case '\n': stringBuilder.Append("\\n"); break; case '\v': stringBuilder.Append("\\v"); break; case '\f': stringBuilder.Append("\\f"); break; case '\r': stringBuilder.Append("\\r"); break; case '\'': stringBuilder.Append("\\'"); break; case '"': stringBuilder.Append("\\\""); break; default: stringBuilder.Append(c); break; } } if (stringBuilder.Length == txt.Length) { return txt; } return stringBuilder.ToString(); } private static string Unescape(string txt) { if (string.IsNullOrEmpty(txt)) { return txt; } int num = txt.IndexOf('\\'); if (num == -1) { return txt; } StringBuilder stringBuilder = new StringBuilder(txt.Length); stringBuilder.Append(txt, 0, num); int num2 = num; while (num2 < txt.Length) { int num3 = txt.IndexOf('\\', num2); if (num3 < 0 || num3 == txt.Length - 1) { num3 = txt.Length; } stringBuilder.Append(txt, num2, num3 - num2); if (num3 >= txt.Length) { break; } char c = txt[num3 + 1]; switch (c) { case '0': stringBuilder.Append('\0'); break; case 'a': stringBuilder.Append('\a'); break; case 'b': stringBuilder.Append('\b'); break; case 't': stringBuilder.Append('\t'); break; case 'n': stringBuilder.Append('\n'); break; case 'v': stringBuilder.Append('\v'); break; case 'f': stringBuilder.Append('\f'); break; case 'r': stringBuilder.Append('\r'); break; case '\'': stringBuilder.Append('\''); break; case '"': stringBuilder.Append('"'); break; case '\\': stringBuilder.Append('\\'); break; default: stringBuilder.Append('\\').Append(c); break; } num2 = num3 + 2; } return stringBuilder.ToString(); } } internal abstract class TypeConverter<T> : TypeConverter where T : IEquatable<T> { protected TypeConverter() { ((TypeConverter)this).ConvertToObject = (string value, Type _) => ConvertToObject(value); ((TypeConverter)this).ConvertToString = (object value, Type _) => ConvertToString((T)value); } public abstract T ConvertToObject(string value); public abstract string ConvertToString(T value); } } namespace LethalPerformance.Patcher.Patches { [HarmonyPatch(typeof(Chainloader))] internal static class Patch_Chainloader { private static Dictionary<string, PluginInfo>? s_PluginsToLoad; private static string? s_ThreadingFilePath; internal static bool IsModWillBeLoaded(string guid) { return s_PluginsToLoad?.ContainsKey(guid) ?? false; } [HarmonyPatch("Initialize")] [HarmonyPostfix] private static void Initialize() { //IL_0055: 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_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown //IL_00b7: Expected O, but got Unknown //IL_00b7: Expected O, but got Unknown try { LethalPerformancePatcher.Harmony.Patch((MethodBase)MethodOf(new Action(Chainloader.Start)), new HarmonyMethod(MethodOf(new Action(Start)), 800, (string[])null, (string[])null, (bool?)null), new HarmonyMethod(MethodOf(new Action(ModsLoaded)), 0, (string[])null, (string[])null, (bool?)null), new HarmonyMethod(MethodOf(new Func<IEnumerable<CodeInstruction>, IEnumerable<CodeInstruction>>(SaveListOfPluginsTranspiler))), (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { LethalPerformancePatcher.Logger.LogWarning((object)ex); } DebugRemoveThreadSafetyCheck(); } private static void Start() { s_ThreadingFilePath = Path.Combine(Application.persistentDataPath, "threadingLogIssues.log"); if (File.Exists(s_ThreadingFilePath)) { File.Delete(s_ThreadingFilePath); } } private static void ModsLoaded() { LethalPerformancePatcher.InvokeOnModsLoaded(); } private static void DebugRemoveThreadSafetyCheck() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown if (UnityPlayerModule.TryInitialize() && UnityPlayerModule.IsDebugBuild) { NativeDetour val = new NativeDetour(UnityPlayerModule.GetRva(16905760), (MethodBase)MethodOf(new Action(StubMethod))); } static void StubMethod() { if (s_ThreadingFilePath != null) { File.AppendAllText(s_ThreadingFilePath, new StackTrace().ToString() + "\n\n"); } } } private static MethodInfo MethodOf(Delegate @delegate) { return @delegate.Method; } private static IEnumerable<CodeInstruction> SaveListOfPluginsTranspiler(IEnumerable<CodeInstruction> codeInstructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Expected O, but got Unknown //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(codeInstructions, (ILGenerator)null); object operand = val.SearchForward((Func<CodeInstruction, bool>)((CodeInstruction c) => c.operand is FieldInfo fieldInfo && fieldInfo.FieldType == typeof(Dictionary<string, PluginInfo>))).Operand; val.Start().MatchForward(true, (CodeMatch[])(object)new CodeMatch[4] { new CodeMatch((OpCode?)OpCodes.Ldloc_0, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldc_I4_0, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Newarr, (object)typeof(string), (string)null), new CodeMatch((OpCode?)OpCodes.Stfld, (object)null, (string)null) }).ThrowIfInvalid("Failed to get injection point") .Insert((CodeInstruction[])(object)new CodeInstruction[3] { new CodeInstruction(OpCodes.Ldloc_0, (object)null), new CodeInstruction(OpCodes.Ldfld, operand), new CodeInstruction(OpCodes.Stsfld, (object)typeof(Patch_Chainloader).GetField("s_PluginsToLoad", AccessTools.all)) }); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(ConfigDefinition))] internal static class Patch_ConfigDefinition { private static readonly MethodInfo s_TargetMethod = typeof(Patch_ConfigDefinition).GetMethod("CheckInvalidConfigCharsOptimized", AccessTools.all); [HarmonyPatch("CheckInvalidConfigChars")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> CallCheckInvalidConfigCharsOptimized() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown return new <>z__ReadOnlyArray<CodeInstruction>((CodeInstruction[])(object)new CodeInstruction[4] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), new CodeInstruction(OpCodes.Call, (object)s_TargetMethod), new CodeInstruction(OpCodes.Ret, (object)null) }); } private static void CheckInvalidConfigCharsOptimized(string value, string name) { if (value == null) { throw new ArgumentNullException(name); } ReadOnlySpan<char> span = value.AsSpan().Trim(); if (!span.SequenceEqual(value)) { throw new ArgumentException("Cannot use whitespace characters at start or end of section and key names", name); } if (span.IndexOfAny(ConfigDefinition._invalidConfigChars) >= 0) { throw new ArgumentException("Cannot use any of the following characters in section and key names: = \\n \\t \\ \" ' [ ]", name); } } } [HarmonyPatch(typeof(ConfigEntryBase))] internal static class Patch_ConfigEntryBase { [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPostfix] public static void ScheduleSave(ConfigFile configFile) { LethalPerformancePatcher.ConfigSaverTask.ScheduleSaveFor(configFile); } [HarmonyPatch("WriteDescription")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> CallWriteDescriptionOptimized() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown return new <>z__ReadOnlyArray<CodeInstruction>((CodeInstruction[])(object)new CodeInstruction[4] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), new CodeInstruction(OpCodes.Call, (object)SymbolExtensions.GetMethodInfo((Expression<Action>)(() => WriteDescriptionOptimized(null, null)))), new CodeInstruction(OpCodes.Ret, (object)null) }); } public static void WriteDescriptionOptimized(ConfigEntryBase instance, StreamWriter writer) { if (!string.IsNullOrEmpty(instance.Description.Description)) { writer.Write("## "); string description = instance.Description.Description; foreach (char c in description) { writer.Write(c); if (c == '\n') { writer.Write("## "); } } writer.WriteLine(); } writer.Write("# Setting type: "); writer.WriteLine(instance.SettingType.Name); writer.Write("# Default value: "); writer.WriteLine(TomlTypeConverter.ConvertToString(instance.DefaultValue, instance.SettingType)); if (instance.Description.AcceptableValues != null) { writer.WriteLine(instance.Description.AcceptableValues.ToDescriptionString()); } else { if (!instance.SettingType.IsEnum) { return; } writer.Write("# Acceptable values: "); string[] orCreate = EnumCacheHelper.GetOrCreate(instance.SettingType); for (int j = 0; j < orCreate.Length; j++) { string value = orCreate[j]; writer.Write(value); if (j != orCreate.Length - 1) { writer.Write(", "); } } writer.WriteLine(); if (instance.SettingType.IsDefined(typeof(FlagsAttribute), inherit: false)) { writer.WriteLine("# Multiple values can be set at the same time by separating them with , (e.g. Debug, Warning)"); } } } } [HarmonyPatch(typeof(ConfigFile))] internal static class Patch_ConfigFile { private static bool s_IgnoreConfigSet; [HarmonyPatch("Reload")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> CallOptimizedReload() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown return new <>z__ReadOnlyArray<CodeInstruction>((CodeInstruction[])(object)new CodeInstruction[3] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Call, (object)SymbolExtensions.GetMethodInfo((Expression<Action>)(() => OptimizedReload(null)))), new CodeInstruction(OpCodes.Ret, (object)null) }); } [HarmonyPatch("Save")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> CallOptimizedSave() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown return new <>z__ReadOnlyArray<CodeInstruction>((CodeInstruction[])(object)new CodeInstruction[3] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Call, (object)SymbolExtensions.GetMethodInfo((Expression<Action>)(() => SaveOptimized(null)))), new CodeInstruction(OpCodes.Ret, (object)null) }); } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPostfix] public static void SetFalseForSaveOnConfigSet(ConfigFile __instance, bool saveOnInit) { s_IgnoreConfigSet = true; __instance.SaveOnConfigSet = false; s_IgnoreConfigSet = false; if (saveOnInit) { LethalPerformancePatcher.ConfigSaverTask.ScheduleSaveFor(__instance); } __instance.SettingChanged += delegate(object _, SettingChangedEventArgs arg) { LethalPerformancePatcher.ConfigSaverTask.ScheduleSaveFor(arg.ChangedSetting.ConfigFile); }; } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPostfix] public static void AddIgnoreIfSetToFalse(ConfigFile __instance, bool value) { if (!s_IgnoreConfigSet && !value) { LethalPerformancePatcher.ConfigSaverTask.AddIgnoredConfigFile(__instance); } } private static void OptimizedReload(ConfigFile instance) { //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Expected O, but got Unknown lock (instance._ioLock) { instance.OrphanedEntries.Clear(); using StreamReader streamReader = new StreamReader(instance.ConfigFilePath, Encoding.UTF8); string text = string.Empty; Span<Range> ranges = stackalloc Range[2]; string text2; while ((text2 = streamReader.ReadLine()) != null) { ReadOnlySpan<char> readOnlySpan = text2.AsSpan().Trim(); if (readOnlySpan.IsEmpty || readOnlySpan.StartsWith("#")) { continue; } if (readOnlySpan.StartsWith("[") && readOnlySpan.EndsWith("]")) { text = readOnlySpan.Slice(1, readOnlySpan.Length - 2).ToString(); } else if (SpanExtensions.Split(readOnlySpan, ranges, '=')) { Range range = ranges[0]; ReadOnlySpan<char> readOnlySpan2 = readOnlySpan[range.Start..range.End].Trim(); range = ranges[1]; ReadOnlySpan<char> readOnlySpan3 = readOnlySpan[range.Start..range.End].Trim(); ConfigDefinition key = new ConfigDefinition(text, readOnlySpan2.ToString()); if (instance.Entries.TryGetValue(key, out var value)) { value.SetSerializedValue(readOnlySpan3.ToString()); } else { instance.OrphanedEntries[key] = readOnlySpan3.ToString(); } } } } instance.OnConfigReloaded(); } private static void SaveOptimized(ConfigFile instance) { lock (instance._ioLock) { string directoryName = Path.GetDirectoryName(instance.ConfigFilePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Span<char> destination = stackalloc char[128]; using StreamWriter streamWriter = new StreamWriter(instance.ConfigFilePath, append: false, Utility.UTF8NoBom); if (instance._ownerMetadata != null) { streamWriter.Write("## Settings file was created by plugin "); streamWriter.Write(instance._ownerMetadata.Name); streamWriter.Write(" v"); if (instance._ownerMetadata.Version != null) { instance._ownerMetadata.Version.TryFormat(destination, out var charsWritten); streamWriter.WriteLine(destination.Slice(0, charsWritten)); } streamWriter.Write("## Plugin GUID: "); streamWriter.WriteLine(instance._ownerMetadata.GUID); streamWriter.WriteLine(); } var second = instance.OrphanedEntries.Select((KeyValuePair<ConfigDefinition, string> x) => new { Key = x.Key, entry = (ConfigEntryBase)null, value = x.Value }); var first = instance.Entries.Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> x) => new { Key = x.Key, entry = x.Value, value = (string)null }); var orderedEnumerable = from x in first.Concat(second) group x by x.Key.Section into x orderby x.Key select x; foreach (var item in orderedEnumerable) { streamWriter.Write('['); streamWriter.Write(item.Key); streamWriter.WriteLine(']'); foreach (var item2 in item) { streamWriter.WriteLine(); ConfigEntryBase entry = item2.entry; if (entry != null) { entry.WriteDescription(streamWriter); } object obj = item2.value; if (obj == null) { ConfigEntryBase entry2 = item2.entry; obj = ((entry2 != null) ? entry2.GetSerializedValue() : null) ?? string.Empty; } string value = (string)obj; streamWriter.Write(item2.Key.Key); streamWriter.Write(" = "); streamWriter.WriteLine(value); } streamWriter.WriteLine(); } } } } [HarmonyPatch] internal class Patch_FileSystemWatcher { private static readonly MethodInfo? s_StartDispatching; private static readonly FieldInfo? s_Watches; static Patch_FileSystemWatcher() { Type type = typeof(FileSystemWatcher).Assembly.GetType("System.IO.DefaultWatcher", throwOnError: false); if (!(type == null)) { s_StartDispatching = type.GetMethod("StartDispatching", AccessTools.all); s_Watches = type.GetField("watches", AccessTools.all); s_Watches?.SetValue(null, new Hashtable()); } } [HarmonyPrepare] private static bool ShouldPatch() { return s_StartDispatching != null; } [HarmonyTargetMethod] private static MethodInfo? GetTargetPatch() { return s_StartDispatching; } [HarmonyPrefix] private static bool DisableDefaultWatcher() { return false; } } } namespace LethalPerformance.Patcher.Helpers { internal static class AsyncHelper { public static void Schedule(Func<Task> func) { Task.Run(async delegate { try { await func(); } catch (Exception ex) { LethalPerformancePatcher.Logger.LogError((object)ex); } }); } public static void Schedule<T>(Func<T, Task> func, T param1) { Task.Run(async delegate { try { await func(param1); } catch (Exception ex) { LethalPerformancePatcher.Logger.LogError((object)ex); } }); } } internal static class EnumCacheHelper { private static readonly Dictionary<Type, string[]> s_EnumNamesCache = new Dictionary<Type, string[]>(); public static string[] GetOrCreate(Type enumType) { if (s_EnumNamesCache.Count >= 255) { s_EnumNamesCache.Clear(); } if (s_EnumNamesCache.TryGetValue(enumType, out string[] value)) { return value; } string[] names = Enum.GetNames(enumType); s_EnumNamesCache[enumType] = names; return names; } } internal static class SpanExtensions { public static bool Split(ReadOnlySpan<char> input, Span<Range> ranges, char separator) { if (ranges.IsEmpty && ranges.Length != 2) { return false; } for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c == separator) { ranges[0] = 0..i; ranges[1] = (i + 1)..input.Length; return true; } } return false; } } } namespace LethalPerformance.Patcher.AssemblyPatches { internal static class Patch_AssemblyCSharp { public static void Patch(AssemblyDefinition assembly) { Dictionary<string, Action<AssemblyDefinition, TypeDefinition>> dictionary = new Dictionary<string, Action<AssemblyDefinition, TypeDefinition>> { { "AudioReverbPresets", delegate(AssemblyDefinition a, TypeDefinition t) { AssemblyPatcherUtilities.AddMethod(a, t, "Awake"); } } }; foreach (KeyValuePair<string, Action<AssemblyDefinition, TypeDefinition>> item in dictionary) { item.Deconstruct(out var key, out var value); string text = key; Action<AssemblyDefinition, TypeDefinition> action = value; TypeDefinition type = assembly.MainModule.GetType(text); if (type == null) { LethalPerformancePatcher.Logger.LogWarning((object)("Failed to patch " + text)); } else { action(assembly, type); } } } } internal static class Patch_ES3 { public static void Patch(AssemblyDefinition assembly) { TypeDefinition type = assembly.MainModule.GetType("ES3"); TypeDefinition type2 = assembly.MainModule.GetType("ES3Settings"); PatchSave(assembly, type, (TypeReference)(object)type2); PatchLoad(assembly, type, (TypeReference)(object)type2); PatchSerialize(assembly, type); TypeDefinition type3 = assembly.MainModule.GetType("ES3File"); PatchFileSave(assembly, type3, type2); } private static void PatchFileSave(AssemblyDefinition assembly, TypeDefinition es3FileType, TypeDefinition es3SettingsType) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) MethodDefinition val = ((IEnumerable<MethodDefinition>)es3FileType.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "Save")); MethodDefinition val2 = AddNonGenericMethod(assembly, es3FileType, null, "LethalPerformance_Save", (MethodAttributes)6); Extensions.InsertRange<Instruction>(val.Body.Instructions, 0, (IEnumerable<Instruction>)new <>z__ReadOnlyArray<Instruction>((Instruction[])(object)new Instruction[2] { Instruction.Create(OpCodes.Ldarg_0), Instruction.Create(OpCodes.Call, (MethodReference)(object)val2) })); } private static void PatchSave(AssemblyDefinition assembly, TypeDefinition es3Type, TypeReference es3SettingsType) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) MethodDefinition val = ((IEnumerable<MethodDefinition>)es3Type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "Save" && ((MethodReference)m).Parameters.Count == 3 && ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[2]).ParameterType).Name == "ES3Settings" && ((MethodReference)m).HasGenericParameters)); if (val == null) { LethalPerformancePatcher.Logger.LogWarning((object)"ES3.Save doesn't exists. Removed by other mod?"); return; } ParameterDefinition parameter = new ParameterDefinition("settings", (ParameterAttributes)0, es3SettingsType); MethodDefinition val2 = AddNonGenericMethod(assembly, es3Type, parameter, "LethalPerformance_Save", (MethodAttributes)22); Collection<Instruction> instructions = val.Body.Instructions; Instruction[] array = new Instruction[2]; OpCode ldarg = OpCodes.Ldarg; Collection<ParameterDefinition> parameters = ((MethodReference)val).Parameters; array[0] = Instruction.Create(ldarg, parameters[parameters.Count - 1]); array[1] = Instruction.Create(OpCodes.Call, (MethodReference)(object)val2); Extensions.InsertRange<Instruction>(instructions, 0, (IEnumerable<Instruction>)new <>z__ReadOnlyArray<Instruction>((Instruction[])(object)array)); } private static void PatchLoad(AssemblyDefinition assembly, TypeDefinition es3Type, TypeReference es3SettingsType) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) List<MethodDefinition> list = ((IEnumerable<MethodDefinition>)es3Type.Methods).Where(delegate(MethodDefinition m) { if (((MemberReference)m).Name != "Load" || !((MethodReference)m).ReturnType.IsGenericParameter) { return false; } if (((MethodReference)m).Parameters.Count == 2 && ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).Name == "String" && ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[1]).ParameterType).Name == "ES3Settings") { return true; } return (((MethodReference)m).Parameters.Count == 3 && ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[0]).ParameterType).Name == "String" && ((ParameterReference)((MethodReference)m).Parameters[1]).ParameterType.IsGenericParameter && ((MemberReference)((ParameterReference)((MethodReference)m).Parameters[2]).ParameterType).Name == "ES3Settings") ? true : false; }).ToList(); if (list.Count != 2) { LethalPerformancePatcher.Logger.LogWarning((object)"Detected ES3.Load mismatch of count"); return; } ParameterDefinition parameter = new ParameterDefinition("settings", (ParameterAttributes)0, es3SettingsType); MethodDefinition val = AddNonGenericMethod(assembly, es3Type, parameter, "LethalPerformance_Load", (MethodAttributes)22); foreach (MethodDefinition item in list) { Collection<Instruction> instructions = item.Body.Instructions; Instruction[] array = new Instruction[2]; OpCode ldarg = OpCodes.Ldarg; Collection<ParameterDefinition> parameters = ((MethodReference)item).Parameters; array[0] = Instruction.Create(ldarg, parameters[parameters.Count - 1]); array[1] = Instruction.Create(OpCodes.Call, (MethodReference)(object)val); Extensions.InsertRange<Instruction>(instructions, 0, (IEnumerable<Instruction>)new <>z__ReadOnlyArray<Instruction>((Instruction[])(object)array)); } } private static void PatchSerialize(AssemblyDefinition assembly, TypeDefinition es3Type) { //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: 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_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_016a: 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) MethodDefinition val = ((IEnumerable<MethodDefinition>)es3Type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "Serialize" && ((MethodReference)m).Parameters.Count == 2)); MethodDefinition val2 = ((IEnumerable<MethodDefinition>)es3Type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "Serialize" && ((MethodReference)m).Parameters.Count == 3)); MethodDefinition val3 = ((IEnumerable<MethodDefinition>)assembly.MainModule.GetType("ES3Internal.ES3TypeMgr").Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "GetOrCreateES3Type")); val.Body.Instructions.Clear(); Extensions.AddRange<Instruction>(val.Body.Instructions, (IEnumerable<Instruction>)new <>z__ReadOnlyArray<Instruction>((Instruction[])(object)new Instruction[10] { Instruction.Create(OpCodes.Ldarg_0), Instruction.Create(OpCodes.Box, ((ParameterReference)((MethodReference)val).Parameters[0]).ParameterType), Instruction.Create(OpCodes.Ldarga, ((MethodReference)val).Parameters[0]), Instruction.Create(OpCodes.Constrained, ((ParameterReference)((MethodReference)val).Parameters[0]).ParameterType), Instruction.Create(OpCodes.Callvirt, assembly.MainModule.ImportReference((MethodBase)typeof(object).GetMethod("GetType"))), Instruction.Create(OpCodes.Ldc_I4_1), Instruction.Create(OpCodes.Call, (MethodReference)(object)val3), Instruction.Create(OpCodes.Ldarg_1), Instruction.Create(OpCodes.Call, (MethodReference)(object)val2), Instruction.Create(OpCodes.Ret) })); } private static MethodDefinition AddNonGenericMethod(AssemblyDefinition assembly, TypeDefinition es3Type, ParameterDefinition? parameter, string name, MethodAttributes attributes = (MethodAttributes)22) { //IL_0001: 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_0019: Expected O, but got Unknown MethodDefinition val = new MethodDefinition(name, attributes, assembly.MainModule.TypeSystem.Void); if (parameter != null) { ((MethodReference)val).Parameters.Add(parameter); } AssemblyPatcherUtilities.StubMethod(val.Body.GetILProcessor()); es3Type.Methods.Add(val); return val; } } internal static class Patch_ProxyDoorwayConnection { public static void Patch(AssemblyDefinition assembly) { //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Expected O, but got Unknown ModuleDefinition mainModule = assembly.MainModule; TypeDefinition type = mainModule.GetType("DunGen.ProxyDoorwayConnection"); if (type == null) { LethalPerformancePatcher.Logger.LogWarning((object)"Failed to patch ProxyDoorwayConnection"); return; } TypeReference openEquatableDef = mainModule.ImportReference(typeof(IEquatable<>)); if (!((IEnumerable<InterfaceImplementation>)type.Interfaces).Any((InterfaceImplementation i) => ((MemberReference)i.InterfaceType.GetElementType()).FullName == ((MemberReference)openEquatableDef).FullName)) { MethodDefinition val = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "get_A")); MethodDefinition val2 = ((IEnumerable<MethodDefinition>)type.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => ((MemberReference)m).Name == "get_B")); if (val == null || val2 == null) { LethalPerformancePatcher.Logger.LogWarning((object)"Failed to patch ProxyDoorwayConnection"); return; } GenericInstanceType val3 = new GenericInstanceType(openEquatableDef); val3.GenericArguments.Add((TypeReference)(object)type); type.Interfaces.Add(new InterfaceImplementation((TypeReference)(object)val3)); type.Methods.Add(CreateEqualsMethod(mainModule, type, val, val2)); } } private static MethodDefinition CreateEqualsMethod(ModuleDefinition module, TypeDefinition type, MethodDefinition getA, MethodDefinition getB) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004d: 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_0064: 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_007c: 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_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: 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_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) MethodDefinition val = new MethodDefinition("Equals", (MethodAttributes)454, module.TypeSystem.Boolean); ParameterDefinition val2 = new ParameterDefinition("other", (ParameterAttributes)0, (TypeReference)(object)type); ((MethodReference)val).Parameters.Add(val2); ILProcessor iLProcessor = val.Body.GetILProcessor(); Instruction val3 = iLProcessor.Create(OpCodes.Ldc_I4_0); iLProcessor.Emit(OpCodes.Ldarg_0); iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)getA); iLProcessor.Emit(OpCodes.Ldarga, val2); iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)getA); iLProcessor.Emit(OpCodes.Bne_Un, val3); iLProcessor.Emit(OpCodes.Ldarg_0); iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)getB); iLProcessor.Emit(OpCodes.Ldarga, val2); iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)getB); iLProcessor.Emit(OpCodes.Ceq); iLProcessor.Emit(OpCodes.Ret); iLProcessor.Append(val3); iLProcessor.Emit(OpCodes.Ret); return val; } } } namespace LethalPerformance.Patcher.API { internal static class HarmonyExceptionHandler { public static Exception? ReportException(Exception? exception) { if (exception != null) { LethalPerformancePatcher.Logger.LogWarning((object)exception); LethalPerformancePatcher.Logger.LogWarning((object)Environment.StackTrace); } return null; } } [AttributeUsage(AttributeTargets.Method)] internal sealed class InitializeOnAwakeAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }