Decompiled source of LethalPerformance v1.1.5
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.UpdateShaderVariablesXRCB_00000003$BurstDirectCall))] [assembly: StaticTypeReinit(typeof(LethalPerformance.Unity.UpdateShaderVariablesGlobalCB_00000004$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() { MonoScriptData result = default(MonoScriptData); result.FilePathsData = new byte[48] { 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 }; result.TypesData = new byte[238] { 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 }; result.TotalFiles = 1; result.TotalTypes = 4; result.IsEditorOnly = false; return result; } } namespace LethalPerformance.Unity; [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_00000003$PostfixBurstDelegate(in ReadableViewConstants* xrViewConstants, in int viewCount, ReadableShaderVariablesXR* cb); internal static class UpdateShaderVariablesXRCB_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(UpdateShaderVariablesXRCB_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 UpdateShaderVariablesXRCB_00000003$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_00000004$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_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(UpdateShaderVariablesGlobalCB_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 UpdateShaderVariablesGlobalCB_00000004$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_00000003$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_00000004$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 * 15), (void*)(&xrViewConstants[i].viewMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRInvViewMatrix + i * 15), (void*)(&xrViewConstants[i].invViewMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRProjMatrix + i * 15), (void*)(&xrViewConstants[i].projMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRInvProjMatrix + i * 15), (void*)(&xrViewConstants[i].invProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRViewProjMatrix + i * 15), (void*)(&xrViewConstants[i].viewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRInvViewProjMatrix + i * 15), (void*)(&xrViewConstants[i].invViewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRNonJitteredViewProjMatrix + i * 15), (void*)(&xrViewConstants[i].nonJitteredViewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPrevViewProjMatrix + i * 15), (void*)(&xrViewConstants[i].prevViewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPrevInvViewProjMatrix + i * 15), (void*)(&xrViewConstants[i].prevInvViewProjMatrix), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRViewProjMatrixNoCameraTrans + i * 15), (void*)(&xrViewConstants[i].viewProjectionNoCameraTrans), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPrevViewProjMatrixNoCameraTrans + i * 15), (void*)(&xrViewConstants[i].prevViewProjMatrixNoCameraTrans), (long)Unsafe.SizeOf<float4x4>()); UnsafeUtility.MemCpy((void*)(cb->_XRPixelCoordToViewDirWS + i * 15), (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() { CameraBurst.UpdateShaderVariablesXRCB_00000003$BurstDirectCall.Initialize(); CameraBurst.UpdateShaderVariablesGlobalCB_00000004$BurstDirectCall.Initialize(); } }
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.Binary; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; 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 GameNetcodeStuff; using HarmonyLib; using HarmonyLib.Tools; using LethalPerformance.API; using LethalPerformance.Caching; using LethalPerformance.Configuration; using LethalPerformance.Extensions; using LethalPerformance.Patcher; using LethalPerformance.Patcher.API; using LethalPerformance.Patcher.Patches; using LethalPerformance.Unity; using LethalPerformance.Utilities; using Microsoft.CodeAnalysis; 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.EventSystems; using UnityEngine.InputSystem; using UnityEngine.Pool; 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("Unity.Netcode.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalPerformance")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.1.5.0")] [assembly: AssemblyInformationalVersion("1.1.5+95da822352e6628bd0c0d40005917e0d4c6eb134")] [assembly: AssemblyProduct("LethalPerformance")] [assembly: AssemblyTitle("LethalPerformance")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.5.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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 static bool IsModLoaded(string id) { if (!Chainloader.PluginInfos.ContainsKey(id)) { return Patch_Chainloader.IsModWillBeLoaded(id); } return true; } } [BepInPlugin("LethalPerformance", "LethalPerformance", "1.1.5")] [BepInDependency(/*Could not decode attribute arguments.*/)] 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); Application.SetStackTraceLogType((LogType)3, (StackTraceLogType)0); Application.SetStackTraceLogType((LogType)2, (StackTraceLogType)0); Application.SetStackTraceLogType((LogType)0, (StackTraceLogType)0); Application.SetStackTraceLogType((LogType)1, (StackTraceLogType)0); LoadGameBurstLib(); InitializeHarmony(); CallInitializeOnAwake(); InitializeSaveScheduler(); } 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() { foreach (MethodInfo item in from m in typeof(LethalPerformancePlugin).Assembly.GetTypes().SelectMany((Type t) => t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) where ((MemberInfo)m).GetCustomAttribute<InitializeOnAwakeAttribute>() != null select m) { item.Invoke(null, null); Logger.LogInfo((object)("Initialized " + GeneralExtensions.FullDescription((MethodBase)item))); } } 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.1.5"; } } 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; goto end_IL_0089; } } continue; end_IL_0089: 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).Dispose(); } } finally { ((IDisposable)val).Dispose(); } } } } namespace LethalPerformance.Utilities { 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 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_0090: 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.hdShadowInitParams.cachedAreaLightShadowAtlas = 8192; currentPlatformRenderPipelineSettings.hdShadowInitParams.cachedPunctualLightShadowAtlas = 8192; currentPlatformRenderPipelineSettings.hdShadowInitParams.allowDirectionalMixedCachedShadows = true; bool flag = (currentPlatformRenderPipelineSettings.supportVolumetrics = SystemInfo.supportsRenderTargetArrayIndexFromVertexShader); val.currentPlatformRenderPipelineSettings = currentPlatformRenderPipelineSettings; HDRenderPipelineGlobalSettings instance = HDRenderPipelineGlobalSettings.instance; 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)5, true); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)22, false); LethalPerformancePlugin.Instance.Logger.LogInfo((object)"Disabled StopNan and enabled DepthPrepassWithDeferredRendering globally"); 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(AudioReverbTrigger), "OnTriggerStay")] internal static class Patch_AudioReverbTrigger { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyTranspiler] public static IEnumerable<CodeInstruction> FixTagAllocation(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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); MethodInfo getMethod = typeof(GameObject).GetProperty("tag", AccessTools.all).GetMethod; val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Callvirt, (object)getMethod, (string)null), new CodeMatch((OpCode?)OpCodes.Ldstr, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null) }).RemoveInstructions(3).Insert((CodeInstruction[])(object)new CodeInstruction[1] { CodeInstruction.Call<GameObject, bool>((Expression<Func<GameObject, bool>>)((GameObject x) => ObjectExtensions.ComparePlayerRagdollTag(x))) }); return val.Instructions(); } } [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(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(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* ptr3 = __instance.m_XRViewConstants) { void* ptr4 = ptr3; ReadableViewConstants* ptr5 = (ReadableViewConstants*)ptr4; int viewCount = __instance.viewCount; CameraBurst.UpdateShaderVariablesXRCB(ref ptr5, 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* ptr3 = &__instance.mainViewConstants) { void* ptr4 = ptr3; fixed (Vector4* ptr5 = __instance.frustumPlaneEquations) { void* ptr6 = ptr5; 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* ptr7 = (ReadableViewConstants*)ptr4; float4* ptr8 = (float4*)ptr6; 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 ptr7, ref val, ref val2, ref val3, ref ptr8, 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(PlayerControllerB))] internal static class Patch_PlayerControllerB { private static Vector3[] s_Normals; [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("CalculateGroundNormal")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> UseStaticField(IEnumerable<CodeInstruction> instructions) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); short value = OpCodes.Ldc_I4_0.Value; OpCode opcode = list[0].opcode; int num = opcode.Value - value; if (num < 0 || num >= OpCodes.Ldc_I4_8.Value) { return list; } s_Normals = (Vector3[])(object)new Vector3[num + 1]; list.RemoveRange(0, 2); FieldInfo field = typeof(Patch_PlayerControllerB).GetField("s_Normals", AccessTools.all); list.Insert(0, new CodeInstruction(OpCodes.Ldsfld, (object)field)); return list; } } [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(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 { [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).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; } } } 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() { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) if (!Dependencies.IsModLoaded("io.daxcess.lcvr")) { GameObject val = GameObject.Find("/Systems/UI/UICamera"); HDAdditionalCameraData val2 = default(HDAdditionalCameraData); if (!((Object)(object)val == (Object)null) && val.TryGetComponent<HDAdditionalCameraData>(ref val2)) { ref FrameSettingsOverrideMask renderingPathCustomFrameSettingsOverrideMask = ref val2.renderingPathCustomFrameSettingsOverrideMask; ref FrameSettings renderingPathCustomFrameSettings = ref val2.renderingPathCustomFrameSettings; ((BitArray128)(ref renderingPathCustomFrameSettingsOverrideMask.mask))[127u] = true; ((BitArray128)(ref renderingPathCustomFrameSettings.bitDatas))[127u] = false; ((BitArray128)(ref renderingPathCustomFrameSettingsOverrideMask.mask))[79u] = true; ((BitArray128)(ref renderingPathCustomFrameSettings.bitDatas))[79u] = false; val2.probeLayerMask = LayerMask.op_Implicit(0); } } } } [HarmonyPatch(typeof(NavMeshSurface))] internal static class Patch_NavMeshSurface { private static int s_LastCalledSceneId = -1; private static readonly UnsafeCachedInstance<ItemDropship> s_ItemDropship = UnsafeCacheManager.AddReferenceToMap<ItemDropship>((UnsafeCachedInstance<ItemDropship>)new ManualCachedInstance<ItemDropship>()); private static readonly UnsafeCachedInstance<RuntimeDungeon> s_RuntimeDungeon = UnsafeCacheManager.AddReferenceToMap<RuntimeDungeon>((UnsafeCachedInstance<RuntimeDungeon>)new ManualCachedInstance<RuntimeDungeon>()); [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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0051: 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) { if (((Scene)(ref lastLoadedScene)).rootCount == 0) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)("New scene loading triggered navmesh, but no roots on the scene! Mod initializing navmesh early?\n" + Environment.StackTrace)); } else if (!FindDropship(lastLoadedScene) || !FindDungeon(lastLoadedScene)) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)("New scene loading triggered navmesh, but nothing found! Mod initializing navmesh early?\n" + Environment.StackTrace)); } else { 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; } } return false; } finally { ((IDisposable)val2).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; } } return false; } finally { ((IDisposable)val2).Dispose(); } } [HarmonyPatch("OnDisable")] [HarmonyPostfix] public static void OnDisable() { //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); } } } } } namespace LethalPerformance.Patches.Mods { [HarmonyPatch] internal static class Patch_MoreSuits { private static readonly MethodInfo? s_MethodToPatch; static Patch_MoreSuits() { if (Chainloader.PluginInfos.TryGetValue("x753.More_Suits", out var value)) { Type type = AccessTools.Inner(((object)value.Instance).GetType(), "StartOfRoundPatch"); if (type != null) { s_MethodToPatch = type.GetMethod("StartPatch", AccessTools.all); } if (s_MethodToPatch == null) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)"Failed to find MoreSuits method to patch"); } } } [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPrepare] public static bool ShouldPatch() { return s_MethodToPatch != null; } [HarmonyTargetMethod] public static MethodBase GetTargetMethod() { return s_MethodToPatch; } [HarmonyTranspiler] public static IEnumerable<CodeInstruction> OptimizeSuitsTextures(IEnumerable<CodeInstruction> codeInstructions) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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 CodeMatcher val = new CodeMatcher(codeInstructions, (ILGenerator)null); ConstructorInfo textureConstructor = typeof(Texture2D).GetConstructor(new Type[4] { typeof(int), typeof(int), typeof(TextureFormat), typeof(bool) }); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Ldc_I4_2, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldc_I4_2, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Newobj, (object)null, (string)null) }).Repeat((Action<CodeMatcher>)delegate(CodeMatcher m) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown m.SetOpcodeAndAdvance(OpCodes.Ldc_I4_4).SetOpcodeAndAdvance(OpCodes.Ldc_I4_4).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldc_I4, (object)12), new CodeInstruction(OpCodes.Ldc_I4_1, (object)null) }) .SetOperandAndAdvance((object)textureConstructor); }, (Action<string>)null); return val.InstructionEnumeration(); } } } namespace LethalPerformance.Metrics { [HarmonyPatch(typeof(ProfilingSampler))] [IgnoredByDeepProfiler] internal static class Patch_ProfilingSampler { [HarmonyPrepare] public static bool ShouldPatch() { return Debug.isDebugBuild; } [HarmonyPatch("Begin")] [HarmonyPostfix] public static void Begin(ProfilingSampler __instance) { CustomSampler inlineSampler = __instance.inlineSampler; if (inlineSampler != null) { inlineSampler.Begin(); } } [HarmonyPatch("End")] [HarmonyPostfix] public static void End(ProfilingSampler __instance) { CustomSampler inlineSampler = __instance.inlineSampler; if (inlineSampler != null) { inlineSampler.End(); } } } [HarmonyPatch(typeof(ProfilingScope))] [IgnoredByDeepProfiler] internal static class Patch_ProfilingScope { private sealed class ProfilingScopeData { public CommandBuffer m_CommandBuffer; public ProfilingSampler? m_Sampler; } private static readonly Stack<ProfilingScopeData> s_ProfilingScopeDatas = new Stack<ProfilingScopeData>(); [HarmonyPrepare] public static bool ShouldPatch() { return Debug.isDebugBuild; } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPrefix] public static void StartProfiler(CommandBuffer cmd, ProfilingSampler? sampler) { ProfilingScopeData profilingScopeData = UnsafeGenericPool<ProfilingScopeData>.Get(); profilingScopeData.m_Sampler = sampler; profilingScopeData.m_CommandBuffer = cmd; s_ProfilingScopeDatas.Push(profilingScopeData); if (sampler != null) { sampler.Begin(cmd); } } [HarmonyPatch("Dispose")] [HarmonyPrefix] public static void StopProfiler() { if (s_ProfilingScopeDatas.TryPop(out ProfilingScopeData result)) { ProfilingSampler? sampler = result.m_Sampler; if (sampler != null) { sampler.End(result.m_CommandBuffer); } result.m_Sampler = null; result.m_CommandBuffer = null; UnsafeGenericPool<ProfilingScopeData>.Release(result); } } } } namespace LethalPerformance.Extensions { internal static class BinaryPrimitivesExtension { public static void WriteSingleLittleEndian(Span<byte> destination, float value) { if (BitConverter.IsLittleEndian) { MemoryMarshal.Write(destination, ref value); return; } int value2 = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); MemoryMarshal.Write(destination, ref value2); } } internal static class CodeMatcherExtensions { public static CodeMatcher GetOperand(this CodeMatcher matcher, out object operand) { operand = matcher.Operand; return matcher; } } internal static class TransformExtensions { public static string GetScenePath(this Transform transform) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('/').Append(((Object)transform).name); Transform parent; while (Object.op_Implicit((Object)(object)(parent = transform.parent))) { stringBuilder.Insert(0, ((Object)parent).name).Insert(0, '/'); transform = parent; } return stringBuilder.ToString(); } } } namespace LethalPerformance.EasySave3 { internal static class ES3Utilities { public static void ForceToCache(ES3Settings settings) { //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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_0019: Unknown result type (might be due to invalid IL or missing references) Location location = settings._location; if (((int)location == 0 || (int)location == 4) ? true : false) { settings._location = (Location)4; } } public static void LoadFileToCache(ES3Settings settings) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0030: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown //IL_008b: 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_0062: Expected O, but got Unknown //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) if ((int)settings.encryptionType != 0) { settings.encryptionType = (EncryptionType)0; } if (ES3File.cachedFiles.ContainsKey(settings.path)) { return; } ES3Settings val = (ES3Settings)settings.Clone(); val._location = (Location)0; Location location = settings._location; settings._location = (Location)0; string fullPath = settings.FullPath; settings._location = location; if (!File.Exists(fullPath)) { ES3File val2 = new ES3File(val, false); val2.syncWithFile = true; ES3File.cachedFiles[settings.path] = val2; return; } ES3Settings val3 = (ES3Settings)settings.Clone(); val3._location = (Location)0; if (CheckFileEncrypted(fullPath)) { val3.encryptionType = (EncryptionType)1; } ES3File.cachedFiles[settings.path] = new ES3File(ES3.LoadRawBytes(val3), val); } private static bool CheckFileEncrypted(string path) { using FileStream fileStream = File.OpenRead(path); ReadOnlySpan<byte> other = "{\""u8; Span<byte> span = stackalloc byte[2]; int num = fileStream.Read(span); return num != 2 || !span.SequenceEqual(other); } } [HarmonyPatch(typeof(ES3))] internal static class Patch_ES3 { [HarmonyPatch("DeleteFile", new Type[] { typeof(ES3Settings) })] [HarmonyPostfix] internal static void DeleteCachedFile(ES3Settings settings) { ES3File.cachedFiles.Remove(settings.path); } [HarmonyPatch("RenameFile", new Type[] { typeof(ES3Settings), typeof(ES3Settings) })] [HarmonyPostfix] internal static void RenameCachedFile(ES3Settings oldSettings, ES3Settings newSettings) { if (ES3File.cachedFiles.Remove(oldSettings.path, out var value)) { ES3File.cachedFiles[newSettings.path] = value; } } [HarmonyPatch("GetKeys", new Type[] { typeof(ES3Settings) })] [HarmonyPatch("KeyExists", new Type[] { typeof(string), typeof(ES3Settings) })] [HarmonyPatch("DeleteKey", new Type[] { typeof(string), typeof(ES3Settings) })] [HarmonyPatch("LethalPerformance_Load")] [HarmonyPatch("LethalPerformance_Save")] [HarmonyPrefix] internal static void UseCache(ES3Settings settings) { ES3Utilities.ForceToCache(settings); ES3Utilities.LoadFileToCache(settings); } } [HarmonyPatch(typeof(ES3File))] internal static class Patch_ES3File { [HarmonyPatch("KeyExists", new Type[] { typeof(string), typeof(ES3Settings) })] [HarmonyPrefix] public static void KeyExists(ES3Settings settings) { ES3Utilities.ForceToCache(settings); ES3Utilities.LoadFileToCache(settings); } [HarmonyPatch("LethalPerformance_Save")] [HarmonyPrefix] public static void ScheduleSave(ES3File __instance) { LethalPerformancePlugin.Instance.ES3SaverTask.ScheduleSaveFor(__instance); } } } namespace LethalPerformance.Configuration { internal class AcceptableValueEnum<T> : AcceptableValueBase where T : struct { private static readonly string[] s_EnumValues = Enum.GetNames(typeof(T)); public AcceptableValueEnum() : base(typeof(T)) { if (s_EnumValues.Length == 0) { throw new ArgumentException("Enum should have any value"); } } public override object Clamp(object value) { if (((AcceptableValueBase)this).IsValid(value)) { return value; } return Enum.Parse<T>(s_EnumValues[0]); } public override bool IsValid(object value) { return Enum.IsDefined(typeof(T), value); } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", s_EnumValues); } } internal class ConfigManager { private readonly ConfigFile m_Config; public ConfigEntry<CookieAtlasResolutionLimited> CookieAtlasResolution { get; private set; } public ConfigEntry<ReflectionProbeTextureCacheResolution> ReflectionProbeCacheResolution { get; private set; } public ConfigEntry<bool> CacheEntranceTeleports { get; private set; } public ConfigManager(ConfigFile config) { m_Config = config; BindConfig(); } private void BindConfig() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown CookieAtlasResolution = BindRenderingConfig("Rendering", "Cookie atlas texture resolution", CookieAtlasResolutionLimited.CookieResolution1024, new ConfigDescription("Sets cookie light atlas texture resolution. By default 1024 is enough for vanilla, but some mods can use custom cookie texture, causing this log spam:\n\"No more space in the 2D Cookie Texture Atlas. To solve this issue, increase the resolution of the cookie atlas in the HDRP settings\".\n\nTo fix it just increase the resolution of texture atlas.", (AcceptableValueBase)(object)new AcceptableValueEnum<CookieAtlasResolutionLimited>(), Array.Empty<object>())); ReflectionProbeCacheResolution = BindRenderingConfig<ReflectionProbeTextureCacheResolution>("Rendering", "Reflection probe atlas texture resolution", (ReflectionProbeTextureCacheResolution)134218752, new ConfigDescription("Sets reflection probe cache resolution. By default it's 16384x8192 causing high RAM usage (~1GB) even if vanilla game doesn't use them at all. But some mods may use, so it may cause this log spam:\n\"No more space in Reflection Probe Atlas. To solve this issue, increase the size of the Reflection Probe Atlas in the HDRP settings\".\n\nTo fix it just increase the resolution of texture atlas.", (AcceptableValueBase)(object)new AcceptableValueEnum<ReflectionProbeTextureCacheResolution>(), Array.Empty<object>())); CacheEntranceTeleports = m_Config.Bind<bool>("Caching", "Cache entrance teleport", true, "Should Entrance Teleport be cached for better performance. Note it causing blocked entrance on some custom interiors.\nYou can find the tracking issue here: https://github.com/DiFFoZ/LethalPerformance/issues/15\n\nIf you see this popup, it means that interior is misconfigurated and causing Lethal Performance to confuse about where the entrance teleport should be.\n\nKnown mods that causing this issue:\n- [Tartarus](https://thunderstore.io/c/lethal-company/p/Teaisnt/Tartarus/)\n- [Sector Alpha](https://thunderstore.io/c/lethal-company/p/v0xx/SectorAlpha_Interior/)\n- [Hadal Laboratories](https://thunderstore.io/c/lethal-company/p/Tolian/Hadal_Laboratories/)\n- [MapImprovements](https://thunderstore.io/c/lethal-company/p/SpookyBuddy/MapImprovements/)\n\nTo fix the issue you can set CacheEntranceTeleports to false or remove these mods above, until they fix the issue on their side."); } private ConfigEntry<T> BindRenderingConfig<T>(string section, string key, T defaultValue, ConfigDescription? description) { ConfigEntry<T> val = m_Config.Bind<T>(section, key, defaultValue, description); val.SettingChanged += UpdateRenderingAsset; return val; } private ConfigEntry<T> BindHarmonyConfig<T>(string section, string key, T defaultValue, string? description) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) ConfigDescription val = ((description == null) ? ((ConfigDescription)null) : new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); ConfigEntry<T> val2 = m_Config.Bind<T>(section, key, defaultValue, val); val2.SettingChanged += RepatchHarmony; return val2; } private static void UpdateRenderingAsset(object _, EventArgs __) { HDRenderPipelineAssetOptimizer.Initialize(); } private static void RepatchHarmony(object _, EventArgs __) { LethalPerformancePlugin.Instance.Logger.LogInfo((object)"Config option of Harmony got changed, repatching..."); Harmony harmony = LethalPerformancePlugin.Instance.Harmony; if (harmony == null) { return; } try { harmony.UnpatchSelf(); harmony.PatchAll(typeof(ConfigManager).Assembly); } catch (Exception ex) { LethalPerformancePlugin.Instance.Logger.LogError((object)("Failed to repatch with Harmony\n" + ex)); } } } internal enum CookieAtlasResolutionLimited { CookieResolution1024 = 0x400, CookieResolution2048 = 0x800, CookieResolution4096 = 0x1000, CookieResolution8192 = 0x2000, CookieResolution16384 = 0x4000 } } namespace LethalPerformance.Caching { internal class AutoUnsafeCachedInstance<T> : UnsafeCachedInstance<T>, IAutoInstance where T : Behaviour { private readonly string m_HierarchyPath; public AutoUnsafeCachedInstance(string hierarchyPath) { m_HierarchyPath = hierarchyPath; } public void SaveInstance() { if ((Object)(object)base.Instance != (Object)null) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)(typeof(T).Name + " instance is already cached")); } GameObject val = GameObject.Find(m_HierarchyPath); if ((Object)(object)val != (Object)null) { T instance = default(T); if (val.TryGetComponent<T>(ref instance)) { base.Instance = instance; } else { LethalPerformancePlugin.Instance.Logger.LogWarning((object)("Failed to cache instance of " + typeof(T).Name)); } } else { LethalPerformancePlugin.Instance.Logger.LogWarning((object)("Failed to find gameobject of " + typeof(T).Name)); } } } public interface IAutoInstance { void SaveInstance(); } internal struct InstanceResult { public bool isFound; public Behaviour? instance; public InstanceResult(bool isFound, Behaviour? instance) { this.isFound = isFound; this.instance = instance; } public static InstanceResult Found(Behaviour? instance) { InstanceResult result = default(InstanceResult); result.instance = instance; result.isFound = true; return result; } public static InstanceResult NotFound(Behaviour? instance) { InstanceResult result = default(InstanceResult); result.instance = instance; result.isFound = false; return result; } public readonly void Deconstruct(out bool isFound, out Behaviour? instance) { isFound = this.isFound; instance = this.instance; } } internal struct InstancesResult { public bool isFound; public Behaviour[]? instances; public InstancesResult(bool isFound, Behaviour[]? instances) { this.isFound = isFound; this.instances = instances; } public static InstancesResult Found(Behaviour[]? instances) { InstancesResult result = default(InstancesResult); result.instances = instances; result.isFound = true; return result; } public static InstancesResult NotFound(Behaviour[]? instances) { InstancesResult result = default(InstancesResult); result.instances = instances; result.isFound = false; return result; } public readonly void Deconstruct(out bool isFound, out Behaviour[]? instances) { isFound = this.isFound; instances = this.instances; } } internal class ManualCachedInstance<T> : UnsafeCachedInstance<T> where T : Behaviour { public override InstanceResult TryGetInstance(FindObjectsInactive findObjectsInactive) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 if ((Object)(object)base.Instance == (Object)null) { return InstanceResult.Found(null); } if ((int)findObjectsInactive == 1) { return InstanceResult.Found((Behaviour?)(object)base.Instance); } if (((Behaviour)base.Instance).enabled && ((Component)(object)base.Instance).gameObject.activeInHierarchy) { return InstanceResult.Found((Behaviour?)(object)base.Instance); } return InstanceResult.Found(null); } } internal abstract class UnsafeCachedInstance { public static List<UnsafeCachedInstance> UnsafeCachedInstances { get; private set; } = new List<UnsafeCachedInstance>(); public abstract InstanceResult TryGetInstance(FindObjectsInactive findObjectsInactive); public abstract void Cleanup(); public static T AddSelfToMap<T, B>(T unsafeInstance) where T : UnsafeCachedInstance<B> where B : Behaviour { return (T)UnsafeCacheManager.AddReferenceToMap(unsafeInstance); } } internal class UnsafeCachedInstance<T> : UnsafeCachedInstance where T : Behaviour { public T? Instance { get; protected set; } protected UnsafeCachedInstance() { Instance = default(T); UnsafeCachedInstance.UnsafeCachedInstances.Add(this); } public void SetInstance(T? instance) { if ((Object)(object)instance != (Object)null && (Object)(object)Instance != (Object)null) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)(typeof(T).Name + " is requested caching, while cached instance is still alive")); } Instance = instance; } public override InstanceResult TryGetInstance(FindObjectsInactive findObjectsInactive) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 if ((Object)(object)Instance == (Object)null) { return InstanceResult.NotFound(null); } if ((int)findObjectsInactive == 1) { return InstanceResult.Found((Behaviour?)(object)Instance); } if (((Behaviour)Instance).enabled && ((Component)(object)Instance).gameObject.activeInHierarchy) { return InstanceResult.Found((Behaviour?)(object)Instance); } return InstanceResult.Found(null); } public override void Cleanup() { Instance = default(T); } } internal static class UnsafeCacheManager { public delegate InstanceResult TryGetInstance(FindObjectsInactive findObjectsInactive); public delegate InstancesResult TryGetInstances(FindObjectsInactive findObjectsInactive); private static readonly Dictionary<Type, TryGetInstance> s_MapGettingInstance; private static readonly Dictionary<Type, TryGetInstances> s_MapGettingInstances; static UnsafeCacheManager() { s_MapGettingInstance = new Dictionary<Type, TryGetInstance> { [typeof(StartOfRound)] = (FindObjectsInactive _) => new InstanceResult(Object.op_Implicit((Object)(object)StartOfRound.Instance), (Behaviour?)(object)StartOfRound.Instance), [typeof(GameNetworkManager)] = (FindObjectsInactive _) => InstanceResult.Found((Behaviour?)(object)GameNetworkManager.Instance), [typeof(HUDManager)] = (FindObjectsInactive _) => new InstanceResult(Object.op_Implicit((Object)(object)HUDManager.Instance), (Behaviour?)(object)HUDManager.Instance), [typeof(GlobalEffects)] = (FindObjectsInactive _) => new InstanceResult(Object.op_Implicit((Object)(object)GlobalEffects.Instance), (Behaviour?)(object)GlobalEffects.Instance), [typeof(IngamePlayerSettings)] = (FindObjectsInactive _) => InstanceResult.Found((Behaviour?)(object)IngamePlayerSettings.Instance), [typeof(SteamManager)] = (FindObjectsInactive _) => InstanceResult.Found((Behaviour?)(object)SteamManager.Instance) }; s_MapGettingInstances = new Dictionary<Type, TryGetInstances> { [typeof(PlayerVoiceIngameSettings)] = delegate(FindObjectsInactive inactive) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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) //IL_0091: Invalid comparison between Unknown and I4 if (!TryGetCachedBehaviour<DissonanceComms>(inactive, out DissonanceComms result)) { return InstancesResult.NotFound(null); } List<VoicePlayerState> players = result._players._players; Stack<VoicePlayback> items = result._playbackPool._pool._items; List<PlayerVoiceIngameSettings> list = default(List<PlayerVoiceIngameSettings>); PooledObject<List<PlayerVoiceIngameSettings>> val = CollectionPool<List<PlayerVoiceIngameSettings>, PlayerVoiceIngameSettings>.Get(ref list); try { PlayerVoiceIngameSettings item = default(PlayerVoiceIngameSettings); for (int i = 0; i < players.Count; i++) { IVoicePlayback playback = result._players._players[i].Playback; MonoBehaviour val2 = (MonoBehaviour)(object)((playback is MonoBehaviour) ? playback : null); if (val2 != null && (Object)(object)val2 != (Object)null && ((Component)val2).TryGetComponent<PlayerVoiceIngameSettings>(ref item)) { list.Add(item); } } if ((int)inactive == 1) { PlayerVoiceIngameSettings item2 = default(PlayerVoiceIngameSettings); foreach (VoicePlayback item3 in items) { if (((Component)item3).TryGetComponent<PlayerVoiceIngameSettings>(ref item2)) { list.Add(item2); } } } Behaviour[] instances = (Behaviour[])(object)list.ToArray(); return InstancesResult.Found(instances); } finally { ((IDisposable)val).Dispose(); } } }; AddReference<DissonanceComms>("/Systems/DissonanceSetup"); AddReference<RoundManager>("/Systems/GameSystems/RoundManager"); AddReference<QuickMenuManager>("/Systems/GameSystems/QuickMenuManager"); AddReference<TimeOfDay>("/Systems/GameSystems/TimeAndWeather"); AddReference<SoundManager>("/Systems/GameSystems/SoundManager"); AddReference<ShipBuildModeManager>("/Systems/GameSystems/ShipBuildMode"); AddReference<MoldSpreadManager>("/Systems/GameSystems/Misc/MoldSpread"); AddReference<StormyWeather>("/Systems/GameSystems/TimeAndWeather/Stormy"); AddReference<BeltBagInventoryUI>("/Systems/UI/Canvas/IngamePlayerHUD/BeltBagUI"); AddReference<AudioListener>("/Systems/Audios/PlayerAudioListener"); AddReference<Terminal>("/Environment/HangarShip/Terminal/TerminalTrigger/TerminalScript"); AddReference<StartMatchLever>("/Environment/HangarShip/StartGameLever"); AddReference<HangarShipDoor>("/Environment/HangarShip/AnimatedShipDoor"); static void AddReference<T>(string hierarchyPath) where T : notnull, Behaviour { AutoUnsafeCachedInstance<T> autoUnsafeCachedInstance = new AutoUnsafeCachedInstance<T>(hierarchyPath); s_MapGettingInstance[typeof(T)] = autoUnsafeCachedInstance.TryGetInstance; } } public static UnsafeCachedInstance<T> AddReferenceToMap<T>(UnsafeCachedInstance<T> unsafeInstance) where T : Behaviour { s_MapGettingInstance[typeof(T)] = unsafeInstance.TryGetInstance; return unsafeInstance; } public static void AddActionToMap(Type type, TryGetInstances action) { s_MapGettingInstances[type] = action; } public static bool RemoveActionToMap(Type type) { return s_MapGettingInstances.Remove(type); } public static void CacheInstances() { foreach (UnsafeCachedInstance unsafeCachedInstance in UnsafeCachedInstance.UnsafeCachedInstances) { if (unsafeCachedInstance is IAutoInstance autoInstance) { autoInstance.SaveInstance(); } } } public static bool TryGetCachedReference(Type type, FindObjectsInactive findObjectsInactive, out Object? cache) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) bool isFound; if (s_MapGettingInstance.TryGetValue(type, out TryGetInstance value)) { value(findObjectsInactive).Deconstruct(out isFound, out Behaviour instance); bool flag = isFound; Behaviour val = instance; if (flag) { cache = (Object?)(object)val; return true; } } if (s_MapGettingInstances.TryGetValue(type, out TryGetInstances value2)) { value2(findObjectsInactive).Deconstruct(out isFound, out Behaviour[] instances); bool flag2 = isFound; Behaviour[] array = instances; if (flag2 && array.Length != 0) { cache = (Object?)(object)array[0]; } else { cache = null; } return true; } cache = null; return false; } public static bool TryGetCachedReferences(Type type, FindObjectsInactive findObjectsInactive, out Object[]? cache) { //IL_0010: 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) bool isFound; if (s_MapGettingInstances.TryGetValue(type, out TryGetInstances value)) { value(findObjectsInactive).Deconstruct(out isFound, out Behaviour[] instances); bool flag = isFound; Behaviour[] array = instances; if (flag) { Object[] array2 = (Object[])(object)array; cache = array2; return true; } } if (s_MapGettingInstance.TryGetValue(type, out TryGetInstance value2)) { value2(findObjectsInactive).Deconstruct(out isFound, out Behaviour instance); bool flag2 = isFound; Behaviour val = instance; if (flag2 && (Object)(object)val != (Object)null) { cache = (Object[]?)(object)new Object[1] { (Object)val }; } else { cache = Array.Empty<Object>(); } return true; } cache = null; return false; } public static void CleanupCache() { foreach (UnsafeCachedInstance unsafeCachedInstance in UnsafeCachedInstance.UnsafeCachedInstances) { unsafeCachedInstance.Cleanup(); } } private static bool TryGetCachedBehaviour<T>(FindObjectsInactive findObjectsInactive, [NotNullWhen(true)] out T? result) where T : Behaviour { //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (TryGetCachedReference(typeof(T), findObjectsInactive, out Object cache)) { result = (T)(object)cache; return true; } result = default(T); return false; } } } namespace LethalPerformance.Caching.References { internal static class NetworkBehaviourCaching { private static readonly HashSet<Type> s_TypesToCache = new HashSet<Type> { typeof(VehicleController), typeof(GrabbableObject), typeof(DepositItemsDesk), typeof(ShipTeleporter), typeof(BreakerBox), typeof(MineshaftElevatorController), typeof(ShipLights), typeof(TVScript), typeof(EnemyVent), typeof(TerminalAccessibleObject), typeof(SteamValveHazard), typeof(DoorLock), typeof(UnlockableSuit), typeof(Landmine), typeof(Turret), typeof(SpikeRoofTrap), typeof(StoryLog) }; private static readonly MethodInfo s_FindWithSpawnedBehaviours = typeof(NetworkBehaviourCaching).GetMethod("FindWithSpawnedBehaviours", AccessTools.all); [InitializeOnAwake] internal static void Initialize() { foreach (Type item in s_TypesToCache) { AddActionToMap(item); } LethalPerformancePlugin.Instance.Configuration.CacheEntranceTeleports.SettingChanged += CacheEntranceTeleports_SettingChanged; if (LethalPerformancePlugin.Instance.Configuration.CacheEntranceTeleports.Value) { CacheEntranceTeleports_SettingChanged(null, null); } } private static void CacheEntranceTeleports_SettingChanged(object sender, EventArgs e) { UnsafeCacheManager.RemoveActionToMap(typeof(EntranceTeleport)); AddActionToMap(typeof(EntranceTeleport)); } private static void AddActionToMap(Type type) { MethodInfo method = s_FindWithSpawnedBehaviours.MakeGenericMethod(type); UnsafeCacheManager.TryGetInstances action = (UnsafeCacheManager.TryGetInstances)Delegate.CreateDelegate(typeof(UnsafeCacheManager.TryGetInstances), method); UnsafeCacheManager.AddActionToMap(type, action); } private static InstancesResult FindWithSpawnedBehaviours<T>(FindObjectsInactive inactive) where T : Object { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //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) if ((int)inactive == 1) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)(typeof(T).Name + " search called with inactive objects, probably will cause incompatibility!")); } List<T> list = default(List<T>); PooledObject<List<T>> val = CollectionPool<List<T>, T>.Get(ref list); try { NetworkManagerUtilities.FindAllSpawnedNetworkBehaviour(list); return InstancesResult.Found(list.ToArray() as Behaviour[]); } finally { ((IDisposable)val).Dispose(); } } } [HarmonyPatch(typeof(AudioReverbPresets))] internal static class Patch_AudioReverbPresets { private static readonly UnsafeCachedInstance<AudioReverbPresets> s_Instance = UnsafeCacheManager.AddReferenceToMap<AudioReverbPresets>((UnsafeCachedInstance<AudioReverbPresets>)new ManualCachedInstance<AudioReverbPresets>()); [HarmonyPrepare] public static void Prepare() { } [HarmonyPatch("Awake")] [HarmonyPrefix] public static void Awake(AudioReverbPresets __instance) { s_Instance.SetInstance(__instance); } } } namespace LethalPerformance.Caching.FindingObjectOptimization { [HarmonyPatch(typeof(Object))] internal static class NativeFindObjectOfTypePatch { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("FindAnyObjectByType", new Type[] { typeof(Type), typeof(FindObjectsInactive) })] [HarmonyPatch("FindFirstObjectByType", new Type[] { typeof(Type), typeof(FindObjectsInactive) })] [HarmonyPrefix] public static bool FindObjectFast(Type type, FindObjectsInactive findObjectsInactive, bool __runOriginal, ref Object? __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (!__runOriginal) { return false; } return !TryFindObjectFast(type, findObjectsInactive, out __result); } [HarmonyPatch("FindObjectOfType", new Type[] { typeof(Type), typeof(bool) })] [HarmonyPrefix] public static bool FindObjectFast(Type type, bool includeInactive, bool __runOriginal, ref Object? __result) { if (!__runOriginal) { return false; } return !TryFindObjectFast(type, (FindObjectsInactive)(includeInactive ? 1 : 0), out __result); } [HarmonyPatch("FindObjectsOfType", new Type[] { typeof(Type), typeof(bool) })] [HarmonyPrefix] public static bool FindObjectsFast(Type type, bool includeInactive, bool __runOriginal, ref Object[]? __result) { if (!__runOriginal) { return false; } return !TryFindObjectsFast(type, (FindObjectsInactive)(includeInactive ? 1 : 0), out __result); } [HarmonyPatch("FindObjectsByType", new Type[] { typeof(Type), typeof(FindObjectsInactive), typeof(FindObjectsSortMode) })] [HarmonyPrefix] public static bool FindObjectsFast(Type type, FindObjectsInactive findObjectsInactive, bool __runOriginal, ref Object[]? __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (!__runOriginal) { return false; } return !TryFindObjectsFast(type, findObjectsInactive, out __result); } [Conditional("ENABLE_PROFILER")] private static void ShowInProfilerType(Type type, bool findAllObjects) { string text = "DiFFoZ.Find." + type.Name; if (findAllObjects) { text += " (all objects)"; } LethalPerformancePlugin.Instance.Logger.LogInfo((object)("[Cache] " + text)); } public static bool TryFindObjectFast(Type type, FindObjectsInactive findObjectsInactive, out Object? result) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (UnsafeCacheManager.TryGetCachedReference(type, findObjectsInactive, out result)) { return true; } result = null; return false; } public static bool TryFindObjectsFast(Type type, FindObjectsInactive findObjectsInactive, out Object[]? result) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (UnsafeCacheManager.TryGetCachedReferences(type, findObjectsInactive, out result)) { return true; } result = null; return false; } } [HarmonyPatch] [HarmonyPriority(100)] internal static class ReplaceFindObjectOfTypePatch { private static readonly Dictionary<Type, MethodInfo> s_MapGettingInstance = new Dictionary<Type, MethodInfo> { { typeof(StartOfRound), AccessTools.PropertyGetter(typeof(StartOfRound), "Instance") }, { typeof(TimeOfDay), AccessTools.PropertyGetter(typeof(TimeOfDay), "Instance") }, { typeof(GameNetworkManager), AccessTools.PropertyGetter(typeof(GameNetworkManager), "Instance") }, { typeof(HUDManager), AccessTools.PropertyGetter(typeof(HUDManager), "Instance") }, { typeof(GlobalEffects), AccessTools.PropertyGetter(typeof(GlobalEffects), "Instance") }, { typeof(IngamePlayerSettings), AccessTools.PropertyGetter(typeof(IngamePlayerSettings), "Instance") }, { typeof(RoundManager), AccessTools.PropertyGetter(typeof(RoundManager), "Instance") }, { typeof(ShipBuildModeManager), AccessTools.PropertyGetter(typeof(ShipBuildModeManager), "Instance") }, { typeof(SoundManager), AccessTools.PropertyGetter(typeof(SoundManager), "Instance") }, { typeof(SteamManager), AccessTools.PropertyGetter(typeof(SteamManager), "Instance") } }; private static readonly HashSet<Type> s_ExcludedTypes = new HashSet<Type>(); private static readonly MethodInfo s_FindObjectByTypeNonOrdered = typeof(ObjectExtensions).GetMethod("FindObjectByTypeNonOrdered", AccessTools.all); private static readonly MethodInfo s_FindObjectByTypeNonOrderedInActive = typeof(ObjectExtensions).GetMethod("FindObjectByTypeNonOrderedInActive", AccessTools.all); [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyTargetMethods] private static IEnumerable<MethodInfo> GetTargetMethods() { Type type29 = typeof(BreakerBox); yield return type29.GetMethod("Start", AccessTools.all); yield return type29.GetMethod("SetSwitchesOff", AccessTools.all); type29 = typeof(FoliageDetailDistance); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(animatedSun); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(BoomboxItem); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(TimeOfDay); yield return type29.GetMethod("Start", AccessTools.all); yield return type29.GetMethod("SyncNewProfitQuotaClientRpc", AccessTools.all); type29 = typeof(Terminal); yield return type29.GetMethod("Start", AccessTools.all); yield return type29.GetMethod("ParsePlayerSentence", AccessTools.all); yield return type29.GetMethod("LoadNewNodeIfAffordable", AccessTools.all); yield return AccessTools.EnumeratorMoveNext((MethodBase)type29.GetMethod("displayReimbursedTipDelay", AccessTools.all)); type29 = typeof(StartOfRound); yield return type29.GetMethod("Start", AccessTools.all); yield return type29.GetMethod("SetMapScreenInfoToCurrentLevel", AccessTools.all); yield return type29.GetMethod("ChangePlanet", AccessTools.all); yield return type29.GetMethod("ArriveAtLevel", AccessTools.all); yield return type29.GetMethod("SwitchMapMonitorPurpose", AccessTools.all); yield return type29.GetMethod("StartGameServerRpc", AccessTools.all); yield return type29.GetMethod("StartGame", AccessTools.all); yield return type29.GetMethod("ShipHasLeft", AccessTools.all); yield return type29.GetMethod("SetTimeAndPlanetToSavedSettings", AccessTools.all); yield return type29.GetMethod("SetShipReadyToLand", AccessTools.all); yield return type29.GetMethod("SetShipDoorsOverheatClientRpc", AccessTools.all); yield return type29.GetMethod("SetPlanetsMold", AccessTools.all); yield return type29.GetMethod("ResetShip", AccessTools.all); yield return type29.GetMethod("ResetPlayersLoadedValueClientRpc", AccessTools.all); yield return type29.GetMethod("ResetMoldStates", AccessTools.all); yield return type29.GetMethod("PowerSurgeShip", AccessTools.all); yield return type29.GetMethod("PassTimeToNextDay", AccessTools.all); yield return type29.GetMethod("GetBodiesInShip", AccessTools.all); yield return AccessTools.EnumeratorMoveNext((MethodBase)type29.GetMethod("TravelToLevelEffects", AccessTools.all)); type29 = typeof(Shovel); yield return type29.GetMethod("HitShovel", AccessTools.all); type29 = typeof(RoundManager); yield return type29.GetMethod("Start", AccessTools.all); yield return AccessTools.EnumeratorMoveNext((MethodBase)type29.GetMethod("turnOnLights", AccessTools.all)); type29 = typeof(OutOfBoundsTrigger); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(MouthDogAI); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(LungProp); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(LevelGenerationManager); yield return type29.GetMethod("Awake", AccessTools.all); type29 = typeof(Landmine); yield return AccessTools.EnumeratorMoveNext((MethodBase)type29.GetMethod("StartIdleAnimation", AccessTools.all)); type29 = typeof(KnifeItem); yield return type29.GetMethod("HitKnife", AccessTools.all); type29 = typeof(ItemDropship); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(InteractTrigger); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(HUDManager); yield return type29.GetMethod("Awake", AccessTools.all); type29 = typeof(HangarShipDoor); yield return type29.GetMethod("Start", AccessTools.all); type29 = typeof(GlobalEffects); yield return type29.GetMethod("Awake", AccessTools.all); type29 = typeof(GameNetworkManager); yield return type29.GetMethod("SaveGameValues", AccessTools.all); yield return type29.GetMethod("ResetSavedGameValues", AccessTools.all); type29 = typeof(PlayerControllerB); yield return type29.GetMethod("SetSpectatedPlay
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.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.1.5.0")] [assembly: AssemblyInformationalVersion("1.1.5+95da822352e6628bd0c0d40005917e0d4c6eb134")] [assembly: AssemblyProduct("LethalPerformance.Patcher")] [assembly: AssemblyTitle("LethalPerformance.Patcher")] [assembly: InternalsVisibleTo("LethalPerformance")] [assembly: InternalsVisibleTo("LethalPerformance.Dev")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.5.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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[2] { "Assembly-CSharp.dll", "Assembly-CSharp-firstpass.dll" }); 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) { if (((AssemblyNameReference)assembly.Name).Name == "Assembly-CSharp-firstpass") { PatchES3(assembly); return; } 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) { Logger.LogWarning((object)("Failed to patch " + text)); } else { action(assembly, type); } } } private static void PatchES3(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) { 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) { 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 = 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; } } } 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).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 string methodName2 = methodName; if (!((IEnumerable<MethodDefinition>)type.Methods).Any((MethodDefinition m) => ((MemberReference)m).Name == methodName2)) { MethodDefinition val = new MethodDefinition(methodName2, (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 (!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; } } } 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; internal static bool IsModWillBeLoaded(string guid) { return s_PluginsToLoad?.ContainsKey(guid) ?? false; } [HarmonyPatch("Initialize")] [HarmonyPostfix] private static void Initialize() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown try { LethalPerformancePatcher.Harmony.Patch((MethodBase)MethodOf(new Action(Chainloader.Start)), (HarmonyMethod)null, (HarmonyMethod)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 DebugRemoveThreadSafetyCheck() { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown if (Debug.isDebugBuild) { IntPtr? intPtr = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().FirstOrDefault((ProcessModule p) => p.ModuleName.Contains("UnityPlayer"))?.BaseAddress; if (intPtr.HasValue) { NativeDetour val = new NativeDetour(intPtr.Value + 16617536, (MethodBase)MethodOf(new Action(StubMethod))); } } } private static void StubMethod() { } 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"); 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) { Func<Task> func2 = func; Task.Run(async delegate { try { await func2(); } catch (Exception ex) { LethalPerformancePatcher.Logger.LogError((object)ex); } }); } public static void Schedule<T>(Func<T, Task> func, T param1) { Func<T, Task> func2 = func; T param2 = param1; Task.Run(async delegate { try { await func2(param2); } 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.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) { } } } 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(); } }