Decompiled source of Hooks Hellpit v1.0.1
plugins/CSync/com.sigurd.csync.dll
Decompiled 5 hours agousing System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using CSync.Extensions; using CSync.Lib; using CSync.Util; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Unity.Collections; using Unity.Netcode; using UnityEngine; using com.sigurd.csync.NetcodePatcher; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("ClientNetworkTransform")] [assembly: IgnoresAccessChecksTo("DissonanceVoip")] [assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")] [assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")] [assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")] [assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")] [assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")] [assembly: IgnoresAccessChecksTo("Unity.Burst")] [assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")] [assembly: IgnoresAccessChecksTo("Unity.Collections")] [assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")] [assembly: IgnoresAccessChecksTo("Unity.Jobs")] [assembly: IgnoresAccessChecksTo("Unity.Mathematics")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")] [assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")] [assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")] [assembly: IgnoresAccessChecksTo("Unity.Services.QoS")] [assembly: IgnoresAccessChecksTo("Unity.Services.Relay")] [assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")] [assembly: IgnoresAccessChecksTo("Unity.Timeline")] [assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")] [assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.UI")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Sigurd Team")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Configuration file syncing library for BepInEx.\n Allows serialization of a ConfigEntry with a drop in replacement.\n\n A usage guide can be found on the Thunderstore wiki.\n https://thunderstore.io/c/lethal-company/p/Sigurd/CSync/wiki/\n ")] [assembly: AssemblyFileVersion("5.0.1.0")] [assembly: AssemblyInformationalVersion("5.0.1+3ddfccad9bb0ff70bf3b3b9061a60ae274a5b0a5")] [assembly: AssemblyProduct("CSync")] [assembly: AssemblyTitle("com.sigurd.csync")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/lc-sigurd/CSync")] [assembly: NeutralResourcesLanguage("en-GB")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("5.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>(); NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializable<SyncedEntryDelta>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<SyncedEntryDelta>(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [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 Unity.Netcode { internal class ListierNetworkList<T> : NetworkList<T>, IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable where T : unmanaged, IEquatable<T> { public bool IsReadOnly => false; IEnumerator IEnumerable.GetEnumerator() { return base.GetEnumerator(); } public void CopyTo(T[] array, int arrayIndex) { throw new NotSupportedException(); } T IList<T>.get_Item(int index) { return base[index]; } void IList<T>.set_Item(int index, T value) { base[index] = value; } int IList<T>.IndexOf(T item) { return base.IndexOf(item); } void IList<T>.Insert(int index, T item) { base.Insert(index, item); } void IList<T>.RemoveAt(int index) { base.RemoveAt(index); } int ICollection<T>.get_Count() { return base.Count; } void ICollection<T>.Add(T item) { base.Add(item); } void ICollection<T>.Clear() { base.Clear(); } bool ICollection<T>.Contains(T item) { return base.Contains(item); } bool ICollection<T>.Remove(T item) { return base.Remove(item); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return base.GetEnumerator(); } } } namespace CSync { [BepInPlugin("com.sigurd.csync", "CSync", "5.0.1")] public class Plugin : BaseUnityPlugin { internal static Harmony Patcher; internal static ManualLogSource Logger { get; private set; } private void Awake() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; try { Patcher = new Harmony("com.sigurd.csync"); Patcher.PatchAll(); Logger.LogInfo((object)"CSync successfully applied patches."); } catch (Exception ex) { Logger.LogError((object)ex); } } } internal static class MyPluginInfo { public const string PLUGIN_GUID = "com.sigurd.csync"; public const string PLUGIN_NAME = "CSync"; public const string PLUGIN_VERSION = "5.0.1"; } } namespace CSync.Util { [Obsolete] public class ByteSerializer<T> { } [Obsolete("Use SyncedBindingExtensions instead.")] public static class Extensions { [Obsolete("Use SyncedBindingExtensions instead.")] public static SyncedEntry<T> BindSyncedEntry<T>(this ConfigFile configFile, string section, string key, T defaultValue, string description) { return SyncedBindingExtensions.BindSyncedEntry(configFile, section, key, defaultValue, description); } [Obsolete("Use SyncedBindingExtensions instead.")] public static SyncedEntry<T> BindSyncedEntry<T>(this ConfigFile configFile, string section, string key, T defaultValue, ConfigDescription? description = null) { return SyncedBindingExtensions.BindSyncedEntry(configFile, section, key, defaultValue, description); } [Obsolete("Use SyncedBindingExtensions instead.")] public static SyncedEntry<T> BindSyncedEntry<T>(this ConfigFile configFile, ConfigDefinition definition, T defaultValue, string description) { return SyncedBindingExtensions.BindSyncedEntry(configFile, definition, defaultValue, description); } [Obsolete("Use SyncedBindingExtensions instead.")] public static SyncedEntry<T> BindSyncedEntry<T>(this ConfigFile configFile, ConfigDefinition definition, T defaultValue, ConfigDescription? description = null) { return SyncedBindingExtensions.BindSyncedEntry(configFile, definition, defaultValue, description); } [Obsolete("Use SyncedBindingExtensions instead.")] public static SyncedEntry<T> ToSyncedEntry<T>(this ConfigEntry<T> entry) { return SyncedBindingExtensions.ToSyncedEntry<T>(entry); } } } namespace CSync.Patches { [HarmonyPatch(typeof(GameNetworkManager))] public static class GameNetworkManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] public static void OnNetworkManagerStart(GameNetworkManager __instance) { ConfigManager.PopulateEntries(); if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Contains(ConfigManager.Prefab)) { NetworkManager.Singleton.AddNetworkPrefab(ConfigManager.Prefab); } } } [HarmonyPatch(typeof(StartOfRound))] public static class StartOfRoundPatch { [HarmonyPatch("Start")] [HarmonyPostfix] public static void OnSessionStart(StartOfRound __instance) { if (!((NetworkBehaviour)__instance).IsOwner) { return; } try { GameObject obj = Object.Instantiate<GameObject>(ConfigManager.Prefab, ((Component)__instance).transform); ((Object)obj).hideFlags = (HideFlags)0; obj.GetComponent<NetworkObject>().Spawn(false); } catch (Exception arg) { Plugin.Logger.LogError((object)$"Failed to instantiate config sync behaviours:\n{arg}"); } } } } namespace CSync.Lib { [PublicAPI] public static class ConfigManager { [Serializable] [UsedImplicitly] public record struct InstanceKey { public string Guid => _guid; public string AssemblyQualifiedName => _assemblyQualifiedName; [SerializeField] private string _guid; [SerializeField] private string _assemblyQualifiedName; public InstanceKey(string guid, string assemblyQualifiedName) { _guid = guid; _assemblyQualifiedName = assemblyQualifiedName; } [CompilerGenerated] private bool PrintMembers(StringBuilder builder) { builder.Append("Guid = "); builder.Append((object?)Guid); builder.Append(", AssemblyQualifiedName = "); builder.Append((object?)AssemblyQualifiedName); return true; } } internal static readonly Dictionary<string, ConfigFile> FileCache; internal static readonly Dictionary<InstanceKey, ISyncedConfig> Instances; internal static readonly Dictionary<InstanceKey, EventHandler> InitialSyncHandlers; private static readonly Lazy<GameObject> LazyPrefab; internal static GameObject Prefab => LazyPrefab.Value; private static event Action? OnPopulateEntriesRequested; internal static void PopulateEntries() { ConfigManager.OnPopulateEntriesRequested?.Invoke(); } static ConfigManager() { FileCache = new Dictionary<string, ConfigFile>(); Instances = new Dictionary<InstanceKey, ISyncedConfig>(); InitialSyncHandlers = new Dictionary<InstanceKey, EventHandler>(); LazyPrefab = new Lazy<GameObject>((Func<GameObject>)delegate { //IL_0005: 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_0013: Expected O, but got Unknown //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown GameObject val = new GameObject("CSyncPrefabContainer") { hideFlags = (HideFlags)61 }; val.SetActive(false); Object.DontDestroyOnLoad((Object)(object)val); GameObject val2 = new GameObject("ConfigSyncHolder"); val2.transform.SetParent(val.transform); NetworkObject obj = val2.AddComponent<NetworkObject>(); byte[] array = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("com.sigurd.csync:ConfigSyncHolder")); obj.GlobalObjectIdHash = BitConverter.ToUInt32(array); return val2; }); } internal static void AddToFileCache(ConfigFile configFile) { FileCache.TryAdd(configFile.GetConfigFileRelativePath(), configFile); } internal static ConfigFile GetConfigFile(string relativePath) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown if (FileCache.TryGetValue(relativePath, out ConfigFile value)) { return value; } value = new ConfigFile(Path.GetFullPath(Path.Combine(Paths.BepInExRootPath, relativePath)), false); FileCache.Add(relativePath, value); return value; } [Obsolete("Obsolete, use SyncedConfig2")] public static void Register<T>(T config) where T : SyncedConfig<T> { Register((SyncedConfig<T>)config); } [Obsolete("Obsolete, use SyncedConfig2")] public static void Register<T>(SyncedConfig<T> config) where T : SyncedConfig<T> { if (config == null) { throw new ArgumentNullException("config", "Config instance is null, cannot register."); } if (!(config is T)) { throw new ArgumentException(string.Format("{0} declares it extends {1}<{2}>. It should be declared to extend {3}<{4}>.", config.GetType(), "SyncedConfig", typeof(T), "SyncedConfig", config.GetType()), "config"); } string assemblyQualifiedName = typeof(T).AssemblyQualifiedName ?? throw new ArgumentException("config"); InstanceKey instanceKey = new InstanceKey(config.GUID, assemblyQualifiedName); try { Instances.Add(instanceKey, config); InitialSyncHandlers.Add(instanceKey, config.OnInitialSyncCompleted); } catch (ArgumentException innerException) { throw new InvalidOperationException($"Attempted to register config instance of type `{typeof(T)}`, but an instance has already been registered with key {instanceKey}.", innerException); } Plugin.Logger.LogDebug((object)$"Successfully registered config instance {instanceKey}."); SyncedInstance<T>.Instance = (T)config; SyncedInstance<T>.Default = (T)config; OnPopulateEntriesRequested += config.PopulateEntryContainer; Prefab.AddComponent<ConfigSyncBehaviour>().ConfigInstanceKey = instanceKey; } public static void Register<T>(SyncedConfig2<T> config) where T : SyncedConfig2<T> { if (config == null) { throw new ArgumentNullException("config", "Config instance is null, cannot register."); } if (!(config is T)) { throw new ArgumentException(string.Format("{0} declares it extends {1}<{2}>. It should be declared to extend {3}<{4}>.", config.GetType(), "SyncedConfig2", typeof(T), "SyncedConfig2", config.GetType()), "config"); } string assemblyQualifiedName = typeof(T).AssemblyQualifiedName ?? throw new ArgumentException("config"); InstanceKey instanceKey = new InstanceKey(config.GUID, assemblyQualifiedName); try { Instances.Add(instanceKey, config); InitialSyncHandlers.Add(instanceKey, config.OnInitialSyncCompleted); } catch (ArgumentException innerException) { throw new InvalidOperationException($"Attempted to register config instance of type `{typeof(T)}`, but an instance has already been registered with key {instanceKey}.", innerException); } config.PopulateEntryContainer(); Plugin.Logger.LogDebug((object)$"Successfully registered config instance {instanceKey}."); Prefab.AddComponent<ConfigSyncBehaviour>().ConfigInstanceKey = instanceKey; } } public class ConfigSyncBehaviour : NetworkBehaviour { private ISyncedEntryContainer? _entryContainer; private readonly NetworkVariable<bool> _syncEnabled = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private NetworkList<SyncedEntryDelta> _deltas; [field: SerializeField] public ConfigManager.InstanceKey ConfigInstanceKey { get; internal set; } private ISyncedConfig? Config { get { if (!ConfigManager.Instances.TryGetValue(ConfigInstanceKey, out ISyncedConfig value)) { return null; } return value; } } private EventHandler? InitialSyncCompletedHandler { get { if (!ConfigManager.InitialSyncHandlers.TryGetValue(ConfigInstanceKey, out EventHandler value)) { return null; } return value; } } internal ISyncedEntryContainer? EntryContainer => _entryContainer ?? (_entryContainer = Config?.EntryContainer); public bool SyncEnabled { get { return _syncEnabled.Value; } set { _syncEnabled.Value = value; } } [MemberNotNull("EntryContainer")] private void EnsureEntryContainer() { if (EntryContainer != null) { return; } throw new InvalidOperationException("Entry container has not been assigned."); } private void Awake() { EnsureEntryContainer(); _deltas = new NetworkList<SyncedEntryDelta>(); } public override void OnNetworkSpawn() { EnsureEntryContainer(); if (((NetworkBehaviour)this).IsServer) { _syncEnabled.Value = true; foreach (SyncedEntryBase syncedEntryBase in EntryContainer.Values) { int currentIndex = _deltas.Count; _deltas.Add(syncedEntryBase.ToDelta()); syncedEntryBase.BoxedEntry.ConfigFile.SettingChanged += delegate(object _, SettingChangedEventArgs args) { if (syncedEntryBase.BoxedEntry == args.ChangedSetting) { _deltas[currentIndex] = syncedEntryBase.ToDelta(); } }; syncedEntryBase.SyncEnabledChanged += delegate { _deltas[currentIndex] = syncedEntryBase.ToDelta(); }; } InitialSyncCompletedHandler?.Invoke(this, EventArgs.Empty); } else { if (!((NetworkBehaviour)this).IsClient) { return; } NetworkVariable<bool> syncEnabled = _syncEnabled; syncEnabled.OnValueChanged = (OnValueChangedDelegate<bool>)(object)Delegate.Combine((Delegate?)(object)syncEnabled.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<bool>(OnSyncEnabledChanged)); _deltas.OnListChanged += OnClientDeltaListChanged; foreach (SyncedEntryDelta delta in _deltas) { UpdateOverrideValue(delta); } if (_syncEnabled.Value) { EnableOverrides(); } InitialSyncCompletedHandler?.Invoke(this, EventArgs.Empty); } } public override void OnDestroy() { DisableOverrides(); foreach (SyncedEntryDelta delta in _deltas) { ResetOverrideValue(delta); } ((NetworkBehaviour)this).OnDestroy(); } private void OnSyncEnabledChanged(bool previousValue, bool newValue) { if (previousValue != newValue) { if (newValue) { EnableOverrides(); } else { DisableOverrides(); } } } private void OnClientDeltaListChanged(NetworkListEvent<SyncedEntryDelta> args) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_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_0029: Expected I4, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) EventType<SyncedEntryDelta> type = args.Type; switch ((int)type) { case 2: case 3: ResetOverrideValue(args.PreviousValue); break; case 0: case 1: case 4: UpdateOverrideValue(args.Value); break; case 5: { foreach (SyncedEntryDelta delta in _deltas) { ResetOverrideValue(delta); } break; } case 6: { foreach (SyncedEntryDelta delta2 in _deltas) { UpdateOverrideValue(delta2); } break; } default: throw new ArgumentOutOfRangeException(); } } private void ResetOverrideValue(SyncedEntryDelta delta) { EnsureEntryContainer(); try { SyncedEntryBase syncedEntryBase = EntryContainer[delta.SyncedEntryIdentifier]; syncedEntryBase.BoxedValueOverride = syncedEntryBase.BoxedEntry.DefaultValue; } catch (KeyNotFoundException) { } } private void UpdateOverrideValue(SyncedEntryDelta delta) { EnsureEntryContainer(); try { SyncedEntryBase syncedEntryBase = EntryContainer[delta.SyncedEntryIdentifier]; syncedEntryBase.SetSerializedValueOverride(((FixedString512Bytes)(ref delta.SerializedValue)).Value); syncedEntryBase.ValueOverridden = delta.SyncEnabled && SyncEnabled; } catch (KeyNotFoundException) { Plugin.Logger.Log((LogLevel)4, (object)$"Setting \"{delta.Definition}\" could not be found, so its synced value override will be ignored."); } catch (Exception ex2) { Plugin.Logger.Log((LogLevel)4, (object)$"Synced value override of setting \"{delta.Definition}\" could not be parsed and will be ignored. Reason: {ex2.Message}; Value: {((FixedString512Bytes)(ref delta.SerializedValue)).Value}"); } } private void EnableOverrides() { EnsureEntryContainer(); foreach (SyncedEntryDelta delta in _deltas) { try { EntryContainer[delta.SyncedEntryIdentifier].ValueOverridden = delta.SyncEnabled; } catch (KeyNotFoundException) { Plugin.Logger.Log((LogLevel)4, (object)$"Setting \"{delta.Definition}\" could not be found, so its value override could not be enabled."); } } } private void DisableOverrides() { EnsureEntryContainer(); foreach (SyncedEntryBase value in EntryContainer.Values) { value.ValueOverridden = false; } } protected override void __initializeVariables() { if (_syncEnabled == null) { throw new Exception("ConfigSyncBehaviour._syncEnabled cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)_syncEnabled).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)_syncEnabled, "_syncEnabled"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)_syncEnabled); if (_deltas == null) { throw new Exception("ConfigSyncBehaviour._deltas cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)_deltas).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)_deltas, "_deltas"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)_deltas); ((NetworkBehaviour)this).__initializeVariables(); } [MethodImpl(MethodImplOptions.NoInlining)] protected internal override string? __getTypeName() { return "ConfigSyncBehaviour"; } } public interface ISyncedConfig { string GUID { get; } ISyncedEntryContainer EntryContainer { get; } } public interface ISyncedEntryContainer : IDictionary<(string ConfigFileRelativePath, SyncedConfigDefinition Definition), SyncedEntryBase>, ICollection<KeyValuePair<(string ConfigFileRelativePath, SyncedConfigDefinition Definition), SyncedEntryBase>>, IEnumerable<KeyValuePair<(string ConfigFileRelativePath, SyncedConfigDefinition Definition), SyncedEntryBase>>, IEnumerable { } [PublicAPI] [Obsolete("Obsolete, use SyncedConfig2")] public class SyncedConfig<T> : SyncedInstance<T>, ISyncedConfig where T : SyncedConfig<T> { private int _entryContainerPopulated; private static Lazy<FieldInfo[]> SyncedEntryFields = new Lazy<FieldInfo[]>(() => (from field in AccessTools.GetDeclaredFields(typeof(T)) where field.GetCustomAttribute<DataMemberAttribute>() != null where typeof(SyncedEntryBase).IsAssignableFrom(field.FieldType) select field).ToArray()); public ISyncedEntryContainer EntryContainer { get; } = new SyncedEntryContainer(); public string GUID { get; } public event EventHandler? InitialSyncCompleted; public SyncedConfig(string guid) { GUID = guid; } internal void PopulateEntryContainer() { if (Interlocked.Exchange(ref _entryContainerPopulated, 1) == 0) { FieldInfo[] value = SyncedEntryFields.Value; for (int i = 0; i < value.Length; i++) { SyncedEntryBase syncedEntryBase = (SyncedEntryBase)value[i].GetValue(this); EntryContainer.Add(syncedEntryBase.BoxedEntry.ToSyncedEntryIdentifier(), syncedEntryBase); } } } internal void OnInitialSyncCompleted(object sender, EventArgs e) { this.InitialSyncCompleted?.Invoke(sender, e); } } [PublicAPI] public class SyncedConfig2<T> : ISyncedConfig where T : SyncedConfig2<T> { private int _entryContainerPopulated; private static Lazy<FieldInfo[]> SyncedEntryFields = new Lazy<FieldInfo[]>(() => (from field in AccessTools.GetDeclaredFields(typeof(T)) where field.GetCustomAttribute<SyncedEntryFieldAttribute>() != null where typeof(SyncedEntryBase).IsAssignableFrom(field.FieldType) select field).ToArray()); public ISyncedEntryContainer EntryContainer { get; } = new SyncedEntryContainer(); public string GUID { get; } public event EventHandler? InitialSyncCompleted; public SyncedConfig2(string guid) { GUID = guid; } internal void PopulateEntryContainer() { if (Interlocked.Exchange(ref _entryContainerPopulated, 1) == 0) { FieldInfo[] value = SyncedEntryFields.Value; for (int i = 0; i < value.Length; i++) { SyncedEntryBase syncedEntryBase = (SyncedEntryBase)value[i].GetValue(this); EntryContainer.Add(syncedEntryBase.BoxedEntry.ToSyncedEntryIdentifier(), syncedEntryBase); } } } internal void OnInitialSyncCompleted(object sender, EventArgs e) { this.InitialSyncCompleted?.Invoke(sender, e); } } public struct SyncedConfigDefinition : INetworkSerializable, IEquatable<SyncedConfigDefinition> { public FixedString128Bytes Section; public FixedString128Bytes Key; public SyncedConfigDefinition(FixedString128Bytes section, FixedString128Bytes key) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: 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_0009: Unknown result type (might be due to invalid IL or missing references) Section = section; Key = key; } public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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) if (serializer.IsReader) { FastBufferReader fastBufferReader = serializer.GetFastBufferReader(); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<FixedString128Bytes>(ref Section, default(ForFixedStrings)); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<FixedString128Bytes>(ref Key, default(ForFixedStrings)); } else { FastBufferWriter fastBufferWriter = serializer.GetFastBufferWriter(); ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<FixedString128Bytes>(ref Section, default(ForFixedStrings)); ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<FixedString128Bytes>(ref Key, default(ForFixedStrings)); } } public bool Equals(SyncedConfigDefinition other) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (((FixedString128Bytes)(ref Section)).Equals(other.Section)) { return ((FixedString128Bytes)(ref Key)).Equals(other.Key); } return false; } public override bool Equals(object? obj) { if (obj is SyncedConfigDefinition other) { return Equals(other); } return false; } public override int GetHashCode() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) return HashCode.Combine<FixedString128Bytes, FixedString128Bytes>(Section, Key); } } [PublicAPI] public sealed class SyncedEntry<T> : SyncedEntryBase { private ConfigEntry<T> _entry; private T _lastLocalValue; private T _typedValueOverride; public ConfigEntry<T> Entry { get { return _entry; } init { _entry = value; _lastLocalValue = _entry.Value; Entry.SettingChanged += OnLocalSettingChanged; } } public override ConfigEntryBase BoxedEntry { get { return (ConfigEntryBase)(object)Entry; } protected init { Entry = (ConfigEntry<T>)(object)value; } } public override bool ValueOverridden { get { return base.ValueOverridden; } internal set { if (value != base.ValueOverridden) { T value2 = Value; base.ValueOverridden = value; OnValueOverriddenChanged(this, value2); } } } public T LocalValue { get { return Entry.Value; } set { Entry.Value = value; } } public override object? BoxedValueOverride { get { return _typedValueOverride; } set { T value2 = Value; _typedValueOverride = (T)value; OnValueOverrideChanged(this, value2); } } public T Value { get { if (ValueOverridden) { return _typedValueOverride; } return LocalValue; } } public event EventHandler<SyncedSettingChangedEventArgs<T>>? Changed; private void OnLocalSettingChanged(object sender, EventArgs e) { object sender2 = sender; InvokeChangedIfNecessary(); _lastLocalValue = LocalValue; void InvokeChangedIfNecessary() { if (!ValueOverridden && !object.Equals(_lastLocalValue, LocalValue)) { SyncedSettingChangedEventArgs<T> e2 = new SyncedSettingChangedEventArgs<T> { OldValue = _lastLocalValue, NewValue = LocalValue, ChangedEntry = this }; this.Changed?.Invoke(sender2, e2); } } } private void OnValueOverrideChanged(object sender, T oldValue) { if (ValueOverridden && !object.Equals(oldValue, _typedValueOverride)) { SyncedSettingChangedEventArgs<T> e = new SyncedSettingChangedEventArgs<T> { OldValue = oldValue, NewValue = _typedValueOverride, ChangedEntry = this }; this.Changed?.Invoke(sender, e); } } private void OnValueOverriddenChanged(object sender, T oldValue) { if (!object.Equals(Value, oldValue)) { SyncedSettingChangedEventArgs<T> e = new SyncedSettingChangedEventArgs<T> { OldValue = oldValue, NewValue = Value, ChangedEntry = this }; this.Changed?.Invoke(sender, e); } } public static implicit operator T(SyncedEntry<T> e) { return e.Value; } public SyncedEntry(ConfigEntry<T> entry) : base((ConfigEntryBase)(object)entry) { } public override string ToString() { return $"Key: {((ConfigEntryBase)Entry).Definition.Key}\nLocal Value: {LocalValue}\nCurrent Value: {Value}"; } } public abstract class SyncedEntryBase { private bool _syncEnabled = true; public abstract ConfigEntryBase BoxedEntry { get; protected init; } public abstract object? BoxedValueOverride { get; set; } public bool SyncEnabled { get { return _syncEnabled; } set { if (value != _syncEnabled) { _syncEnabled = value; this.SyncEnabledChanged?.Invoke(this, EventArgs.Empty); } } } public virtual bool ValueOverridden { get; internal set; } internal event EventHandler? SyncEnabledChanged; internal SyncedEntryBase(ConfigEntryBase configEntry) { BoxedEntry = configEntry ?? throw new ArgumentNullException("configEntry"); BoxedValueOverride = configEntry.DefaultValue; } public void SetSerializedValueOverride(string value) { BoxedValueOverride = TomlTypeConverter.ConvertToValue(value, BoxedEntry.SettingType); } internal SyncedEntryDelta ToDelta() { //IL_0010: 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) return new SyncedEntryDelta(FixedString128Bytes.op_Implicit(BoxedEntry.ConfigFile.GetConfigFileRelativePath()), BoxedEntry.Definition.ToSynced(), FixedString512Bytes.op_Implicit(BoxedEntry.GetSerializedValue()), SyncEnabled); } } public class SyncedEntryContainer : Dictionary<(string ConfigFileRelativePath, SyncedConfigDefinition Definition), SyncedEntryBase>, ISyncedEntryContainer, IDictionary<(string ConfigFileRelativePath, SyncedConfigDefinition Definition), SyncedEntryBase>, ICollection<KeyValuePair<(string ConfigFileRelativePath, SyncedConfigDefinition Definition), SyncedEntryBase>>, IEnumerable<KeyValuePair<(string ConfigFileRelativePath, SyncedConfigDefinition Definition), SyncedEntryBase>>, IEnumerable { public bool TryGetEntry<T>(string configFileRelativePath, SyncedConfigDefinition configDefinition, [MaybeNullWhen(false)] out SyncedEntry<T> entry) { if (TryGetValue((configFileRelativePath, configDefinition), out SyncedEntryBase value)) { entry = (SyncedEntry<T>)value; return true; } entry = null; return false; } public bool TryGetEntry<T>(string configFileRelativePath, string section, string key, [MaybeNullWhen(false)] out SyncedEntry<T> entry) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) return TryGetEntry(configFileRelativePath, new SyncedConfigDefinition(FixedString128Bytes.op_Implicit(section), FixedString128Bytes.op_Implicit(key)), out entry); } } internal struct SyncedEntryDelta : INetworkSerializable, IEquatable<SyncedEntryDelta> { public SyncedConfigDefinition Definition; public FixedString128Bytes ConfigFileRelativePath; public FixedString512Bytes SerializedValue; public bool SyncEnabled; public (string ConfigFileRelativePath, SyncedConfigDefinition Definition) SyncedEntryIdentifier => (((FixedString128Bytes)(ref ConfigFileRelativePath)).Value, Definition); public SyncedEntryDelta(FixedString128Bytes configFileRelativePath, SyncedConfigDefinition definition, FixedString512Bytes serializedValue, bool syncEnabled) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) ConfigFileRelativePath = configFileRelativePath; Definition = definition; SerializedValue = serializedValue; SyncEnabled = syncEnabled; } public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_0074: 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_0082: 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) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: 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: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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) if (serializer.IsReader) { ((BufferSerializer<SyncedConfigDefinition>*)(&serializer))->SerializeValue<SyncedConfigDefinition>(ref Definition, default(ForNetworkSerializable)); FastBufferReader fastBufferReader = serializer.GetFastBufferReader(); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<FixedString128Bytes>(ref ConfigFileRelativePath, default(ForFixedStrings)); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<FixedString512Bytes>(ref SerializedValue, default(ForFixedStrings)); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<bool>(ref SyncEnabled, default(ForPrimitives)); } else { ((BufferSerializer<SyncedConfigDefinition>*)(&serializer))->SerializeValue<SyncedConfigDefinition>(ref Definition, default(ForNetworkSerializable)); FastBufferWriter fastBufferWriter = serializer.GetFastBufferWriter(); ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<FixedString128Bytes>(ref ConfigFileRelativePath, default(ForFixedStrings)); ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<FixedString512Bytes>(ref SerializedValue, default(ForFixedStrings)); ((FastBufferWriter)(ref fastBufferWriter)).WriteValue<bool>(ref SyncEnabled, default(ForPrimitives)); } } public bool Equals(SyncedEntryDelta other) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (!Definition.Equals(other.Definition)) { return false; } if (!((FixedString128Bytes)(ref ConfigFileRelativePath)).Equals(other.ConfigFileRelativePath)) { return false; } if (!((FixedString512Bytes)(ref SerializedValue)).Equals(other.SerializedValue)) { return false; } if (!SyncEnabled.Equals(other.SyncEnabled)) { return false; } return true; } public override bool Equals(object? obj) { if (obj is SyncedEntryDelta other) { return Equals(other); } return false; } public override int GetHashCode() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) return HashCode.Combine<SyncedConfigDefinition, FixedString128Bytes, FixedString512Bytes, bool>(Definition, ConfigFileRelativePath, SerializedValue, SyncEnabled); } } [AttributeUsage(AttributeTargets.Field)] public class SyncedEntryFieldAttribute : Attribute { } public class SyncedInstance<T> : ByteSerializer<T> where T : class { [Obsolete] public static T? Instance { get; internal set; } [Obsolete("This will never actually hold the local configured values. Use SyncedEntry.LocalValue instead.")] public static T? Default { get; internal set; } } [PublicAPI] public sealed class SyncedSettingChangedEventArgs<T> : EventArgs { public required SyncedEntry<T> ChangedEntry { get; init; } public required T OldValue { get; init; } public required T NewValue { get; init; } } } namespace CSync.Extensions { internal static class ConfigDefinitionExtensions { public static SyncedConfigDefinition ToSynced(this ConfigDefinition definition) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) return new SyncedConfigDefinition(FixedString128Bytes.op_Implicit(definition.Section), FixedString128Bytes.op_Implicit(definition.Key)); } } internal static class ConfigEntryExtensions { public static (string ConfigFileRelativePath, SyncedConfigDefinition Definition) ToSyncedEntryIdentifier(this ConfigEntryBase entry) { return (entry.ConfigFile.GetConfigFileRelativePath(), entry.Definition.ToSynced()); } } internal static class ConfigFileExtensions { public static string GetConfigFileRelativePath(this ConfigFile configFile) { return Path.GetRelativePath(Paths.BepInExRootPath, configFile.ConfigFilePath); } } public static class SyncedBindingExtensions { public static SyncedEntry<T> BindSyncedEntry<T>(this ConfigFile configFile, string section, string key, T defaultVal, string description) { //IL_0003: 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_001b: Expected O, but got Unknown //IL_001b: Expected O, but got Unknown return configFile.BindSyncedEntry(new ConfigDefinition(section, key), defaultVal, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } public static SyncedEntry<T> BindSyncedEntry<T>(this ConfigFile configFile, string section, string key, T defaultValue, ConfigDescription? desc = null) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown return configFile.BindSyncedEntry(new ConfigDefinition(section, key), defaultValue, desc); } public static SyncedEntry<T> BindSyncedEntry<T>(this ConfigFile configFile, ConfigDefinition definition, T defaultValue, string description) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return configFile.BindSyncedEntry(definition, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } public static SyncedEntry<T> BindSyncedEntry<T>(this ConfigFile configFile, ConfigDefinition definition, T defaultValue, ConfigDescription? description = null) { ConfigManager.AddToFileCache(configFile); return configFile.Bind<T>(definition, defaultValue, description).ToSyncedEntry<T>(); } public static SyncedEntry<T> ToSyncedEntry<T>(this ConfigEntry<T> entry) { return new SyncedEntry<T>(entry); } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ExperimentalAttribute : Attribute { public string DiagnosticId { get; } public string? UrlFormat { get; set; } public ExperimentalAttribute(string diagnosticId) { DiagnosticId = diagnosticId; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class SetsRequiredMembersAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object?[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = new object[0]; } public StringSyntaxAttribute(string syntax, params object?[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class UnscopedRefAttribute : Attribute { } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiresPreviewFeaturesAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string? message) { Message = message; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CollectionBuilderAttribute : Attribute { public Type BuilderType { get; } public string MethodName { get; } public CollectionBuilderAttribute(Type builderType, string methodName) { BuilderType = builderType; MethodName = methodName; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; set; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class InterpolatedStringHandlerAttribute : Attribute { } [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal sealed class RequiresLocationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class SkipLocalsInitAttribute : Attribute { } } namespace com.sigurd.csync.NetcodePatcher { [AttributeUsage(AttributeTargets.Module)] internal class NetcodePatchedAssemblyAttribute : Attribute { } }
plugins/LandMineFartReverb.dll
Decompiled 5 hours agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using LandMineFartReverb.Patches; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("LandMineFartReverb")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("LandMineFartReverb")] [assembly: AssemblyTitle("LandMineFartReverb")] [assembly: AssemblyVersion("1.0.0.0")] 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; } } } namespace LandMineFartReverb { [BepInPlugin("sunnobunno.landminefartreverb", "Land Mine Fart Reverb", "1.0.3")] public class LandMineFartReverbBase : BaseUnityPlugin { private const string modGUID = "sunnobunno.landminefartreverb"; private const string modName = "Land Mine Fart Reverb"; private const string modVersion = "1.0.3"; private readonly Harmony harmony = new Harmony("sunnobunno.landminefartreverb"); private static LandMineFartReverbBase? Instance; internal ManualLogSource? mls; internal static AudioClip[]? newMineDetonate; internal static AudioClip[]? newMineDetonateFar; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("sunnobunno.landminefartreverb"); mls.LogInfo((object)"sunnobunno.landminefartreverb is loading."); string location = ((BaseUnityPlugin)Instance).Info.Location; string text = "LandMineFartReverb.dll"; string text2 = location.TrimEnd(text.ToCharArray()); string text3 = text2 + "fartwithreverb"; AssetBundle val = AssetBundle.LoadFromFile(text3); if ((Object)(object)val == (Object)null) { mls.LogError((object)"Failed to load audio assets!"); return; } newMineDetonate = val.LoadAssetWithSubAssets<AudioClip>("Assets/fartwithreverb.mp3"); newMineDetonateFar = val.LoadAssetWithSubAssets<AudioClip>("Assets/fartwithreverb.mp3"); harmony.PatchAll(typeof(LandminePatch)); mls.LogInfo((object)"sunnobunno.landminefartreverb is loaded. Pee-yeww."); } } } namespace LandMineFartReverb.Patches { [HarmonyPatch(typeof(Landmine))] internal class LandminePatch { [HarmonyPatch("Start")] [HarmonyPostfix] public static void hoarderBugAudioPatch(ref AudioClip ___mineDetonate, ref AudioClip ___mineDetonateFar) { AudioClip val = LandMineFartReverbBase.newMineDetonate[0]; ___mineDetonate = val; AudioClip val2 = LandMineFartReverbBase.newMineDetonateFar[0]; ___mineDetonateFar = val2; } } }
plugins/LateCompanyV1.0.17.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")] [assembly: AssemblyCompany("LateCompany")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+394f6e913ae93b8bc416d40547f3b1a710f49a92")] [assembly: AssemblyProduct("LateCompany")] [assembly: AssemblyTitle("LateCompany")] [assembly: AssemblyVersion("1.0.0.0")] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LateCompany { public static class PluginInfo { public const string GUID = "twig.latecompany"; public const string PrintName = "Late Company"; public const string Version = "1.0.17"; } [BepInPlugin("twig.latecompany", "Late Company", "1.0.17")] internal class Plugin : BaseUnityPlugin { public static bool LobbyJoinable = true; public void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown Harmony val = new Harmony("twig.latecompany"); val.PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.Log((LogLevel)16, (object)"Late Company loaded!"); } public static void SetLobbyJoinable(bool joinable) { LobbyJoinable = joinable; GameNetworkManager.Instance.SetLobbyJoinable(joinable); QuickMenuManager val = Object.FindObjectOfType<QuickMenuManager>(); if (Object.op_Implicit((Object)(object)val)) { val.inviteFriendsTextAlpha.alpha = (joinable ? 1f : 0.2f); } } } } namespace LateCompany.Patches { [HarmonyPatch(typeof(GameNetworkManager), "LeaveLobbyAtGameStart")] [HarmonyWrapSafe] internal static class LeaveLobbyAtGameStart_Patch { [HarmonyPrefix] private static bool Prefix() { return false; } } [HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")] [HarmonyWrapSafe] internal static class ConnectionApproval_Patch { [HarmonyPostfix] private static void Postfix(ref ConnectionApprovalRequest request, ref ConnectionApprovalResponse response) { if (request.ClientNetworkId != NetworkManager.Singleton.LocalClientId && Plugin.LobbyJoinable && response.Reason == "Game has already started!") { response.Reason = ""; response.Approved = true; } } } [HarmonyPatch(typeof(QuickMenuManager), "DisableInviteFriendsButton")] internal static class DisableInviteFriendsButton_Patch { [HarmonyPrefix] private static bool Prefix() { return false; } } [HarmonyPatch(typeof(QuickMenuManager), "InviteFriendsButton")] internal static class InviteFriendsButton_Patch { [HarmonyPrefix] private static bool Prefix() { if (Plugin.LobbyJoinable && !GameNetworkManager.Instance.disableSteam) { GameNetworkManager.Instance.InviteFriendsUI(); } return false; } } [HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")] [HarmonyWrapSafe] internal static class OnPlayerConnectedClientRpc_Patch { internal static void UpdateControlledState() { for (int i = 0; i < StartOfRound.Instance.connectedPlayersAmount + 1; i++) { if ((i == 0 || !((NetworkBehaviour)StartOfRound.Instance.allPlayerScripts[i]).IsOwnedByServer) && !StartOfRound.Instance.allPlayerScripts[i].isPlayerDead) { StartOfRound.Instance.allPlayerScripts[i].isPlayerControlled = true; } } } [HarmonyTranspiler] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; bool flag3 = false; foreach (CodeInstruction instruction in instructions) { if (!flag3) { if (!flag && instruction.opcode == OpCodes.Call && instruction.operand != null && instruction.operand.ToString() == "System.Collections.IEnumerator setPlayerToSpawnPosition(UnityEngine.Transform, UnityEngine.Vector3)") { flag = true; } else { if (flag && instruction.opcode == OpCodes.Ldc_I4_0) { flag2 = true; continue; } if (flag2 && instruction.opcode == OpCodes.Ldloc_0) { flag2 = false; flag3 = true; list.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(OnPlayerConnectedClientRpc_Patch), "UpdateControlledState", new Type[0], (Type[])null))); } } } if (!flag2) { list.Add(instruction); } } if (!flag3) { Debug.LogError((object)"Failed to transpile StartOfRound::OnPlayerConnectedClientRpc"); } return list.AsEnumerable(); } [HarmonyPostfix] private static void Postfix() { if (StartOfRound.Instance.connectedPlayersAmount + 1 >= StartOfRound.Instance.allPlayerScripts.Length) { Plugin.SetLobbyJoinable(joinable: false); } } } [HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")] [HarmonyWrapSafe] internal static class OnPlayerDC_Patch { [HarmonyPostfix] private static void Postfix(int playerObjectNumber) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (StartOfRound.Instance.inShipPhase) { Plugin.SetLobbyJoinable(joinable: true); } PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerObjectNumber]; val.activatingItem = false; val.bleedingHeavily = false; val.clampLooking = false; val.criticallyInjured = false; val.Crouch(false); val.disableInteract = false; val.DisableJetpackControlsLocally(); val.disableLookInput = false; val.disableMoveInput = false; val.DisablePlayerModel(((Component)val).gameObject, true, true); val.disableSyncInAnimation = false; val.externalForceAutoFade = Vector3.zero; val.freeRotationInInteractAnimation = false; val.hasBeenCriticallyInjured = false; val.health = 100; ((Behaviour)val.helmetLight).enabled = false; val.holdingWalkieTalkie = false; val.inAnimationWithEnemy = null; val.inShockingMinigame = false; val.inSpecialInteractAnimation = false; val.inVehicleAnimation = false; val.isClimbingLadder = false; val.isSinking = false; val.isUnderwater = false; Animator mapRadarDotAnimator = val.mapRadarDotAnimator; if (mapRadarDotAnimator != null) { mapRadarDotAnimator.SetBool("dead", false); } Animator playerBodyAnimator = val.playerBodyAnimator; if (playerBodyAnimator != null) { playerBodyAnimator.SetBool("Limp", false); } val.ResetZAndXRotation(); val.sinkingValue = 0f; val.speakingToWalkieTalkie = false; AudioSource statusEffectAudio = val.statusEffectAudio; if (statusEffectAudio != null) { statusEffectAudio.Stop(); } ((Collider)val.thisController).enabled = true; ((Component)val).transform.SetParent(StartOfRound.Instance.playersContainer); val.twoHanded = false; val.voiceMuffledByEnemy = false; } } [HarmonyPatch(typeof(StartOfRound), "SetShipReadyToLand")] internal static class SetShipReadyToLand_Patch { [HarmonyPostfix] private static void Postfix() { if (StartOfRound.Instance.connectedPlayersAmount + 1 < StartOfRound.Instance.allPlayerScripts.Length) { Plugin.SetLobbyJoinable(joinable: true); } } } [HarmonyPatch(typeof(StartOfRound), "StartGame")] internal static class StartGame_Patch { [HarmonyPrefix] private static void Prefix() { Plugin.SetLobbyJoinable(joinable: false); } } }
plugins/LethalFashion.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalFashion")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Unlocks all base game suits for free to use immediately.")] [assembly: AssemblyFileVersion("1.0.6.0")] [assembly: AssemblyInformationalVersion("1.0.6")] [assembly: AssemblyProduct("LethalFashion")] [assembly: AssemblyTitle("LethalFashion")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.6.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LethalFashion { [BepInPlugin("LethalFashion", "LethalFashion", "1.0.6")] public class Plugin : BaseUnityPlugin { public static ManualLogSource Log; private static Harmony harmonyInstance; public ConfigEntry<string> SuitUnlockConfig; public static Plugin Instance { get; private set; } private void Awake() { Instance = this; Log = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LethalFashion is loaded!"); SuitUnlockConfig = ((BaseUnityPlugin)this).Config.Bind<string>("General", "SuitUnlocks", "Green Suit, Hazard Suit, Pajama Suit, Purple Suit, Bee Suit, Bunny Suit", "Names of the suits to unlock. You can remove them off of this list to ignore unlocking them. This should work for future game updates and can be used to unlock suits from other mods if you know the suit name."); InitializeHarmony(); } private void InitializeHarmony() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown if (harmonyInstance == null) { harmonyInstance = new Harmony("LethalFashion"); try { harmonyInstance.PatchAll(typeof(SuitFashion)); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Patch applied successfully. You are now FASHIONABLE."); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Error applying patch: " + ex.Message)); } } } } public class SuitFashion { private static readonly MethodInfo unlockItem; private static bool isHost; static SuitFashion() { unlockItem = typeof(StartOfRound).GetMethod("SpawnUnlockable", BindingFlags.Instance | BindingFlags.NonPublic); if (unlockItem == null) { Plugin.Log.LogError((object)"SpawnUnlockable method not found in StartOfRound. Please check game/plugin version."); } else { Plugin.Log.LogInfo((object)"SpawnUnlockable method found successfully."); } } public static void SpawnUnlockableDelegate(StartOfRound instance, int ID) { if (unlockItem == null) { Plugin.Log.LogError((object)"SpawnUnlockable method reference is null."); } else if (!instance.SpawnedShipUnlockables.ContainsKey(ID)) { try { unlockItem.Invoke(instance, new object[1] { ID }); } catch (Exception ex) { Plugin.Log.LogError((object)$"Error invoking SpawnUnlockable for ID {ID}: {ex.Message}"); } } } public static void PositionSuitsOnRack(StartOfRound startOfRoundInstance) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) UnlockableSuit[] array = Object.FindObjectsOfType<UnlockableSuit>(); for (int i = 0; i < array.Length; i++) { UnlockableSuit val = array[i]; AutoParentToShip component = ((Component)val).gameObject.GetComponent<AutoParentToShip>(); if ((Object)(object)component != (Object)null) { component.overrideOffset = true; component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + startOfRoundInstance.rightmostSuitPosition.forward * 0.18f * (float)i; component.rotationOffset = new Vector3(0f, 90f, 0f); } } } private static void UnlockAndSpawnSuits(StartOfRound startOfRoundInstance) { string value = Plugin.Instance.SuitUnlockConfig.Value; HashSet<string> hashSet = new HashSet<string>(from s in value.Split(',') select s.Trim(), StringComparer.OrdinalIgnoreCase); for (int i = 0; i < startOfRoundInstance.unlockablesList.unlockables.Count; i++) { UnlockableItem val = startOfRoundInstance.unlockablesList.unlockables[i]; if (val != null && (Object)(object)val.suitMaterial != (Object)null && hashSet.Contains(val.unlockableName)) { Plugin.Log.LogInfo((object)$"Unlocking suit: ID={i}, Name={val.unlockableName}"); val.alreadyUnlocked = true; val.hasBeenUnlockedByPlayer = true; val.inStorage = false; SpawnUnlockableDelegate(startOfRoundInstance, i); } } Plugin.Log.LogInfo((object)"Finished unlocking and spawning suits."); } [HarmonyPatch(typeof(StartOfRound), "Start")] [HarmonyPostfix] public static void StartOfRoundSuitPatch(StartOfRound __instance) { isHost = GameNetworkManager.Instance.isHostingGame; if (isHost) { UnlockAndSpawnSuits(__instance); PositionSuitsOnRack(__instance); } } [HarmonyPatch(typeof(StartOfRound), "ResetShip")] [HarmonyPostfix] public static void ResetShipSuitPatch(StartOfRound __instance) { if (isHost) { StartOfRoundSuitPatch(__instance); } } } public static class PluginInfo { public const string PLUGIN_GUID = "LethalFashion"; public const string PLUGIN_NAME = "LethalFashion"; public const string PLUGIN_VERSION = "1.0.6"; } }
plugins/LethalLib/LethalLib.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using DunGen; using DunGen.Graph; using LethalLib.Extras; using LethalLib.Modules; using LethalLib.NetcodePatcher; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using On; using Unity.Netcode; using UnityEngine; using UnityEngine.Audio; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("ClientNetworkTransform")] [assembly: IgnoresAccessChecksTo("DissonanceVoip")] [assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")] [assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")] [assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")] [assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")] [assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")] [assembly: IgnoresAccessChecksTo("Unity.Burst")] [assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")] [assembly: IgnoresAccessChecksTo("Unity.Collections")] [assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")] [assembly: IgnoresAccessChecksTo("Unity.Jobs")] [assembly: IgnoresAccessChecksTo("Unity.Mathematics")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")] [assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")] [assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")] [assembly: IgnoresAccessChecksTo("Unity.Services.QoS")] [assembly: IgnoresAccessChecksTo("Unity.Services.Relay")] [assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")] [assembly: IgnoresAccessChecksTo("Unity.Timeline")] [assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")] [assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.UI")] [assembly: AssemblyCompany("Evaisa")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Content-addition API for Lethal Company")] [assembly: AssemblyFileVersion("0.16.3.0")] [assembly: AssemblyInformationalVersion("0.16.3+f63350d63539f33122a2a577059d6bbcc9fdee8a")] [assembly: AssemblyProduct("LethalLib")] [assembly: AssemblyTitle("LethalLib")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/EvaisaDev/LethalLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] internal class <Module> { static <Module>() { } } 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 LethalLib { [BepInPlugin("evaisa.lethallib", "LethalLib", "0.16.3")] public class Plugin : BaseUnityPlugin { public const string ModGUID = "evaisa.lethallib"; public const string ModName = "LethalLib"; public const string ModVersion = "0.16.3"; public static AssetBundle MainAssets; public static ManualLogSource logger; public static ConfigFile config; public static Plugin Instance; public static ConfigEntry<bool> extendedLogging; private void Awake() { //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_0092: Unknown result type (might be due to invalid IL or missing references) Instance = this; config = ((BaseUnityPlugin)this).Config; logger = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalLib loaded!!"); extendedLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ExtendedLogging", false, "Enable extended logging"); MainAssets = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "lethallib")); new ILHook((MethodBase)typeof(StackTrace).GetMethod("AddFrames", BindingFlags.Instance | BindingFlags.NonPublic), new Manipulator(IlHook)); Enemies.Init(); Items.Init(); Unlockables.Init(); MapObjects.Init(); Dungeon.Init(); Weathers.Init(); Player.Init(); Utilities.Init(); NetworkPrefabs.Init(); } private void IlHook(ILContext il) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown ILCursor val = new ILCursor(il); MethodInfo getFileLineNumberMethod = typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public); if (val.TryGotoNext(new Func<Instruction, bool>[1] { (Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)getFileLineNumberMethod) })) { val.RemoveRange(2); val.EmitDelegate<Func<StackFrame, string>>((Func<StackFrame, string>)GetLineOrIL); } } private static string GetLineOrIL(StackFrame instance) { int fileLineNumber = instance.GetFileLineNumber(); if (fileLineNumber == -1 || fileLineNumber == 0) { return "IL_" + instance.GetILOffset().ToString("X4"); } return fileLineNumber.ToString(); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "LethalLib"; public const string PLUGIN_NAME = "LethalLib"; public const string PLUGIN_VERSION = "0.16.3"; } } namespace LethalLib.Modules { public class ContentLoader { public class CustomContent { private string id = ""; public string ID => id; public CustomContent(string id) { this.id = id; } } public class CustomItem : CustomContent { public Action<Item> registryCallback = delegate { }; public string contentPath = ""; internal Item item; public Item Item => item; public CustomItem(string id, string contentPath, Action<Item> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } } } public class ShopItem : CustomItem { public int initPrice; public string buyNode1Path; public string buyNode2Path; public string itemInfoPath; public void RemoveFromShop() { Items.RemoveShopItem(base.Item); } public void SetPrice(int price) { Items.UpdateShopItemPrice(base.Item, price); } public ShopItem(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, Action<Item> registryCallback = null) : base(id, contentPath, registryCallback) { initPrice = price; this.buyNode1Path = buyNode1Path; this.buyNode2Path = buyNode2Path; this.itemInfoPath = itemInfoPath; } } public class ScrapItem : CustomItem { public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>(); public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>(); public int Rarity => 0; public void RemoveFromLevels(Levels.LevelTypes levelFlags) { Items.RemoveScrapFromLevels(base.Item, levelFlags); } public ScrapItem(string id, string contentPath, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Action<Item> registryCallback = null) : base(id, contentPath, registryCallback) { if (levelFlags != Levels.LevelTypes.None) { levelRarities.Add(levelFlags, rarity); } else if (levelOverrides != null) { foreach (string key in levelOverrides) { customLevelRarities.Add(key, rarity); } } } public ScrapItem(string id, string contentPath, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, Action<Item> registryCallback = null) : base(id, contentPath, registryCallback) { if (levelRarities != null) { this.levelRarities = levelRarities; } if (customLevelRarities != null) { this.customLevelRarities = customLevelRarities; } } } public class Unlockable : CustomContent { public Action<UnlockableItem> registryCallback = delegate { }; internal UnlockableItem unlockable; public string contentPath = ""; public int initPrice; public string buyNode1Path; public string buyNode2Path; public string itemInfoPath; public StoreType storeType; public UnlockableItem UnlockableItem => unlockable; public void RemoveFromShop() { Unlockables.DisableUnlockable(UnlockableItem); } public void SetPrice(int price) { Unlockables.UpdateUnlockablePrice(UnlockableItem, price); } public Unlockable(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, StoreType storeType = StoreType.None, Action<UnlockableItem> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } initPrice = price; this.buyNode1Path = buyNode1Path; this.buyNode2Path = buyNode2Path; this.itemInfoPath = itemInfoPath; this.storeType = storeType; } } public class CustomEnemy : CustomContent { public Action<EnemyType> registryCallback = delegate { }; public string contentPath = ""; internal EnemyType enemy; public string infoNodePath; public string infoKeywordPath; public int rarity; public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None; public string[] levelOverrides; public Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1); public EnemyType Enemy => enemy; public void RemoveFromLevels(Levels.LevelTypes levelFlags) { Enemies.RemoveEnemyFromLevels(Enemy, levelFlags); } public CustomEnemy(string id, string contentPath, int rarity = 0, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1), string[] levelOverrides = null, string infoNodePath = null, string infoKeywordPath = null, Action<EnemyType> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } this.infoNodePath = infoNodePath; this.infoKeywordPath = infoKeywordPath; this.rarity = rarity; LevelTypes = levelFlags; this.levelOverrides = levelOverrides; this.spawnType = spawnType; } } public class MapHazard : CustomContent { public Action<SpawnableMapObjectDef> registryCallback = delegate { }; public string contentPath = ""; internal SpawnableMapObjectDef hazard; public Func<SelectableLevel, AnimationCurve> spawnRateFunction; public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None; public string[] levelOverrides; public SpawnableMapObjectDef Hazard => hazard; public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { MapObjects.RemoveMapObject(Hazard, levelFlags, levelOverrides); } public MapHazard(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableMapObjectDef> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } LevelTypes = levelFlags; this.levelOverrides = levelOverrides; this.spawnRateFunction = spawnRateFunction; } } public class OutsideObject : CustomContent { public Action<SpawnableOutsideObjectDef> registryCallback = delegate { }; public string contentPath = ""; internal SpawnableOutsideObjectDef mapObject; public Func<SelectableLevel, AnimationCurve> spawnRateFunction; public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None; public string[] levelOverrides; public SpawnableOutsideObjectDef MapObject => mapObject; public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { MapObjects.RemoveOutsideObject(MapObject, levelFlags, levelOverrides); } public OutsideObject(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableOutsideObjectDef> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } LevelTypes = levelFlags; this.levelOverrides = levelOverrides; this.spawnRateFunction = spawnRateFunction; } } public PluginInfo modInfo; private AssetBundle modBundle; public Action<CustomContent, GameObject> prefabCallback = delegate { }; public Dictionary<string, CustomContent> LoadedContent { get; } = new Dictionary<string, CustomContent>(); public string modName => modInfo.Metadata.Name; public string modVersion => modInfo.Metadata.Version.ToString(); public string modGUID => modInfo.Metadata.GUID; public ContentLoader(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null) { this.modInfo = modInfo; this.modBundle = modBundle; if (prefabCallback != null) { this.prefabCallback = prefabCallback; } } public ContentLoader Create(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null) { return new ContentLoader(modInfo, modBundle, prefabCallback); } public void Register(CustomContent content) { if (LoadedContent.ContainsKey(content.ID)) { Debug.LogError((object)("[LethalLib] " + modName + " tried to register content with ID " + content.ID + " but it already exists!")); return; } if (content is CustomItem customItem) { Item val = (customItem.item = modBundle.LoadAsset<Item>(customItem.contentPath)); NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab); Utilities.FixMixerGroups(val.spawnPrefab); prefabCallback(customItem, val.spawnPrefab); customItem.registryCallback(val); if (content is ShopItem shopItem) { TerminalNode buyNode = null; TerminalNode buyNode2 = null; TerminalNode itemInfo = null; if (shopItem.buyNode1Path != null) { buyNode = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode1Path); } if (shopItem.buyNode2Path != null) { buyNode2 = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode2Path); } if (shopItem.itemInfoPath != null) { itemInfo = modBundle.LoadAsset<TerminalNode>(shopItem.itemInfoPath); } Items.RegisterShopItem(val, buyNode, buyNode2, itemInfo, shopItem.initPrice); } else if (content is ScrapItem scrapItem) { Items.RegisterScrap(val, scrapItem.levelRarities, scrapItem.customLevelRarities); } else { Items.RegisterItem(val); } } else if (content is Unlockable unlockable) { UnlockableItemDef unlockableItemDef = modBundle.LoadAsset<UnlockableItemDef>(unlockable.contentPath); if ((Object)(object)unlockableItemDef.unlockable.prefabObject != (Object)null) { NetworkPrefabs.RegisterNetworkPrefab(unlockableItemDef.unlockable.prefabObject); prefabCallback(content, unlockableItemDef.unlockable.prefabObject); Utilities.FixMixerGroups(unlockableItemDef.unlockable.prefabObject); } unlockable.unlockable = unlockableItemDef.unlockable; unlockable.registryCallback(unlockableItemDef.unlockable); TerminalNode buyNode3 = null; TerminalNode buyNode4 = null; TerminalNode itemInfo2 = null; if (unlockable.buyNode1Path != null) { buyNode3 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode1Path); } if (unlockable.buyNode2Path != null) { buyNode4 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode2Path); } if (unlockable.itemInfoPath != null) { itemInfo2 = modBundle.LoadAsset<TerminalNode>(unlockable.itemInfoPath); } Unlockables.RegisterUnlockable(unlockableItemDef, unlockable.storeType, buyNode3, buyNode4, itemInfo2, unlockable.initPrice); } else if (content is CustomEnemy customEnemy) { EnemyType val2 = modBundle.LoadAsset<EnemyType>(customEnemy.contentPath); NetworkPrefabs.RegisterNetworkPrefab(val2.enemyPrefab); Utilities.FixMixerGroups(val2.enemyPrefab); customEnemy.enemy = val2; prefabCallback(content, val2.enemyPrefab); customEnemy.registryCallback(val2); TerminalNode infoNode = null; TerminalKeyword infoKeyword = null; if (customEnemy.infoNodePath != null) { infoNode = modBundle.LoadAsset<TerminalNode>(customEnemy.infoNodePath); } if (customEnemy.infoKeywordPath != null) { infoKeyword = modBundle.LoadAsset<TerminalKeyword>(customEnemy.infoKeywordPath); } if (customEnemy.spawnType == (Enemies.SpawnType)(-1)) { Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.levelOverrides, infoNode, infoKeyword); } else { Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.spawnType, customEnemy.levelOverrides, infoNode, infoKeyword); } } else if (content is MapHazard mapHazard) { SpawnableMapObjectDef spawnableMapObjectDef = (mapHazard.hazard = modBundle.LoadAsset<SpawnableMapObjectDef>(mapHazard.contentPath)); NetworkPrefabs.RegisterNetworkPrefab(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn); Utilities.FixMixerGroups(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn); prefabCallback(content, spawnableMapObjectDef.spawnableMapObject.prefabToSpawn); mapHazard.registryCallback(spawnableMapObjectDef); MapObjects.RegisterMapObject(spawnableMapObjectDef, mapHazard.LevelTypes, mapHazard.levelOverrides, mapHazard.spawnRateFunction); } else if (content is OutsideObject outsideObject) { SpawnableOutsideObjectDef spawnableOutsideObjectDef = (outsideObject.mapObject = modBundle.LoadAsset<SpawnableOutsideObjectDef>(outsideObject.contentPath)); NetworkPrefabs.RegisterNetworkPrefab(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn); Utilities.FixMixerGroups(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn); prefabCallback(content, spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn); outsideObject.registryCallback(spawnableOutsideObjectDef); MapObjects.RegisterOutsideObject(spawnableOutsideObjectDef, outsideObject.LevelTypes, outsideObject.levelOverrides, outsideObject.spawnRateFunction); } LoadedContent.Add(content.ID, content); } public void RegisterAll(CustomContent[] content) { Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Length} content items!"); foreach (CustomContent content2 in content) { Register(content2); } } public void RegisterAll(List<CustomContent> content) { Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Count} content items!"); foreach (CustomContent item in content) { Register(item); } } } public class Dungeon { public class CustomDungeonArchetype { public DungeonArchetype archeType; public Levels.LevelTypes LevelTypes; public int lineIndex = -1; } public class CustomGraphLine { public GraphLine graphLine; public Levels.LevelTypes LevelTypes; } public class CustomDungeon { public int rarity; public DungeonFlow dungeonFlow; public Levels.LevelTypes LevelTypes; public string[] levelOverrides; public int dungeonIndex = -1; public AudioClip firstTimeDungeonAudio; } [CompilerGenerated] private static class <>O { public static hook_GenerateNewFloor <0>__RoundManager_GenerateNewFloor; public static hook_Start <1>__RoundManager_Start; } public static List<CustomDungeonArchetype> customDungeonArchetypes = new List<CustomDungeonArchetype>(); public static List<CustomGraphLine> customGraphLines = new List<CustomGraphLine>(); public static Dictionary<string, TileSet> extraTileSets = new Dictionary<string, TileSet>(); public static Dictionary<string, GameObjectChance> extraRooms = new Dictionary<string, GameObjectChance>(); public static List<CustomDungeon> customDungeons = new List<CustomDungeon>(); public static void Init() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //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_003b: Expected O, but got Unknown object obj = <>O.<0>__RoundManager_GenerateNewFloor; if (obj == null) { hook_GenerateNewFloor val = RoundManager_GenerateNewFloor; <>O.<0>__RoundManager_GenerateNewFloor = val; obj = (object)val; } RoundManager.GenerateNewFloor += (hook_GenerateNewFloor)obj; object obj2 = <>O.<1>__RoundManager_Start; if (obj2 == null) { hook_Start val2 = RoundManager_Start; <>O.<1>__RoundManager_Start = val2; obj2 = (object)val2; } RoundManager.Start += (hook_Start)obj2; } private static void RoundManager_Start(orig_Start orig, RoundManager self) { orig.Invoke(self); } private static void RoundManager_GenerateNewFloor(orig_GenerateNewFloor orig, RoundManager self) { string name = ((Object)self.currentLevel).name; if (Enum.IsDefined(typeof(Levels.LevelTypes), name)) { Levels.LevelTypes levelEnum = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name); int index = 0; self.dungeonGenerator.Generator.DungeonFlow.Lines.ForEach(delegate(GraphLine line) { foreach (CustomDungeonArchetype customDungeonArchetype in customDungeonArchetypes) { if (customDungeonArchetype.LevelTypes.HasFlag(levelEnum) && !line.DungeonArchetypes.Contains(customDungeonArchetype.archeType) && (customDungeonArchetype.lineIndex == -1 || customDungeonArchetype.lineIndex == index)) { line.DungeonArchetypes.Add(customDungeonArchetype.archeType); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)("Added " + ((Object)customDungeonArchetype.archeType).name + " to " + name)); } } } foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes) { string name2 = ((Object)dungeonArchetype).name; if (extraTileSets.ContainsKey(name2)) { TileSet val4 = extraTileSets[name2]; if (!dungeonArchetype.TileSets.Contains(val4)) { dungeonArchetype.TileSets.Add(val4); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)("Added " + ((Object)val4).name + " to " + name)); } } } foreach (TileSet tileSet in dungeonArchetype.TileSets) { string name3 = ((Object)tileSet).name; if (extraRooms.ContainsKey(name3)) { GameObjectChance item = extraRooms[name3]; if (!tileSet.TileWeights.Weights.Contains(item)) { tileSet.TileWeights.Weights.Add(item); } } } } index++; }); foreach (CustomGraphLine customGraphLine in customGraphLines) { if (customGraphLine.LevelTypes.HasFlag(levelEnum) && !self.dungeonGenerator.Generator.DungeonFlow.Lines.Contains(customGraphLine.graphLine)) { self.dungeonGenerator.Generator.DungeonFlow.Lines.Add(customGraphLine.graphLine); } } } orig.Invoke(self); NetworkManager val = Object.FindObjectOfType<NetworkManager>(); RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>(); foreach (RandomMapObject val2 in array) { for (int j = 0; j < val2.spawnablePrefabs.Count; j++) { string prefabName = ((Object)val2.spawnablePrefabs[j]).name; NetworkPrefab val3 = ((IEnumerable<NetworkPrefab>)val.NetworkConfig.Prefabs.m_Prefabs).FirstOrDefault((Func<NetworkPrefab, bool>)((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName)); if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j]) { val2.spawnablePrefabs[j] = val3.Prefab; } else if (val3 == null) { Plugin.logger.LogError((object)("DungeonGeneration - Could not find network prefab (" + prefabName + ")! Make sure your assigned prefab is registered with the network manager, or named identically to the vanilla prefab you are referencing.")); } } } } public static void AddArchetype(DungeonArchetype archetype, Levels.LevelTypes levelFlags, int lineIndex = -1) { CustomDungeonArchetype customDungeonArchetype = new CustomDungeonArchetype(); customDungeonArchetype.archeType = archetype; customDungeonArchetype.LevelTypes = levelFlags; customDungeonArchetype.lineIndex = lineIndex; customDungeonArchetypes.Add(customDungeonArchetype); } public static void AddLine(GraphLine line, Levels.LevelTypes levelFlags) { CustomGraphLine customGraphLine = new CustomGraphLine(); customGraphLine.graphLine = line; customGraphLine.LevelTypes = levelFlags; customGraphLines.Add(customGraphLine); } public static void AddLine(DungeonGraphLineDef line, Levels.LevelTypes levelFlags) { AddLine(line.graphLine, levelFlags); } public static void AddTileSet(TileSet set, string archetypeName) { extraTileSets.Add(archetypeName, set); } public static void AddRoom(GameObjectChance room, string tileSetName) { extraRooms.Add(tileSetName, room); } public static void AddRoom(GameObjectChanceDef room, string tileSetName) { AddRoom(room.gameObjectChance, tileSetName); } public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags) { AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, dungeon.firstTimeDungeonAudio); } public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags, string[] levelOverrides) { AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, levelOverrides, dungeon.firstTimeDungeonAudio); } public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, AudioClip firstTimeDungeonAudio = null) { customDungeons.Add(new CustomDungeon { dungeonFlow = dungeon, rarity = rarity, LevelTypes = levelFlags, firstTimeDungeonAudio = firstTimeDungeonAudio }); } public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, string[] levelOverrides = null, AudioClip firstTimeDungeonAudio = null) { customDungeons.Add(new CustomDungeon { dungeonFlow = dungeon, rarity = rarity, LevelTypes = levelFlags, firstTimeDungeonAudio = firstTimeDungeonAudio, levelOverrides = levelOverrides }); } } public class Enemies { public struct EnemyAssetInfo { public EnemyType EnemyAsset; public TerminalKeyword keyword; } public enum SpawnType { Default, Daytime, Outside } public class SpawnableEnemy { public EnemyType enemy; public SpawnType spawnType; public TerminalNode terminalNode; public TerminalKeyword infoKeyword; public string modName; public int rarity; public Levels.LevelTypes spawnLevels; public string[] spawnLevelOverrides; public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>(); public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>(); public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null) { this.enemy = enemy; this.spawnLevels = spawnLevels; this.spawnType = spawnType; if (spawnLevelOverrides != null) { foreach (string levelName in spawnLevelOverrides) { customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity); } } if (spawnLevels == Levels.LevelTypes.None) { return; } foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes))) { if (spawnLevels.HasFlag(value)) { levelRarities.Add(value, rarity); } } } public SpawnableEnemy(EnemyType enemy, SpawnType spawnType, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null) { this.enemy = enemy; this.spawnType = spawnType; if (levelRarities != null) { this.levelRarities = levelRarities; } if (customLevelRarities != null) { this.customLevelRarities = Levels.Compatibility.LLLifyLevelRarityDictionary(customLevelRarities); } } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__RegisterLevelEnemies; public static hook_Start <1>__Terminal_Start; public static hook_Start <2>__QuickMenuManager_Start; public static hook_Start <3>__RegisterLevelEnemiesforLLL_RoundManager_Start; public static hook_Start <4>__RegisterLevelEnemiesforLE_Terminal_Start; } private static List<SelectableLevel> levelsAlreadyAddedTo = new List<SelectableLevel>(); private static bool addedToDebug = false; public static Terminal terminal; public static List<EnemyAssetInfo> enemyAssetInfos = new List<EnemyAssetInfo>(); public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>(); public static void Init() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //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_003b: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown object obj = <>O.<0>__RegisterLevelEnemies; if (obj == null) { hook_Awake val = RegisterLevelEnemies; <>O.<0>__RegisterLevelEnemies = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__Terminal_Start; if (obj2 == null) { hook_Start val2 = Terminal_Start; <>O.<1>__Terminal_Start = val2; obj2 = (object)val2; } Terminal.Start += (hook_Start)obj2; object obj3 = <>O.<2>__QuickMenuManager_Start; if (obj3 == null) { hook_Start val3 = QuickMenuManager_Start; <>O.<2>__QuickMenuManager_Start = val3; obj3 = (object)val3; } QuickMenuManager.Start += (hook_Start)obj3; } private static void QuickMenuManager_Start(orig_Start orig, QuickMenuManager self) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown if (addedToDebug) { orig.Invoke(self); return; } SelectableLevel testAllEnemiesLevel = self.testAllEnemiesLevel; List<SpawnableEnemyWithRarity> enemies = testAllEnemiesLevel.Enemies; List<SpawnableEnemyWithRarity> daytimeEnemies = testAllEnemiesLevel.DaytimeEnemies; List<SpawnableEnemyWithRarity> outsideEnemies = testAllEnemiesLevel.OutsideEnemies; foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { if (enemies.All((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { continue; } SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity { enemyType = spawnableEnemy.enemy, rarity = spawnableEnemy.rarity }; switch (spawnableEnemy.spawnType) { case SpawnType.Default: if (!enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { enemies.Add(item); } break; case SpawnType.Daytime: if (!daytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { daytimeEnemies.Add(item); } break; case SpawnType.Outside: if (!outsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { outsideEnemies.Add(item); } break; } if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)$"Added {spawnableEnemy.enemy.enemyName} to DebugList [{spawnableEnemy.spawnType}]"); } } addedToDebug = true; orig.Invoke(self); } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0252: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Expected O, but got Unknown terminal = self; TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); List<string> list = new List<string>(); foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { if (list.Contains(spawnableEnemy.enemy.enemyName)) { Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added")); continue; } if ((Object)(object)spawnableEnemy.terminalNode == (Object)null) { spawnableEnemy.terminalNode = ScriptableObject.CreateInstance<TerminalNode>(); spawnableEnemy.terminalNode.displayText = spawnableEnemy.enemy.enemyName + "\n\nDanger level: Unknown\n\n[No information about this creature was found.]\n\n"; spawnableEnemy.terminalNode.clearPreviousText = true; spawnableEnemy.terminalNode.maxCharactersToType = 35; spawnableEnemy.terminalNode.creatureName = spawnableEnemy.enemy.enemyName; } if (self.enemyFiles.Any((TerminalNode x) => x.creatureName == spawnableEnemy.terminalNode.creatureName)) { Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added")); continue; } TerminalKeyword keyword2 = (((Object)(object)spawnableEnemy.infoKeyword != (Object)null) ? spawnableEnemy.infoKeyword : TerminalUtils.CreateTerminalKeyword(spawnableEnemy.terminalNode.creatureName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val)); keyword2.defaultVerb = val; List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); if (!list2.Any((TerminalKeyword x) => x.word == keyword2.word)) { list2.Add(keyword2); self.terminalNodes.allKeywords = list2.ToArray(); } List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); if (!list3.Any((CompatibleNoun x) => x.noun.word == keyword2.word)) { list3.Add(new CompatibleNoun { noun = keyword2, result = spawnableEnemy.terminalNode }); } val.compatibleNouns = list3.ToArray(); spawnableEnemy.terminalNode.creatureFileID = self.enemyFiles.Count; self.enemyFiles.Add(spawnableEnemy.terminalNode); ScanNodeProperties[] componentsInChildren = spawnableEnemy.enemy.enemyPrefab.GetComponentsInChildren<ScanNodeProperties>(); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].creatureScanID = spawnableEnemy.terminalNode.creatureFileID; } EnemyAssetInfo enemyAssetInfo = default(EnemyAssetInfo); enemyAssetInfo.EnemyAsset = spawnableEnemy.enemy; enemyAssetInfo.keyword = keyword2; EnemyAssetInfo item = enemyAssetInfo; enemyAssetInfos.Add(item); } orig.Invoke(self); } private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown orig.Invoke(self); RegisterLethalLibEnemiesForAllLevels(); if (Chainloader.PluginInfos.ContainsKey("imabatby.lethallevelloader") || Chainloader.PluginInfos.ContainsKey("iambatby.lethallevelloader")) { object obj = <>O.<3>__RegisterLevelEnemiesforLLL_RoundManager_Start; if (obj == null) { hook_Start val = RegisterLevelEnemiesforLLL_RoundManager_Start; <>O.<3>__RegisterLevelEnemiesforLLL_RoundManager_Start = val; obj = (object)val; } RoundManager.Start += (hook_Start)obj; } if (Chainloader.PluginInfos.ContainsKey("LethalExpansion")) { object obj2 = <>O.<4>__RegisterLevelEnemiesforLE_Terminal_Start; if (obj2 == null) { hook_Start val2 = RegisterLevelEnemiesforLE_Terminal_Start; <>O.<4>__RegisterLevelEnemiesforLE_Terminal_Start = val2; obj2 = (object)val2; } Terminal.Start += (hook_Start)obj2; } } private static void RegisterLevelEnemiesforLLL_RoundManager_Start(orig_Start orig, RoundManager self) { orig.Invoke(self); RegisterLethalLibEnemiesForAllLevels(); } private static void RegisterLevelEnemiesforLE_Terminal_Start(orig_Start orig, Terminal self) { orig.Invoke(self); RegisterLethalLibEnemiesForAllLevels(); } private static void RegisterLethalLibEnemiesForAllLevels() { SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { if (levelsAlreadyAddedTo.Contains(val)) { continue; } foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { AddEnemyToLevel(spawnableEnemy, val); } levelsAlreadyAddedTo.Add(val); } } private static void AddEnemyToLevel(SpawnableEnemy spawnableEnemy, SelectableLevel level) { //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Expected O, but got Unknown SpawnableEnemy spawnableEnemy2 = spawnableEnemy; string text = ((Object)level).name; bool flag = spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.All) || spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Vanilla) || (spawnableEnemy2.customLevelRarities != null && spawnableEnemy2.customLevelRarities.ContainsKey(text)); if (spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), text)) { flag = true; } Levels.LevelTypes levelTypes = Levels.LevelTypes.None; bool flag2 = false; if (Enum.IsDefined(typeof(Levels.LevelTypes), text)) { levelTypes = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), text); flag2 = true; } else { text = Levels.Compatibility.GetLLLNameOfLevel(text); } if (!(flag2 || flag)) { return; } Levels.LevelTypes key = (flag ? Levels.LevelTypes.All : levelTypes); if (!flag && !spawnableEnemy2.levelRarities.ContainsKey(key)) { return; } int num = 0; if (flag2 && spawnableEnemy2.levelRarities.ContainsKey(levelTypes)) { num = spawnableEnemy2.levelRarities[levelTypes]; } else if (flag2 && spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Vanilla)) { num = spawnableEnemy2.levelRarities[Levels.LevelTypes.Vanilla]; } else if (!flag2 && spawnableEnemy2.customLevelRarities != null && spawnableEnemy2.customLevelRarities.ContainsKey(text)) { num = spawnableEnemy2.customLevelRarities[text]; } else if (!flag2 && spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.Modded)) { num = spawnableEnemy2.levelRarities[Levels.LevelTypes.Modded]; } else if (spawnableEnemy2.levelRarities.ContainsKey(Levels.LevelTypes.All)) { num = spawnableEnemy2.levelRarities[Levels.LevelTypes.All]; } SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity { enemyType = spawnableEnemy2.enemy, rarity = num }; switch (spawnableEnemy2.spawnType) { case SpawnType.Default: if (!level.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy)) { level.Enemies.Add(item); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} and SpawnType [Default]"); } } break; case SpawnType.Daytime: if (!level.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy)) { level.DaytimeEnemies.Add(item); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} andSpawnType [Daytime]"); } } break; case SpawnType.Outside: if (!level.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy2.enemy)) { level.OutsideEnemies.Add(item); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)$"To {text} added {((Object)spawnableEnemy2.enemy).name} with weight {num} and SpawnType [Outside]"); } } break; } } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { RegisterEnemy(enemy, rarity, levelFlags, spawnType, null, infoNode, infoKeyword); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { EnemyType enemy2 = enemy; EnemyNullCheck(enemy2); SpawnableEnemy spawnableEnemy = spawnableEnemies.FirstOrDefault((SpawnableEnemy x) => (Object)(object)x.enemy == (Object)(object)enemy2 && x.spawnType == spawnType); if (spawnableEnemy != null) { if (levelFlags != Levels.LevelTypes.None) { spawnableEnemy.levelRarities.Add(levelFlags, rarity); } if (spawnLevelOverrides != null) { foreach (string levelName in spawnLevelOverrides) { spawnableEnemy.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity); } } } else { spawnableEnemy = new SpawnableEnemy(enemy2, rarity, levelFlags, spawnType, spawnLevelOverrides); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; FinalizeRegisterEnemy(spawnableEnemy); } } public static void RegisterEnemy(EnemyType enemy, SpawnType spawnType, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { EnemyType enemy2 = enemy; EnemyNullCheck(enemy2); SpawnableEnemy spawnableEnemy = spawnableEnemies.FirstOrDefault((SpawnableEnemy x) => (Object)(object)x.enemy == (Object)(object)enemy2 && x.spawnType == spawnType); if (spawnableEnemy != null) { if (levelRarities != null) { foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities) { spawnableEnemy.levelRarities.Add(levelRarity.Key, levelRarity.Value); } } if (customLevelRarities == null) { return; } { foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities) { spawnableEnemy.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(customLevelRarity.Key), customLevelRarity.Value); } return; } } spawnableEnemy = new SpawnableEnemy(enemy2, spawnType, levelRarities, customLevelRarities); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; FinalizeRegisterEnemy(spawnableEnemy); } private static void FinalizeRegisterEnemy(SpawnableEnemy spawnableEnemy) { string name = Assembly.GetCallingAssembly().GetName().Name; spawnableEnemy.modName = name; if (spawnableEnemy.enemy.enemyPrefab == null) { throw new NullReferenceException("Cannot register enemy '" + spawnableEnemy.enemy.enemyName + "', because enemy.enemyPrefab is null!"); } EnemyAICollisionDetect[] componentsInChildren = spawnableEnemy.enemy.enemyPrefab.GetComponentsInChildren<EnemyAICollisionDetect>(); foreach (EnemyAICollisionDetect val in componentsInChildren) { if (val.mainScript == null) { Plugin.logger.LogWarning((object)("An Enemy AI Collision Detect Script on GameObject '" + ((Object)((Component)val).gameObject).name + "' of enemy '" + spawnableEnemy.enemy.enemyName + "' does not reference a 'Main Script', and could cause Null Reference Exceptions.")); } } spawnableEnemies.Add(spawnableEnemy); } private static void EnemyNullCheck(EnemyType enemy) { if (enemy == null) { throw new ArgumentNullException("enemy", "The first argument of RegisterEnemy was null!"); } } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { EnemyNullCheck(enemy); SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default)); RegisterEnemy(enemy, rarity, levelFlags, spawnType, null, infoNode, infoKeyword); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { EnemyNullCheck(enemy); SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default)); RegisterEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides, infoNode, infoKeyword); } public static void RegisterEnemy(EnemyType enemy, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { EnemyNullCheck(enemy); SpawnType spawnType = (enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default)); RegisterEnemy(enemy, spawnType, levelRarities, customLevelRarities, infoNode, infoKeyword); } public static void RemoveEnemyFromLevels(EnemyType enemyType, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { EnemyType enemyType2 = enemyType; if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; if (!Enum.IsDefined(typeof(Levels.LevelTypes), name)) { name = Levels.Compatibility.GetLLLNameOfLevel(name); } bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => Levels.Compatibility.GetLLLNameOfLevel(item).ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name)) { flag = true; } if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || levelFlags.HasFlag(levelTypes)) { List<SpawnableEnemyWithRarity> enemies = val.Enemies; List<SpawnableEnemyWithRarity> daytimeEnemies = val.DaytimeEnemies; List<SpawnableEnemyWithRarity> outsideEnemies = val.OutsideEnemies; enemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2); daytimeEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2); outsideEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType2); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)("Removed Enemy " + ((Object)enemyType2).name + " from Level " + name)); } } } } } public class Items { public struct ItemSaveOrderData { public int itemId; public string itemName; public string assetName; } public struct BuyableItemAssetInfo { public Item itemAsset; public TerminalKeyword keyword; } public class ScrapItem { public Item item; public Item origItem; public int rarity; public Levels.LevelTypes spawnLevels; public string[] spawnLevelOverrides; public string modName = "Unknown"; public Dictionary<string, int> customLevelRarities = new Dictionary<string, int>(); public Dictionary<Levels.LevelTypes, int> levelRarities = new Dictionary<Levels.LevelTypes, int>(); public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null) { //IL_00fd: Unknown result type (might be due to invalid IL or missing references) origItem = item; if (!item.isScrap) { item = item.Clone<Item>(); item.isScrap = true; if (item.maxValue == 0 && item.minValue == 0) { item.minValue = 40; item.maxValue = 100; } else if (item.maxValue == 0) { item.maxValue = item.minValue * 2; } else if (item.minValue == 0) { item.minValue = item.maxValue / 2; } GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab); if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null) { val.GetComponent<GrabbableObject>().itemProperties = item; } if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null) { GameObject obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform); ((Object)obj).name = "ScanNode"; obj.transform.localPosition = new Vector3(0f, 0f, 0f); obj.GetComponent<ScanNodeProperties>().headerText = item.itemName; } item.spawnPrefab = val; } this.item = item; if (spawnLevelOverrides != null) { foreach (string levelName in spawnLevelOverrides) { customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity); } } if (spawnLevels == Levels.LevelTypes.None) { return; } foreach (Levels.LevelTypes value in Enum.GetValues(typeof(Levels.LevelTypes))) { if (spawnLevels.HasFlag(value)) { levelRarities.Add(value, rarity); } } } public ScrapItem(Item item, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null) { //IL_00fd: Unknown result type (might be due to invalid IL or missing references) origItem = item; if (!item.isScrap) { item = item.Clone<Item>(); item.isScrap = true; if (item.maxValue == 0 && item.minValue == 0) { item.minValue = 40; item.maxValue = 100; } else if (item.maxValue == 0) { item.maxValue = item.minValue * 2; } else if (item.minValue == 0) { item.minValue = item.maxValue / 2; } GameObject val = NetworkPrefabs.CloneNetworkPrefab(item.spawnPrefab); if ((Object)(object)val.GetComponent<GrabbableObject>() != (Object)null) { val.GetComponent<GrabbableObject>().itemProperties = item; } if ((Object)(object)val.GetComponentInChildren<ScanNodeProperties>() == (Object)null) { GameObject obj = Object.Instantiate<GameObject>(scanNodePrefab, val.transform); ((Object)obj).name = "ScanNode"; obj.transform.localPosition = new Vector3(0f, 0f, 0f); obj.GetComponent<ScanNodeProperties>().headerText = item.itemName; } item.spawnPrefab = val; } this.item = item; if (customLevelRarities != null) { this.customLevelRarities = Levels.Compatibility.LLLifyLevelRarityDictionary(customLevelRarities); } if (levelRarities != null) { this.levelRarities = levelRarities; } } } public class PlainItem { public Item item; public string modName; public PlainItem(Item item) { this.item = item; } } public class ShopItem { public Item item; public Item origItem; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public bool wasRemoved; public int price; public string modName; public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0) { origItem = item; this.item = item; this.price = price; if ((Object)(object)buyNode1 != (Object)null) { this.buyNode1 = buyNode1; } if ((Object)(object)buyNode2 != (Object)null) { this.buyNode2 = buyNode2; } if ((Object)(object)itemInfo != (Object)null) { this.itemInfo = itemInfo; } } } [CompilerGenerated] private static class <>O { public static hook_Start <0>__StartOfRound_Start; public static hook_Awake <1>__Terminal_Awake; public static hook_TextPostProcess <2>__Terminal_TextPostProcess; public static hook_Start <3>__RegisterLevelScrapforLLL_RoundManager_Start; public static hook_Start <4>__RegisterLevelScrapforLE_Terminal_Start; } public static ConfigEntry<bool> useSavedataFix; public static GameObject scanNodePrefab; private static List<SelectableLevel> levelsAlreadyAddedTo = new List<SelectableLevel>(); public static List<Item> LethalLibItemList = new List<Item>(); public static List<BuyableItemAssetInfo> buyableItemAssetInfos = new List<BuyableItemAssetInfo>(); public static Terminal terminal; public static List<ScrapItem> scrapItems = new List<ScrapItem>(); public static List<ShopItem> shopItems = new List<ShopItem>(); public static List<PlainItem> plainItems = new List<PlainItem>(); public static void Init() { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //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_006e: Expected O, but got Unknown //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown useSavedataFix = Plugin.config.Bind<bool>("Items", "EnableItemSaveFix", false, "Allow for LethalLib to store/reorder the item list, which should fix issues where items get reshuffled when loading an old save. This is experimental and may cause save corruptions occasionally."); scanNodePrefab = Plugin.MainAssets.LoadAsset<GameObject>("Assets/Custom/ItemScanNode.prefab"); object obj = <>O.<0>__StartOfRound_Start; if (obj == null) { hook_Start val = StartOfRound_Start; <>O.<0>__StartOfRound_Start = val; obj = (object)val; } StartOfRound.Start += (hook_Start)obj; object obj2 = <>O.<1>__Terminal_Awake; if (obj2 == null) { hook_Awake val2 = Terminal_Awake; <>O.<1>__Terminal_Awake = val2; obj2 = (object)val2; } Terminal.Awake += (hook_Awake)obj2; object obj3 = <>O.<2>__Terminal_TextPostProcess; if (obj3 == null) { hook_TextPostProcess val3 = Terminal_TextPostProcess; <>O.<2>__Terminal_TextPostProcess = val3; obj3 = (object)val3; } Terminal.TextPostProcess += (hook_TextPostProcess)obj3; } private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node) { List<Item> list = self.buyableItemsList.ToList(); List<Item> list2 = self.buyableItemsList.ToList(); list2.RemoveAll((Item x) => shopItems.FirstOrDefault((ShopItem item) => (Object)(object)item.origItem == (Object)(object)x || (Object)(object)item.item == (Object)(object)x)?.wasRemoved ?? false); self.buyableItemsList = list2.ToArray(); string result = orig.Invoke(self, modifiedDisplayText, node); self.buyableItemsList = list.ToArray(); return result; } private static void StartOfRound_Start(orig_Start orig, StartOfRound self) { if (useSavedataFix.Value && ((NetworkBehaviour)self).IsHost) { Plugin.logger.LogInfo((object)"Fixing Item savedata!!"); List<ItemSaveOrderData> itemList = new List<ItemSaveOrderData>(); StartOfRound.Instance.allItemsList.itemsList.ForEach(delegate(Item item) { itemList.Add(new ItemSaveOrderData { itemId = item.itemId, itemName = item.itemName, assetName = ((Object)item).name }); }); if (ES3.KeyExists("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName)) { itemList = ES3.Load<List<ItemSaveOrderData>>("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName); } List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList; List<Item> list = new List<Item>(); foreach (ItemSaveOrderData item2 in itemList) { Item val = ((IEnumerable<Item>)itemsList).FirstOrDefault((Func<Item, bool>)((Item x) => x.itemId == item2.itemId && x.itemName == item2.itemName && item2.assetName == ((Object)x).name)); if ((Object)(object)val != (Object)null) { list.Add(val); } else { list.Add(ScriptableObject.CreateInstance<Item>()); } } foreach (Item item3 in itemsList) { if (!list.Contains(item3)) { list.Add(item3); } } StartOfRound.Instance.allItemsList.itemsList = list; ES3.Save<List<ItemSaveOrderData>>("LethalLibAllItemsList", itemList, GameNetworkManager.Instance.currentSaveFileName); } orig.Invoke(self); } private static void RegisterLevelScrapforLLL_RoundManager_Start(orig_Start orig, RoundManager self) { orig.Invoke(self); RegisterLethalLibScrapItemsForAllLevels(); } private static void RegisterLevelScrapforLE_Terminal_Start(orig_Start orig, Terminal self) { orig.Invoke(self); RegisterLethalLibScrapItemsForAllLevels(); } private static void RegisterLethalLibScrapItemsForAllLevels() { SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { if (levelsAlreadyAddedTo.Contains(val)) { continue; } foreach (ScrapItem scrapItem in scrapItems) { AddScrapItemToLevel(scrapItem, val); } levelsAlreadyAddedTo.Add(val); } } private static void AddScrapItemToLevel(ScrapItem scrapItem, SelectableLevel level) { //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Expected O, but got Unknown ScrapItem scrapItem2 = scrapItem; string text = ((Object)level).name; bool flag = scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.All) || scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.Vanilla) || (scrapItem2.customLevelRarities != null && scrapItem2.customLevelRarities.ContainsKey(text)); if (scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), text)) { flag = true; } Levels.LevelTypes key = Levels.LevelTypes.None; bool flag2 = false; if (Enum.IsDefined(typeof(Levels.LevelTypes), text)) { key = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), text); flag2 = true; } else { text = Levels.Compatibility.GetLLLNameOfLevel(text); } if (!(flag2 || flag)) { return; } Levels.LevelTypes key2 = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), text))); if (!flag && !scrapItem2.levelRarities.ContainsKey(key2)) { return; } int rarity = 0; if (flag2 && scrapItem2.levelRarities.ContainsKey(key)) { rarity = scrapItem2.levelRarities[key]; } else if (flag2 && scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.Vanilla)) { rarity = scrapItem2.levelRarities[Levels.LevelTypes.Vanilla]; } else if (!flag2 && scrapItem2.customLevelRarities != null && scrapItem2.customLevelRarities.ContainsKey(text)) { rarity = scrapItem2.customLevelRarities[text]; } else if (!flag2 && scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.Modded)) { rarity = scrapItem2.levelRarities[Levels.LevelTypes.Modded]; } else if (scrapItem2.levelRarities.ContainsKey(Levels.LevelTypes.All)) { rarity = scrapItem2.levelRarities[Levels.LevelTypes.All]; } SpawnableItemWithRarity item = new SpawnableItemWithRarity { spawnableItem = scrapItem2.item, rarity = rarity }; if (!level.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem2.item)) { level.spawnableScrap.Add(item); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)("To " + text + " added " + ((Object)scrapItem2.item).name)); } } } private static void RegisterScrapAsItem(StartOfRound startOfRound) { foreach (ScrapItem scrapItem in scrapItems) { if (startOfRound.allItemsList.itemsList.Contains(scrapItem.item)) { continue; } if (Plugin.extendedLogging.Value) { if (scrapItem.modName != "LethalLib") { Plugin.logger.LogInfo((object)(scrapItem.modName + " registered scrap item: " + scrapItem.item.itemName)); } else { Plugin.logger.LogInfo((object)("Registered scrap item: " + scrapItem.item.itemName)); } } LethalLibItemList.Add(scrapItem.item); startOfRound.allItemsList.itemsList.Add(scrapItem.item); } } private static void Terminal_Awake(orig_Awake orig, Terminal self) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_006e: 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_0079: Expected O, but got Unknown //IL_0579: Unknown result type (might be due to invalid IL or missing references) //IL_057e: Unknown result type (might be due to invalid IL or missing references) //IL_05b3: Unknown result type (might be due to invalid IL or missing references) //IL_05bc: Expected O, but got Unknown //IL_05be: Unknown result type (might be due to invalid IL or missing references) //IL_05c3: Unknown result type (might be due to invalid IL or missing references) //IL_05f8: Unknown result type (might be due to invalid IL or missing references) //IL_0600: Expected O, but got Unknown //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_0668: Unknown result type (might be due to invalid IL or missing references) //IL_0670: Unknown result type (might be due to invalid IL or missing references) //IL_067d: Expected O, but got Unknown //IL_070a: Unknown result type (might be due to invalid IL or missing references) //IL_070f: Unknown result type (might be due to invalid IL or missing references) //IL_0717: Unknown result type (might be due to invalid IL or missing references) //IL_0724: Expected O, but got Unknown StartOfRound instance = StartOfRound.Instance; RegisterLethalLibScrapItemsForAllLevels(); if (Chainloader.PluginInfos.ContainsKey("imabatby.lethallevelloader") || Chainloader.PluginInfos.ContainsKey("iambatby.lethallevelloader")) { object obj = <>O.<3>__RegisterLevelScrapforLLL_RoundManager_Start; if (obj == null) { hook_Start val = RegisterLevelScrapforLLL_RoundManager_Start; <>O.<3>__RegisterLevelScrapforLLL_RoundManager_Start = val; obj = (object)val; } RoundManager.Start += (hook_Start)obj; } if (Chainloader.PluginInfos.ContainsKey("LethalExpansion")) { object obj2 = <>O.<4>__RegisterLevelScrapforLE_Terminal_Start; if (obj2 == null) { hook_Start val2 = RegisterLevelScrapforLE_Terminal_Start; <>O.<4>__RegisterLevelScrapforLE_Terminal_Start = val2; obj2 = (object)val2; } Terminal.Start += (hook_Start)obj2; } RegisterScrapAsItem(instance); foreach (ShopItem shopItem in shopItems) { if (instance.allItemsList.itemsList.Contains(shopItem.item)) { continue; } if (Plugin.extendedLogging.Value) { if (shopItem.modName != "LethalLib") { Plugin.logger.LogInfo((object)(shopItem.modName + " registered shop item: " + shopItem.item.itemName)); } else { Plugin.logger.LogInfo((object)("Registered shop item: " + shopItem.item.itemName)); } } LethalLibItemList.Add(shopItem.item); instance.allItemsList.itemsList.Add(shopItem.item); } foreach (PlainItem plainItem in plainItems) { if (instance.allItemsList.itemsList.Contains(plainItem.item)) { continue; } if (Plugin.extendedLogging.Value) { if (plainItem.modName != "LethalLib") { Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName)); } else { Plugin.logger.LogInfo((object)("Registered item: " + plainItem.item.itemName)); } } LethalLibItemList.Add(plainItem.item); instance.allItemsList.itemsList.Add(plainItem.item); } terminal = self; List<Item> list = self.buyableItemsList.ToList(); TerminalKeyword val3 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val3.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val4 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); Plugin.logger.LogInfo((object)$"Adding {shopItems.Count} items to terminal"); foreach (ShopItem item in shopItems) { if (list.Any((Item x) => x.itemName == item.item.itemName) && !item.wasRemoved) { Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping")); continue; } item.wasRemoved = false; if (item.price == -1) { item.price = item.item.creditsWorth; } else { item.item.creditsWorth = item.price; } int num = -1; if (!list.Any((Item x) => (Object)(object)x == (Object)(object)item.item)) { list.Add(item.item); } else { num = list.IndexOf(item.item); } int buyItemIndex = ((num == -1) ? (list.Count - 1) : num); string itemName = item.item.itemName; _ = itemName[itemName.Length - 1]; string text = itemName; TerminalNode val5 = item.buyNode2; if ((Object)(object)val5 == (Object)null) { val5 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val5).name = itemName.Replace(" ", "-") + "BuyNode2"; val5.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n"; val5.clearPreviousText = true; val5.maxCharactersToType = 15; } val5.buyItemIndex = buyItemIndex; val5.isConfirmationNode = false; val5.itemCost = item.price; val5.playSyncedClip = 0; TerminalNode val6 = item.buyNode1; if ((Object)(object)val6 == (Object)null) { val6 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val6).name = itemName.Replace(" ", "-") + "BuyNode1"; val6.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val6.clearPreviousText = true; val6.maxCharactersToType = 35; } val6.buyItemIndex = buyItemIndex; val6.isConfirmationNode = true; val6.overrideOptions = true; val6.itemCost = item.price; val6.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val5 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; TerminalKeyword val7 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val3); List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(val7); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val3.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = val7, result = val6 }); val3.compatibleNouns = list3.ToArray(); TerminalNode val8 = item.itemInfo; if ((Object)(object)val8 == (Object)null) { val8 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val8).name = itemName.Replace(" ", "-") + "InfoNode"; val8.displayText = "[No information about this object was found.]\n\n"; val8.clearPreviousText = true; val8.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val4.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = val7, result = val8 }); val4.compatibleNouns = list4.ToArray(); BuyableItemAssetInfo buyableItemAssetInfo = default(BuyableItemAssetInfo); buyableItemAssetInfo.itemAsset = item.item; buyableItemAssetInfo.keyword = val7; BuyableItemAssetInfo item2 = buyableItemAssetInfo; buyableItemAssetInfos.Add(item2); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)$"Added {itemName} to terminal (Item price: {val6.itemCost}, Item Index: {val6.buyItemIndex}, Terminal keyword: {val7.word})"); } } self.buyableItemsList = list.ToArray(); orig.Invoke(self); } public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags) { Item spawnableItem2 = spawnableItem; ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2); if (scrapItem != null) { if (levelFlags != Levels.LevelTypes.None) { scrapItem.levelRarities.Add(levelFlags, rarity); } } else { scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags); string name = Assembly.GetCallingAssembly().GetName().Name; scrapItem.modName = name; scrapItems.Add(scrapItem); } } public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { Item spawnableItem2 = spawnableItem; ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2); if (scrapItem != null) { if (levelFlags != Levels.LevelTypes.None) { scrapItem.levelRarities.Add(levelFlags, rarity); } if (levelOverrides != null) { foreach (string levelName in levelOverrides) { scrapItem.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(levelName), rarity); } } } else { scrapItem = new ScrapItem(spawnableItem2, rarity, levelFlags, levelOverrides); string name = Assembly.GetCallingAssembly().GetName().Name; scrapItem.modName = name; scrapItems.Add(scrapItem); } } public static void RegisterScrap(Item spawnableItem, Dictionary<Levels.LevelTypes, int>? levelRarities = null, Dictionary<string, int>? customLevelRarities = null) { Item spawnableItem2 = spawnableItem; ScrapItem scrapItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)spawnableItem2 || (Object)(object)x.item == (Object)(object)spawnableItem2); if (scrapItem != null) { if (levelRarities != null) { foreach (KeyValuePair<Levels.LevelTypes, int> levelRarity in levelRarities) { scrapItem.levelRarities.Add(levelRarity.Key, levelRarity.Value); } } if (customLevelRarities == null) { return; } { foreach (KeyValuePair<string, int> customLevelRarity in customLevelRarities) { scrapItem.customLevelRarities.Add(Levels.Compatibility.GetLLLNameOfLevel(customLevelRarity.Key), customLevelRarity.Value); } return; } } scrapItem = new ScrapItem(spawnableItem2, levelRarities, customLevelRarities); string name = Assembly.GetCallingAssembly().GetName().Name; scrapItem.modName = name; scrapItems.Add(scrapItem); } public static void RegisterShopItem(Item shopItem, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { ShopItem shopItem2 = new ShopItem(shopItem, buyNode1, buyNode2, itemInfo, price); string name = Assembly.GetCallingAssembly().GetName().Name; shopItem2.modName = name; shopItems.Add(shopItem2); } public static void RegisterShopItem(Item shopItem, int price = -1) { ShopItem shopItem2 = new ShopItem(shopItem, null, null, null, price); string name = Assembly.GetCallingAssembly().GetName().Name; shopItem2.modName = name; shopItems.Add(shopItem2); } public static void RegisterItem(Item plainItem) { PlainItem plainItem2 = new PlainItem(plainItem); string name = Assembly.GetCallingAssembly().GetName().Name; plainItem2.modName = name; plainItems.Add(plainItem2); } public static void RemoveScrapFromLevels(Item scrapItem, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { Item scrapItem2 = scrapItem; if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; if (!Enum.IsDefined(typeof(Levels.LevelTypes), name)) { name = Levels.Compatibility.GetLLLNameOfLevel(name); } bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => Levels.Compatibility.GetLLLNameOfLevel(item).ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name)) { flag = true; } if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (!flag && !levelFlags.HasFlag(levelTypes)) { continue; } ScrapItem actualItem = scrapItems.FirstOrDefault((ScrapItem x) => (Object)(object)x.origItem == (Object)(object)scrapItem2 || (Object)(object)x.item == (Object)(object)scrapItem2); SpawnableItemWithRarity val2 = ((IEnumerable<SpawnableItemWithRarity>)val.spawnableScrap).FirstOrDefault((Func<SpawnableItemWithRarity, bool>)((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)actualItem.item)); if (val2 != null) { if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)("Removed Item " + ((Object)val2.spawnableItem).name + " from Level " + name)); } val.spawnableScrap.Remove(val2); } } } public static void RemoveShopItem(Item shopItem) { Item shopItem2 = shopItem; if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2); actualItem.wasRemoved = true; List<TerminalKeyword> list = terminal.terminalNodes.allKeywords.ToList(); TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); List<CompatibleNoun> list2 = val.compatibleNouns.ToList(); List<CompatibleNoun> list3 = obj.compatibleNouns.ToList(); if (buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item)) { BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item); list.Remove(asset.keyword); list2.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword); list3.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword); } terminal.terminalNodes.allKeywords = list.ToArray(); val.compatibleNouns = list2.ToArray(); obj.compatibleNouns = list3.ToArray(); } public static void UpdateShopItemPrice(Item shopItem, int price) { Item shopItem2 = shopItem; if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } ShopItem actualItem = shopItems.FirstOrDefault((ShopItem x) => (Object)(object)x.origItem == (Object)(object)shopItem2 || (Object)(object)x.item == (Object)(object)shopItem2); actualItem.item.creditsWorth = price; TerminalKeyword obj = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); _ = obj.compatibleNouns[0].result.terminalOptions[1].result; List<CompatibleNoun> source = obj.compatibleNouns.ToList(); if (!buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item)) { return; } BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)actualItem.item); if (!source.Any((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword)) { return; } TerminalNode result = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword).result; result.itemCost = price; if (result.terminalOptions.Length == 0) { return; } CompatibleNoun[] terminalOptions = result.terminalOptions; foreach (CompatibleNoun val in terminalOptions) { if ((Object)(object)val.result != (Object)null && val.result.buyItemIndex != -1) { val.result.itemCost = price; } } } } public class Levels { [Flags] public enum LevelTypes { None = 1, ExperimentationLevel = 4, AssuranceLevel = 8, VowLevel = 0x10, OffenseLevel = 0x20, MarchLevel = 0x40, RendLevel = 0x80, DineLevel = 0x100, TitanLevel = 0x200, AdamanceLevel = 0x800, ArtificeLevel = 0x1000, EmbrionLevel = 0x2000, Vanilla = 0x3BFC, Modded = 0x400, All = -1 } internal static class Compatibility { private const string illegalCharacters = ".,?!@#$%^&*()_+-=';:'\""; private static string GetNumberlessPlanetName(string planetName) { if (planetName != null) { return new string(planetName.SkipWhile((char c) => !char.IsLetter(c)).ToArray()); } return string.Empty; } private static string StripSpecialCharacters(string input) { string text = string.Empty; for (int i = 0; i < input.Length; i++) { char c = input[i]; if ((!".,?!@#$%^&*()_+-=';:'\"".ToCharArray().Contains(c) && char.IsLetterOrDigit(c)) || c.ToString() == " ") { text += c; } } return text; } internal static string GetLLLNameOfLevel(string levelName) { string text = StripSpecialCharacters(GetNumberlessPlanetName(levelName)); if (!text.EndsWith("Level", ignoreCase: true, CultureInfo.InvariantCulture)) { text += "Level"; } return text.ToLowerInvariant(); } internal static Dictionary<string, int> LLLifyLevelRarityDictionary(Dictionary<string, int> keyValuePairs) { Dictionary<string, int> dictionary = new Dictionary<string, int>(); List<string> list = keyValuePairs.Keys.ToList(); List<int> list2 = keyValuePairs.Values.ToList(); for (int i = 0; i < keyValuePairs.Count; i++) { dictionary.Add(GetLLLNameOfLevel(list[i]), list2[i]); } return dictionary; } } } public class MapObjects { public class RegisteredMapObject { public SpawnableMapObject mapObject; public SpawnableOutsideObjectWithRarity outsideObject; public Levels.LevelTypes levels; public string[] spawnLevelOverrides; public Func<SelectableLevel, AnimationCurve> spawnRateFunction; } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_SpawnMapObjects <1>__RoundManager_SpawnMapObjects; } public static List<RegisteredMapObject> mapObjects = new List<RegisteredMapObject>(); public static void Init() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //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_003b: Expected O, but got Unknown object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__RoundManager_SpawnMapObjects; if (obj2 == null) { hook_SpawnMapObjects val2 = RoundManager_SpawnMapObjects; <>O.<1>__RoundManager_SpawnMapObjects = val2; obj2 = (object)val2; } RoundManager.SpawnMapObjects += (hook_SpawnMapObjects)obj2; } private static void RoundManager_SpawnMapObjects(orig_SpawnMapObjects orig, RoundManager self) { RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>(); foreach (RandomMapObject val in array) { foreach (RegisteredMapObject mapObject in mapObjects) { if (mapObject.mapObject != null && !val.spawnablePrefabs.Any((GameObject prefab) => (Object)(object)prefab == (Object)(object)mapObject.mapObject.prefabToSpawn)) { val.spawnablePrefabs.Add(mapObject.mapObject.prefabToSpawn); } } } orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Expected O, but got Unknown //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) //IL_039b: Expected O, but got Unknown orig.Invoke(self); foreach (RegisteredMapObject mapObject in mapObjects) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = mapObject.levels.HasFlag(Levels.LevelTypes.All) || (mapObject.spawnLevelOverrides != null && mapObject.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (mapObject.levels.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name)) { flag = true; } if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (!flag && !mapObject.levels.HasFlag(levelTypes)) { continue; } if (mapObject.mapObject != null) { if (val.spawnableMapObjects.Any((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn)) { List<SpawnableMapObject> list = val.spawnableMapObjects.ToList(); list.RemoveAll((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn); val.spawnableMapObjects = list.ToArray(); } SpawnableMapObject val2 = new SpawnableMapObject { prefabToSpawn = mapObject.mapObject.prefabToSpawn, spawnFacingAwayFromWall = mapObject.mapObject.spawnFacingAwayFromWall, spawnFacingWall = mapObject.mapObject.spawnFacingWall, spawnWithBackToWall = mapObject.mapObject.spawnWithBackToWall, spawnWithBackFlushAgainstWall = mapObject.mapObject.spawnWithBackFlushAgainstWall, requireDistanceBetweenSpawns = mapObject.mapObject.requireDistanceBetweenSpawns, disallowSpawningNearEntrances = mapObject.mapObject.disallowSpawningNearEntrances }; if (mapObject.spawnRateFunction != null) { val2.numberToSpawn = mapObject.spawnRateFunction(val); } List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList(); list2.Add(val2); val.spawnableMapObjects = list2.ToArray(); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)("Added " + ((Object)val2.prefabToSpawn).name + " to " + name)); } } else { if (mapObject.outsideObject == null) { continue; } if (val.spawnableOutsideObjects.Any((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn)) { List<SpawnableOutsideObjectWithRarity> list3 = val.spawnableOutsideObjects.ToList(); list3.RemoveAll((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn); val.spawnableOutsideObjects = list3.ToArray(); } SpawnableOutsideObjectWithRarity val3 = new SpawnableOutsideObjectWithRarity { spawnableObject = mapObject.outsideObject.spawnableObject }; if (mapObject.spawnRateFunction != null) { val3.randomAmount = mapObject.spawnRateFunction(val); } List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList(); list4.Add(val3); val.spawnableOutsideObjects = list4.ToArray(); if (Plugin.extendedLogging.Value) { Plugin.logger.LogInfo((object)("Added " + ((Object)val3.spawnableObject.prefabToSpawn).name + " to " + name)); } } } } } public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterMapObject(mapObject.spawnableMapObject, levels, spawnRateFunction); } public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterMapObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction); } public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { mapObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction }); } public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { mapObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction, spawnLevelOverrides = levelOverrides }); } public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterOutsideObject(mapObject.spawnableMapObject, levels, spawnRateFunction); } public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterOutsideObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction); } public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { outsideObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction }); } public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { outsideObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction, spawnLevelOverrides = levelOverrides }); } public static void RemoveMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null) { RemoveMapObject(mapObject.spawnableMapObject, levelFlags, levelOverrides); } public static void RemoveMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null) { SpawnableMapObject mapObject2 = mapObject; if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name)) { flag = true; } if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || levelFlags.HasFlag(levelTypes)) { val.spawnableMapObjects = val.spawnableMapObjects.Where((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn != (Object)(object)mapObject2.prefabToSpawn).ToArray(); } } } public static void RemoveOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null) { RemoveOutsideObject(mapObject.spawnableMapObject, levelFlags, levelOverrides); } public static void RemoveOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null) { SpawnableOutsideObjectWithRarity mapObject2 = mapObject; if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (levelFlags.HasFlag(Levels.LevelTypes.Modded) && !Enum.IsDefined(typeof(Levels.LevelTypes), name)) { flag = true; } if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || levelFlags.HasFlag(levelTypes)) { val.spawnableOutsideObjects = val.spawnableOutsideObjects.Where((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn != (Object)(object)mapObject2.spawnableObject.prefabToSpawn).ToArray(); } } } } public class NetworkPrefabs { [CompilerGenerated] private static class <>O { public static hook_Start <0>__GameNetworkManager_Start; } private static List<GameObject> _networkPrefabs = new List<GameObject>(); internal static void Init() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown object obj = <>O.<0>__GameNetworkManager_Start; if (obj == null) { hook_Start val = GameNetworkManager_Start; <>O.<0>__GameNetworkManager_Start = val; obj = (object)val; } GameNetworkManager.Start += (hook_Start)obj; } public static void RegisterNetworkPrefab(GameObject prefab) { if (prefab == null) { throw new ArgumentNullException("prefab", "The given argument for RegisterNetworkPrefab is null!"); } if (!_networkPrefabs.Contains(prefab)) { _networkPrefabs.Add(prefab); } } public static GameObject CreateNetworkPrefab(string name) { GameObject obj = PrefabUtils.CreatePrefab(name); obj.AddComponent<NetworkObject>(); byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + name)); obj.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0); RegisterNetworkPrefab(obj); return obj; } public static GameObject CloneNetworkPrefab(GameObject prefabToClone, string newName = null) { GameObject val = PrefabUtils.ClonePrefab(prefabToClone, newName); byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetCallingAssembly().GetName().Name + ((Object)val).name)); val.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0); RegisterNetworkPrefab(val); return val; } private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self) { orig.Invoke(self); foreach (GameObject networkPrefab in _networkPrefabs) { if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Contains(networkPrefab)) { NetworkManager.Singleton.AddNetworkPrefab(networkPrefab); } } } } public class Player { [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; } public static Dictionary<string, GameObject> ragdollRefs = new Dictionary<string, GameObject>(); public static Dictionary<string, int> ragdollIndexes = new Dictionary<string, int>(); public static void Init() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { orig.Invoke(self); foreach (KeyValuePair<string,
plugins/MaxwellScrap.dll
Decompiled 5 hours agousing System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using HarmonyLib; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("LaserTweaks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LaserTweaks")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4963e0ea-7a99-4390-9cae-a4bdd01b6b43")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } } namespace MaxwellScrap { public class Assets { public static AssetBundle MainAssetBundle; public static Item Item; internal static Stream GetEmbededResource(string name) { return Assembly.GetExecutingAssembly().GetManifestResourceStream("MaxwellScrap." + name); } public static void Init() { MainAssetBundle = AssetBundle.LoadFromStream(GetEmbededResource("maxwell.bundle")); Item = MainAssetBundle.LoadAsset<Item>("Assets/Mods/MaxwellScrapItem/Maxwell.asset"); } } [BepInPlugin("Kittenji.MaxwellScrap", "Maxwell Scrap", "1.0.1")] public class Loader : BaseUnityPlugin { [HarmonyPatch(typeof(GameNetworkManager))] internal class GameNetworkManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch() { ((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(Assets.Item.spawnPrefab); Debug.Log((object)"[MAXWELL] Added network prefab"); } } [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void AwakePatch(ref StartOfRound __instance) { //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown SelectableLevel[] levels = __instance.levels; foreach (SelectableLevel val in levels) { if (val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)Assets.Item)) { continue; } int num = 2; SpawnableItemWithRarity val2 = val.spawnableScrap.Find((SpawnableItemWithRarity s) => Object.op_Implicit((Object)(object)s.spawnableItem) && Object.op_Implicit((Object)(object)s.spawnableItem.spawnPrefab) && ((Object)s.spawnableItem.spawnPrefab).name == "CashRegisterItem"); if (val2 != null) { num = val2.rarity; } else if (val.spawnableScrap.Count > 0) { int num2 = int.MaxValue; foreach (SpawnableItemWithRarity item2 in val.spawnableScrap) { if (item2.rarity < num2) { num2 = item2.rarity; } } num = num2; } num = Mathf.Min(100, Mathf.Max(1, num)); SpawnableItemWithRarity item = new SpawnableItemWithRarity { spawnableItem = Assets.Item, rarity = num }; val.spawnableScrap.Add(item); } if (!__instance.allItemsList.itemsList.Contains(Assets.Item)) { __instance.allItemsList.itemsList.Add(Assets.Item); } } } private const string modGUID = "Kittenji.MaxwellScrap"; private readonly Harmony harmony = new Harmony("Kittenji.MaxwellScrap"); private const int DefaultSpawnRarity = 2; private void Awake() { Assets.Init(); harmony.PatchAll(); } } }
plugins/MonsterPlushies.dll
Decompiled 5 hours agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using CSync.Lib; using CSync.Util; using LethalLib.Modules; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("MonsterPlushies")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("MonsterPlushies")] [assembly: AssemblyTitle("MonsterPlushies")] [assembly: AssemblyVersion("1.0.0.0")] [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 MonsterPlushies { [DataContract] public class MyConfig : SyncedConfig<MyConfig> { [DataMember] public SyncedEntry<int> BrackenSpawnWeight; [DataMember] public SyncedEntry<bool> BrackenSpawnAllMoons; [DataMember] public SyncedEntry<string> BrackenSpawnMoonsList; public MyConfig(ConfigFile cfg) : base("scin.monsterplushies") { ConfigManager.Register<MyConfig>(this); BrackenSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Bracken Spawn Settings", "Bracken Plushie Spawn Weight", 20, "The chance for a Bracken Plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); BrackenSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Bracken Spawn Settings", "Bracken Plushie Spawn All Moons", true, "If true the Bracken plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); BrackenSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Bracken Spawn Settings", "Bracken Plushie Moon spawn List", "Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class CoilConfig : SyncedConfig<CoilConfig> { [DataMember] public SyncedEntry<int> CoilSpawnWeight; [DataMember] public SyncedEntry<bool> CoilSpawnAllMoons; [DataMember] public SyncedEntry<string> CoilSpawnMoonsList; public CoilConfig(ConfigFile cfg) : base("scin.monsterplushies") { CoilSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Coil Head Spawn Settings", "Coil Head Plushie Spawn Weight", 20, "The chance for a Coil Head Plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); CoilSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Coil Head Spawn Settings", "Coil Head Plushie Spawn All Moons", true, "If true the Coil Head plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); CoilSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Coil Head Spawn Settings", "Coil Head Moon spawn List", "Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class ComedyTragedyConfig : SyncedConfig<ComedyTragedyConfig> { [DataMember] public SyncedEntry<int> CTSpawnWeight; [DataMember] public SyncedEntry<bool> CTSpawnAllMoons; [DataMember] public SyncedEntry<string> CTSpawnMoonsList; public ComedyTragedyConfig(ConfigFile cfg) : base("scin.monsterplushies") { CTSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Masked Spawn Settings", "Masked Plushie Spawn Weight", 10, "The chance for a Masked plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); CTSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Masked Spawn Settings", "Masked Plushie Spawn All Moons", false, "If true the Masked plushies will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); CTSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Masked Spawn Settings", "Masked Moon spawn List", "Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class BunkerSpiderConfig : SyncedConfig<BunkerSpiderConfig> { [DataMember] public SyncedEntry<int> BunkSpawnWeight; [DataMember] public SyncedEntry<bool> BunkSpawnAllMoons; [DataMember] public SyncedEntry<string> BunkSpawnMoonsList; public BunkerSpiderConfig(ConfigFile cfg) : base("scin.monsterplushies") { BunkSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Bunker Spider Spawn Settings", "Bunker Spider Plushie Spawn Weight", 25, "The chance for a Bunker Spider plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); BunkSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Bunker Spider Spawn Settings", "Bunker Spider SpawnAll Moons", true, "If true the Bunker Spider plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); BunkSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Bunker Spider Spawn Settings", "Bunker Spider Moon spawn List", "Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class LootbugConfig : SyncedConfig<LootbugConfig> { [DataMember] public SyncedEntry<int> LootSpawnWeight; [DataMember] public SyncedEntry<bool> LootSpawnAllMoons; [DataMember] public SyncedEntry<string> LootSpawnMoonsList; public LootbugConfig(ConfigFile cfg) : base("scin.monsterplushies") { LootSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Hoarding bug Spawn Settings", "Hoarding bug Plushie Spawn Weight", 25, "The chance for a Hoarding bug plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); LootSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Hoarding bug Spawn Settings", "Hoarding bug SpawnAll Moons", true, "If true the Hoarding bug plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); LootSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Hoarding bug Spawn Settings", "Hoarding bug Moon spawn List", "Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class JeConfig : SyncedConfig<JeConfig> { [DataMember] public SyncedEntry<int> JestSpawnWeight; [DataMember] public SyncedEntry<bool> JestSpawnAllMoons; [DataMember] public SyncedEntry<string> JestSpawnMoonsList; public JeConfig(ConfigFile cfg) : base("scin.monsterplushies") { JestSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Jester Spawn Settings", "Jester Plushie Spawn Weight", 5, "The chance for a Jester plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); JestSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Jester Spawn Settings", "Jester SpawnAll Moons", false, "If true the Jester plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); JestSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Jester Spawn Settings", "Jester Moon spawn List", "Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class GiantConfig : SyncedConfig<GiantConfig> { [DataMember] public SyncedEntry<int> GiantSpawnWeight; [DataMember] public SyncedEntry<bool> GiantSpawnAllMoons; [DataMember] public SyncedEntry<string> GiantSpawnMoonsList; public GiantConfig(ConfigFile cfg) : base("scin.monsterplushies") { GiantSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Forest Keeper Spawn Settings", "Forest Keeper Plushie Spawn Weight", 15, "The chance for a Forest Keeper plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); GiantSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Forest Keeper Spawn Settings", "Forest Keeper SpawnAll Moons", true, "If true the Forest Keeper plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); GiantSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Forest Keeper Spawn Settings", "Forest Keeper Moon spawn List", "Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class nutConfig : SyncedConfig<nutConfig> { [DataMember] public SyncedEntry<int> NutSpawnWeight; [DataMember] public SyncedEntry<bool> NutSpawnAllMoons; [DataMember] public SyncedEntry<string> NutSpawnMoonsList; public nutConfig(ConfigFile cfg) : base("scin.monsterplushies") { NutSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Nutcracker Spawn Settings", "Nutcracker Plushie Spawn Weight", 10, "The chance for a Nutcracker plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); NutSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Nutcracker Spawn Settings", "Nutcracker SpawnAll Moons", false, "If true the Nutcracker plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); NutSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Nutcracker Spawn Settings", "Nutcracker Moon spawn List", "Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class eyeConfig : SyncedConfig<eyeConfig> { [DataMember] public SyncedEntry<int> DogSpawnWeight; [DataMember] public SyncedEntry<bool> DogSpawnAllMoons; [DataMember] public SyncedEntry<string> DogSpawnMoonsList; public eyeConfig(ConfigFile cfg) : base("scin.monsterplushies") { DogSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Eyeless Dog Spawn Settings", "Eyeless Dog Plushie Spawn Weight", 15, "The chance for an Eyeless Dog plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); DogSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Eyeless Dog Spawn Settings", "Eyeless Dog SpawnAll Moons", true, "If true the Eyeless Dog plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); DogSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Eyeless Dog Spawn Settings", "Eyeless Dog Moon spawn List", "Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [DataContract] public class ThumperConfig : SyncedConfig<ThumperConfig> { [DataMember] public SyncedEntry<int> ThumpSpawnWeight; [DataMember] public SyncedEntry<bool> ThumpSpawnAllMoons; [DataMember] public SyncedEntry<string> ThumpSpawnMoonsList; public ThumperConfig(ConfigFile cfg) : base("scin.monsterplushies") { ThumpSpawnWeight = Extensions.BindSyncedEntry<int>(cfg, "Thumper Spawn Settings", "Thumper Plushie Spawn Weight", 15, "The chance for a Thumper plushie to spawn, Usually between 1-100. Just dont set it super high unless you want to see this thing EVERYWHERE"); ThumpSpawnAllMoons = Extensions.BindSyncedEntry<bool>(cfg, "Thumper Spawn Settings", "Thumper SpawnAll Moons", true, "If true the Thumper plushie will spawn on all the moons, if false then it will only spawn on the moons set in the moons list"); ThumpSpawnMoonsList = Extensions.BindSyncedEntry<string>(cfg, "Thumper Spawn Settings", "Thumper Moon spawn List", "Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan", "List of moons for the plushie to spawn on (Experimentation, Assurance, Vow, Offense, March, Rend, Dine, Titan). Only works if Spawn all moons is off"); } } [BepInPlugin("scin.monsterplushies", "Monster Plushies", "1.2.9")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class MonsterPlushies : BaseUnityPlugin { private const string GUID = "scin.monsterplushies"; private const string NAME = "Monster Plushies"; private const string VERSION = "1.2.9"; public static MonsterPlushies? instance; private MyConfig config; private CoilConfig cconfig; private ComedyTragedyConfig ctconfig; private BunkerSpiderConfig bsConfig; private LootbugConfig lConfig; private JeConfig JConfig; private GiantConfig GConfig; private nutConfig nutcrackConfig; private eyeConfig dogConfig; private ThumperConfig thumpConfig; private void Awake() { config = new MyConfig(((BaseUnityPlugin)this).Config); cconfig = new CoilConfig(((BaseUnityPlugin)this).Config); ctconfig = new ComedyTragedyConfig(((BaseUnityPlugin)this).Config); bsConfig = new BunkerSpiderConfig(((BaseUnityPlugin)this).Config); lConfig = new LootbugConfig(((BaseUnityPlugin)this).Config); JConfig = new JeConfig(((BaseUnityPlugin)this).Config); GConfig = new GiantConfig(((BaseUnityPlugin)this).Config); nutcrackConfig = new nutConfig(((BaseUnityPlugin)this).Config); dogConfig = new eyeConfig(((BaseUnityPlugin)this).Config); thumpConfig = new ThumperConfig(((BaseUnityPlugin)this).Config); instance = this; string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "monsterplushies"); AssetBundle val = AssetBundle.LoadFromFile(text); Item val2 = val.LoadAsset<Item>("Assets/MY STUFF/Bracken Plush/BrackenPlush.asset"); Item val3 = val.LoadAsset<Item>("Assets/MY STUFF/Coil head/CoilHeadPlush.asset"); Item val4 = val.LoadAsset<Item>("Assets/MY STUFF/Masked/comedyplushitem.asset"); Item val5 = val.LoadAsset<Item>("Assets/MY STUFF/Masked/Tragedyplushitem.asset"); Item val6 = val.LoadAsset<Item>("Assets/MY STUFF/Bunkspid/BunkspidItem.asset"); Item val7 = val.LoadAsset<Item>("Assets/MY STUFF/Lootbug/lootbugPlush.asset"); Item val8 = val.LoadAsset<Item>("Assets/MY STUFF/Jester/jesterplushie.asset"); Item val9 = val.LoadAsset<Item>("Assets/MY STUFF/Giant/Forest keeper plushie.asset"); Item val10 = val.LoadAsset<Item>("Assets/MY STUFF/Nutcracker/Nutcracker.asset"); Item val11 = val.LoadAsset<Item>("Assets/MY STUFF/Eyeless dog/EyelessDog.asset"); Item val12 = val.LoadAsset<Item>("Assets/MY STUFF/Thumper/Thumper.asset"); NetworkPrefabs.RegisterNetworkPrefab(val2.spawnPrefab); Utilities.FixMixerGroups(val2.spawnPrefab); if (config.BrackenSpawnAllMoons.Value) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)(-1)); } else { if (config.BrackenSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)4); } if (config.BrackenSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)8); } if (config.BrackenSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)16); } if (config.BrackenSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)32); } if (config.BrackenSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)64); } if (config.BrackenSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)128); } if (config.BrackenSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)256); } if (config.BrackenSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val2, config.BrackenSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val3.spawnPrefab); Utilities.FixMixerGroups(val3.spawnPrefab); if (cconfig.CoilSpawnAllMoons.Value) { Items.RegisterScrap(val3, cconfig.CoilSpawnWeight.Value, (LevelTypes)(-1)); } else { if (cconfig.CoilSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val3, cconfig.CoilSpawnWeight.Value, (LevelTypes)4); } if (cconfig.CoilSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val3, cconfig.CoilSpawnWeight.Value, (LevelTypes)8); } if (cconfig.CoilSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val3, cconfig.CoilSpawnWeight.Value, (LevelTypes)16); } if (cconfig.CoilSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val3, cconfig.CoilSpawnWeight.Value, (LevelTypes)32); } if (cconfig.CoilSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val3, cconfig.CoilSpawnWeight.Value, (LevelTypes)64); } if (cconfig.CoilSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val3, cconfig.CoilSpawnWeight.Value, (LevelTypes)128); } if (cconfig.CoilSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val3, cconfig.CoilSpawnWeight.Value, (LevelTypes)256); } if (cconfig.CoilSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val3, config.BrackenSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val4.spawnPrefab); Utilities.FixMixerGroups(val4.spawnPrefab); if (ctconfig.CTSpawnAllMoons.Value) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)(-1)); } else { if (ctconfig.CTSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)4); } if (ctconfig.CTSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)8); } if (ctconfig.CTSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)16); } if (ctconfig.CTSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)32); } if (ctconfig.CTSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)64); } if (ctconfig.CTSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)128); } if (ctconfig.CTSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)256); } if (ctconfig.CTSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val4, ctconfig.CTSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val5.spawnPrefab); Utilities.FixMixerGroups(val5.spawnPrefab); if (ctconfig.CTSpawnAllMoons.Value) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)(-1)); } else { if (ctconfig.CTSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)4); } if (ctconfig.CTSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)8); } if (ctconfig.CTSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)16); } if (ctconfig.CTSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)32); } if (ctconfig.CTSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)64); } if (ctconfig.CTSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)128); } if (ctconfig.CTSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)256); } if (ctconfig.CTSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val5, ctconfig.CTSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val6.spawnPrefab); Utilities.FixMixerGroups(val6.spawnPrefab); if (bsConfig.BunkSpawnAllMoons.Value) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)(-1)); } else { if (bsConfig.BunkSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)4); } if (bsConfig.BunkSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)8); } if (bsConfig.BunkSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)16); } if (bsConfig.BunkSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)32); } if (bsConfig.BunkSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)64); } if (bsConfig.BunkSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)128); } if (bsConfig.BunkSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)256); } if (bsConfig.BunkSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val6, bsConfig.BunkSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val7.spawnPrefab); Utilities.FixMixerGroups(val7.spawnPrefab); if (lConfig.LootSpawnAllMoons.Value) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)(-1)); } else { if (lConfig.LootSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)4); } if (lConfig.LootSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)8); } if (lConfig.LootSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)16); } if (lConfig.LootSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)32); } if (lConfig.LootSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)64); } if (lConfig.LootSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)128); } if (lConfig.LootSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)256); } if (lConfig.LootSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val7, lConfig.LootSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val8.spawnPrefab); Utilities.FixMixerGroups(val8.spawnPrefab); if (JConfig.JestSpawnAllMoons.Value) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)(-1)); } else { if (JConfig.JestSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)4); } if (JConfig.JestSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)8); } if (JConfig.JestSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)16); } if (JConfig.JestSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)32); } if (JConfig.JestSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)64); } if (JConfig.JestSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)128); } if (JConfig.JestSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)256); } if (JConfig.JestSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val8, JConfig.JestSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val9.spawnPrefab); Utilities.FixMixerGroups(val9.spawnPrefab); if (GConfig.GiantSpawnAllMoons.Value) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)(-1)); } else { if (GConfig.GiantSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)4); } if (GConfig.GiantSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)8); } if (GConfig.GiantSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)16); } if (GConfig.GiantSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)32); } if (GConfig.GiantSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)64); } if (GConfig.GiantSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)128); } if (GConfig.GiantSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)256); } if (GConfig.GiantSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val9, GConfig.GiantSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val10.spawnPrefab); Utilities.FixMixerGroups(val10.spawnPrefab); if (nutcrackConfig.NutSpawnAllMoons.Value) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)(-1)); } else { if (nutcrackConfig.NutSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)4); } if (nutcrackConfig.NutSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)8); } if (nutcrackConfig.NutSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)16); } if (nutcrackConfig.NutSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)32); } if (nutcrackConfig.NutSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)64); } if (nutcrackConfig.NutSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)128); } if (nutcrackConfig.NutSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)256); } if (nutcrackConfig.NutSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val10, nutcrackConfig.NutSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val11.spawnPrefab); Utilities.FixMixerGroups(val11.spawnPrefab); if (dogConfig.DogSpawnAllMoons.Value) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)(-1)); } else { if (dogConfig.DogSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)4); } if (dogConfig.DogSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)8); } if (dogConfig.DogSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)16); } if (dogConfig.DogSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)32); } if (dogConfig.DogSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)64); } if (dogConfig.DogSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)128); } if (dogConfig.DogSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)256); } if (dogConfig.DogSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val11, dogConfig.DogSpawnWeight.Value, (LevelTypes)512); } } NetworkPrefabs.RegisterNetworkPrefab(val12.spawnPrefab); Utilities.FixMixerGroups(val12.spawnPrefab); if (thumpConfig.ThumpSpawnAllMoons.Value) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)(-1)); } else { if (thumpConfig.ThumpSpawnMoonsList.Value.Contains("experiment", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)4); } if (thumpConfig.ThumpSpawnMoonsList.Value.Contains("assurance", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)8); } if (thumpConfig.ThumpSpawnMoonsList.Value.Contains("vow", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)16); } if (thumpConfig.ThumpSpawnMoonsList.Value.Contains("offense", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)32); } if (thumpConfig.ThumpSpawnMoonsList.Value.Contains("march", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)64); } if (thumpConfig.ThumpSpawnMoonsList.Value.Contains("rend", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)128); } if (thumpConfig.ThumpSpawnMoonsList.Value.Contains("dine", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)256); } if (thumpConfig.ThumpSpawnMoonsList.Value.Contains("titan", StringComparison.OrdinalIgnoreCase)) { Items.RegisterScrap(val12, thumpConfig.ThumpSpawnWeight.Value, (LevelTypes)512); } } ((BaseUnityPlugin)this).Logger.LogInfo((object)"Loaded Monster Plushies"); } } }
plugins/MoreCompany.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using MoreCompany.Cosmetics; using MoreCompany.Utils; using Newtonsoft.Json; using Steamworks; using Steamworks.Data; using TMPro; using Unity.Collections; using Unity.Netcode; using Unity.Netcode.Transports.UTP; using UnityEngine; using UnityEngine.Audio; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("MoreCompany")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyCopyright("Copyright © NotNotSwipez 2023")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("MoreCompany")] [assembly: AssemblyTitle("MoreCompany")] [assembly: AssemblyVersion("1.0.0.0")] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace MoreCompany { [HarmonyPatch(typeof(AudioMixer), "SetFloat")] public static class AudioMixerSetFloatPatch { public static bool Prefix(string name, ref float value) { if (name.StartsWith("PlayerVolume")) { string s = name.Replace("PlayerVolume", ""); int num = int.Parse(s); if (!SoundManagerPatch.initialVolumeSet) { MainClass.StaticLogger.LogInfo((object)$"Setting initial volume for {num} to {value}"); return true; } PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[num]; if ((Object)(object)val != (Object)null) { AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource; if (Object.op_Implicit((Object)(object)currentVoiceChatAudioSource)) { currentVoiceChatAudioSource.volume = value / 16f; } } return false; } if (name.StartsWith("PlayerPitch")) { return MainClass.newPlayerCount <= 4; } return true; } } [HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")] public static class SendChatToServerPatch { public static bool Prefix(string chatMessage, int playerId = -1) { if (DebugCommandRegistry.commandEnabled && ((NetworkBehaviour)StartOfRound.Instance).IsHost && chatMessage.StartsWith("/mc")) { string text = chatMessage.Replace("/mc ", ""); DebugCommandRegistry.HandleCommand(text.Split(' ')); return false; } return true; } } [HarmonyPatch] public static class CosmeticSyncPatch { [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__SV_ReceiveCosmetics; public static HandleNamedMessageDelegate <1>__CL_ReceiveCosmetics; public static HandleNamedMessageDelegate <2>__CL_ReceiveAllCosmetics; } public static void UpdateCosmeticsForPlayer(int playerClientId, List<string> splitMessage) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) CosmeticApplication cosmeticApplication = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[playerClientId]).transform.Find("ScavengerModel").Find("metarig")).gameObject.GetComponent<CosmeticApplication>(); if (!Object.op_Implicit((Object)(object)cosmeticApplication)) { cosmeticApplication = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[playerClientId]).transform.Find("ScavengerModel").Find("metarig")).gameObject.AddComponent<CosmeticApplication>(); } cosmeticApplication.parentType = ParentType.Player; cosmeticApplication.ClearCosmetics(); List<string> list = new List<string>(); foreach (string item in splitMessage) { if (cosmeticApplication.ApplyCosmetic(item, startEnabled: false)) { list.Add(item); } } foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics) { Transform transform = ((Component)spawnedCosmetic).transform; transform.localScale *= 0.38f; } cosmeticApplication.UpdateAllCosmeticVisibilities(playerClientId == StartOfRound.Instance.thisClientPlayerId); if (MainClass.playerIdsAndCosmetics.ContainsKey(playerClientId)) { MainClass.playerIdsAndCosmetics[playerClientId] = list; } else { MainClass.playerIdsAndCosmetics.Add(playerClientId, list); } } public static void SV_ReceiveCosmetics(ulong senderId, FastBufferReader messagePayload) { //IL_0019: 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) //IL_0038: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: 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_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer) { return; } ulong num = default(ulong); ((FastBufferReader)(ref messagePayload)).ReadValueSafe<ulong>(ref num, default(ForPrimitives)); string text = default(string); ((FastBufferReader)(ref messagePayload)).ReadValueSafe(ref text, false); bool flag = default(bool); ((FastBufferReader)(ref messagePayload)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); List<string> list = text.Split(',').ToList(); UpdateCosmeticsForPlayer((int)num, list); MainClass.StaticLogger.LogInfo((object)$"Server received {list.Count} cosmetics from {num} | Request All: {flag}"); int num2 = FastBufferWriter.GetWriteSize<ulong>(ref num, default(ForStructs)) + FastBufferWriter.GetWriteSize(text, false); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(num2, (Allocator)2, -1); FastBufferWriter val2 = val; try { ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe(text, false); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("MC_CL_ReceiveCosmetics", val, (NetworkDelivery)((((FastBufferWriter)(ref val)).Capacity > 1300) ? 4 : 2)); } finally { ((IDisposable)(FastBufferWriter)(ref val2)).Dispose(); } if (senderId != 0 && flag) { string text2 = JsonConvert.SerializeObject((object)MainClass.playerIdsAndCosmetics); int writeSize = FastBufferWriter.GetWriteSize(text2, false); FastBufferWriter val3 = default(FastBufferWriter); ((FastBufferWriter)(ref val3))..ctor(writeSize, (Allocator)2, -1); FastBufferWriter val4 = val3; try { ((FastBufferWriter)(ref val3)).WriteValueSafe(text2, false); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("MC_CL_ReceiveAllCosmetics", senderId, val3, (NetworkDelivery)((((FastBufferWriter)(ref val3)).Capacity > 1300) ? 4 : 2)); } finally { ((IDisposable)(FastBufferWriter)(ref val4)).Dispose(); } } } public static void CL_ReceiveAllCosmetics(ulong senderId, FastBufferReader messagePayload) { string text = default(string); ((FastBufferReader)(ref messagePayload)).ReadValueSafe(ref text, false); Dictionary<int, List<string>> dictionary = JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(text); foreach (KeyValuePair<int, List<string>> item in dictionary) { UpdateCosmeticsForPlayer(item.Key, item.Value); } MainClass.StaticLogger.LogInfo((object)$"Client received {dictionary.Sum((KeyValuePair<int, List<string>> x) => x.Value.Count)} cosmetics from {dictionary.Keys.Count} players"); } public static void CL_ReceiveCosmetics(ulong senderId, FastBufferReader messagePayload) { //IL_0019: 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) if (!NetworkManager.Singleton.IsServer) { ulong num = default(ulong); ((FastBufferReader)(ref messagePayload)).ReadValueSafe<ulong>(ref num, default(ForPrimitives)); string text = default(string); ((FastBufferReader)(ref messagePayload)).ReadValueSafe(ref text, false); List<string> list = text.Split(',').ToList(); UpdateCosmeticsForPlayer((int)num, list); MainClass.StaticLogger.LogInfo((object)$"Client received {list.Count} cosmetics from {num}"); } } public static void SyncCosmeticsToOtherClients(PlayerControllerB playerControllerTmp = null, bool disabled = false, bool requestAll = false) { //IL_0048: 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_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007e: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00af: 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) PlayerControllerB val = playerControllerTmp ?? StartOfRound.Instance?.localPlayerController; if ((Object)(object)val != (Object)null) { List<string> cosmeticsToSync = CosmeticRegistry.GetCosmeticsToSync(); string text = (disabled ? "" : string.Join(',', cosmeticsToSync)); int num = FastBufferWriter.GetWriteSize<ulong>(ref val.playerClientId, default(ForStructs)) + FastBufferWriter.GetWriteSize(text, false) + FastBufferWriter.GetWriteSize<bool>(ref requestAll, default(ForStructs)); FastBufferWriter val2 = default(FastBufferWriter); ((FastBufferWriter)(ref val2))..ctor(num, (Allocator)2, -1); FastBufferWriter val3 = val2; try { ((FastBufferWriter)(ref val2)).WriteValueSafe<ulong>(ref val.playerClientId, default(ForPrimitives)); ((FastBufferWriter)(ref val2)).WriteValueSafe(text, false); ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref requestAll, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("MC_SV_SyncCosmetics", 0uL, val2, (NetworkDelivery)((((FastBufferWriter)(ref val2)).Capacity > 1300) ? 4 : 2)); } finally { ((IDisposable)(FastBufferWriter)(ref val3)).Dispose(); } MainClass.StaticLogger.LogInfo((object)$"Sending {cosmeticsToSync.Count} cosmetics to the server | Request All: {requestAll}"); } } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void ConnectClientToPlayerObject(PlayerControllerB __instance) { //IL_006e: 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_0079: Expected O, but got Unknown //IL_003a: 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_0045: Expected O, but got Unknown //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown MainClass.playerIdsAndCosmetics.Clear(); if (NetworkManager.Singleton.IsServer) { CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager; object obj = <>O.<0>__SV_ReceiveCosmetics; if (obj == null) { HandleNamedMessageDelegate val = SV_ReceiveCosmetics; <>O.<0>__SV_ReceiveCosmetics = val; obj = (object)val; } customMessagingManager.RegisterNamedMessageHandler("MC_SV_SyncCosmetics", (HandleNamedMessageDelegate)obj); } else { CustomMessagingManager customMessagingManager2 = NetworkManager.Singleton.CustomMessagingManager; object obj2 = <>O.<1>__CL_ReceiveCosmetics; if (obj2 == null) { HandleNamedMessageDelegate val2 = CL_ReceiveCosmetics; <>O.<1>__CL_ReceiveCosmetics = val2; obj2 = (object)val2; } customMessagingManager2.RegisterNamedMessageHandler("MC_CL_ReceiveCosmetics", (HandleNamedMessageDelegate)obj2); CustomMessagingManager customMessagingManager3 = NetworkManager.Singleton.CustomMessagingManager; object obj3 = <>O.<2>__CL_ReceiveAllCosmetics; if (obj3 == null) { HandleNamedMessageDelegate val3 = CL_ReceiveAllCosmetics; <>O.<2>__CL_ReceiveAllCosmetics = val3; obj3 = (object)val3; } customMessagingManager3.RegisterNamedMessageHandler("MC_CL_ReceiveAllCosmetics", (HandleNamedMessageDelegate)obj3); } SyncCosmeticsToOtherClients(__instance, disabled: false, requestAll: true); } [HarmonyPatch(typeof(GameNetworkManager), "SetInstanceValuesBackToDefault")] [HarmonyPostfix] public static void SetInstanceValuesBackToDefault() { if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.CustomMessagingManager != null) { NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("MC_CL_ReceiveCosmetics"); NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("MC_CL_ReceiveAllCosmetics"); NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("MC_SV_SyncCosmetics"); MainClass.StaticLogger.LogInfo((object)"Unregistered Named Message Handlers"); } } } [HarmonyPatch] public static class PreventOldVersionChatSpamPatch { [HarmonyPatch(typeof(HUDManager), "AddChatMessage")] [HarmonyPrefix] public static bool AddChatMessage_Prefix(string chatMessage, string nameOfUserWhoTyped = "") { if (chatMessage.StartsWith("[replacewithdata]") || chatMessage.StartsWith("[morecompanycosmetics]")) { return false; } return true; } } [HarmonyPatch] public class CosmeticPatches { public static bool CloneCosmeticsToNonPlayer(ParentType parentType, Transform cosmeticRoot, int playerClientId, bool detachedHead = false) { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) if (MainClass.playerIdsAndCosmetics.ContainsKey(playerClientId)) { List<string> list = MainClass.playerIdsAndCosmetics[playerClientId]; CosmeticApplication cosmeticApplication = ((Component)cosmeticRoot).GetComponent<CosmeticApplication>(); if (!Object.op_Implicit((Object)(object)cosmeticApplication)) { cosmeticApplication = ((Component)cosmeticRoot).gameObject.AddComponent<CosmeticApplication>(); } cosmeticApplication.parentType = parentType; cosmeticApplication.detachedHead = detachedHead; cosmeticApplication.ClearCosmetics(); foreach (string item in list) { cosmeticApplication.ApplyCosmetic(item, startEnabled: false); } foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics) { Transform transform = ((Component)spawnedCosmetic).transform; transform.localScale *= 0.38f; } cosmeticApplication.UpdateAllCosmeticVisibilities(); return true; } return false; } [HarmonyPatch(typeof(PlayerControllerB), "SpawnDeadBody")] [HarmonyPostfix] public static void SpawnDeadBody(ref PlayerControllerB __instance, int deathAnimation = 0) { Transform transform = ((Component)__instance.deadBody).transform; if (!((Object)(object)transform == (Object)null)) { bool detachedHead = __instance.deadBody.detachedHead; if (deathAnimation == 4 || deathAnimation == 5) { detachedHead = true; } CloneCosmeticsToNonPlayer(ParentType.DeadBody, transform, (int)__instance.playerClientId, detachedHead); } } [HarmonyPatch(typeof(MaskedPlayerEnemy), "SetEnemyOutside")] [HarmonyPostfix] public static void SetEnemyOutside(MaskedPlayerEnemy __instance) { if (!((Object)(object)__instance.mimickingPlayer == (Object)null)) { Transform val = ((Component)__instance).transform.Find("ScavengerModel").Find("metarig"); if (!((Object)(object)val == (Object)null)) { CloneCosmeticsToNonPlayer(ParentType.MaskedEnemy, val, (int)__instance.mimickingPlayer.playerClientId); ((EnemyAI)__instance).skinnedMeshRenderers = ((Component)__instance).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(); ((EnemyAI)__instance).meshRenderers = ((Component)__instance).gameObject.GetComponentsInChildren<MeshRenderer>(); } } } [HarmonyPatch(typeof(QuickMenuManager), "OpenQuickMenu")] [HarmonyPatch(typeof(QuickMenuManager), "CloseQuickMenu")] [HarmonyPostfix] public static void ToggleQuickMenu(QuickMenuManager __instance) { if (CosmeticRegistry.menuIsInGame && (Object)(object)CosmeticRegistry.cosmeticGUIGlobalScale != (Object)null) { ((Component)CosmeticRegistry.cosmeticGUIGlobalScale.Find("ActivateButton")).gameObject.SetActive(__instance.isMenuOpen); if (!__instance.isMenuOpen) { ((Component)CosmeticRegistry.cosmeticGUIGlobalScale.Find("CosmeticsScreen")).gameObject.SetActive(false); } } } } public class DebugCommandRegistry { public static bool commandEnabled; public static void HandleCommand(string[] args) { //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: 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_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0166: 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) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_027a: 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_029b: Unknown result type (might be due to invalid IL or missing references) if (!commandEnabled) { return; } PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; switch (args[0]) { case "money": { int groupCredits = int.Parse(args[1]); Terminal val5 = Resources.FindObjectsOfTypeAll<Terminal>().First(); val5.groupCredits = groupCredits; break; } case "spawnscrap": { string text = ""; for (int i = 1; i < args.Length; i++) { text = text + args[i] + " "; } text = text.Trim(); Vector3 val = ((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f; SpawnableItemWithRarity val2 = null; foreach (SpawnableItemWithRarity item in StartOfRound.Instance.currentLevel.spawnableScrap) { if (item.spawnableItem.itemName.ToLower() == text.ToLower()) { val2 = item; break; } } GameObject val3 = Object.Instantiate<GameObject>(val2.spawnableItem.spawnPrefab, val, Quaternion.identity, (Transform)null); GrabbableObject component = val3.GetComponent<GrabbableObject>(); ((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation); component.fallTime = 0f; NetworkObject component2 = val3.GetComponent<NetworkObject>(); component2.Spawn(false); break; } case "spawnenemy": { string text2 = ""; for (int j = 1; j < args.Length; j++) { text2 = text2 + args[j] + " "; } text2 = text2.Trim(); SpawnableEnemyWithRarity val4 = null; foreach (SpawnableEnemyWithRarity enemy in StartOfRound.Instance.currentLevel.Enemies) { if (enemy.enemyType.enemyName.ToLower() == text2.ToLower()) { val4 = enemy; break; } } RoundManager.Instance.SpawnEnemyGameObject(((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f, 0f, -1, val4.enemyType); break; } case "listall": MainClass.StaticLogger.LogInfo((object)"Spawnable scrap:"); foreach (SpawnableItemWithRarity item2 in StartOfRound.Instance.currentLevel.spawnableScrap) { MainClass.StaticLogger.LogInfo((object)item2.spawnableItem.itemName); } MainClass.StaticLogger.LogInfo((object)"Spawnable enemies:"); { foreach (SpawnableEnemyWithRarity enemy2 in StartOfRound.Instance.currentLevel.Enemies) { MainClass.StaticLogger.LogInfo((object)enemy2.enemyType.enemyName); } break; } } } } [HarmonyPatch(typeof(ForestGiantAI), "LookForPlayers")] public static class LookForPlayersForestGiantPatch { public static void Prefix(ref ForestGiantAI __instance) { if (__instance.playerStealthMeters.Length != MainClass.newPlayerCount) { Array.Resize(ref __instance.playerStealthMeters, MainClass.newPlayerCount); for (int i = 0; i < MainClass.newPlayerCount; i++) { __instance.playerStealthMeters[i] = 0f; } } } } [HarmonyPatch(typeof(BlobAI), "Start")] public static class BlobAIStartPatch { public static void Postfix(ref BlobAI __instance) { Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount]; ReflectionUtils.SetFieldValue(__instance, "ragdollColliders", value); } } [HarmonyPatch(typeof(CrawlerAI), "Start")] public static class CrawlerAIStartPatch { public static void Postfix(ref CrawlerAI __instance) { Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount]; ReflectionUtils.SetFieldValue(__instance, "nearPlayerColliders", value); } } [HarmonyPatch(typeof(SpringManAI), "Update")] public static class SpringManAIUpdatePatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; foreach (CodeInstruction instruction in instructions) { if (!flag2) { if (!flag && ((object)instruction).ToString() == "call static float UnityEngine.Vector3::Distance(UnityEngine.Vector3 a, UnityEngine.Vector3 b)") { flag = true; } else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL") { flag2 = true; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); continue; } } list.Add(instruction); } if (!flag2) { MainClass.StaticLogger.LogWarning((object)"SpringManAIUpdatePatch failed to replace newPlayerCount"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")] public static class GetClosestPlayerPatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; foreach (CodeInstruction instruction in instructions) { if (!flag && ((object)instruction).ToString() == "ldc.i4.4 NULL") { flag = true; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); } else { list.Add(instruction); } } if (!flag) { MainClass.StaticLogger.LogWarning((object)"GetClosestPlayerPatch failed to replace newPlayerCount"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(EnemyAI), "GetAllPlayersInLineOfSight")] public static class GetAllPlayersInLineOfSightPatch { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction instruction in instructions) { if (instruction.opcode == OpCodes.Ldc_I4_4) { num++; instruction.opcode = OpCodes.Ldsfld; instruction.operand = AccessTools.Field(typeof(MainClass), "newPlayerCount"); } list.Add(instruction); } if (num != 2) { MainClass.StaticLogger.LogWarning((object)$"GetAllPlayersInLineOfSightPatch failed to replace newPlayerCount: {num}/2"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")] public static class DressGirlHauntPatch { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction instruction in instructions) { if (((object)instruction).ToString() == "ldc.i4.4 NULL") { num++; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); } else { list.Add(instruction); } } if (num != 3) { MainClass.StaticLogger.LogWarning((object)$"DressGirlHauntPatch failed to replace newPlayerCount: {num}/3"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(ButlerEnemyAI), "Start")] public static class ButlerEnemyAIPatch { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction instruction in instructions) { if (((object)instruction).ToString() == "ldc.i4.4 NULL") { num++; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); } else { list.Add(instruction); } } if (num != 3) { MainClass.StaticLogger.LogWarning((object)$"ButlerEnemyAIPatch failed to replace newPlayerCount: {num}/3"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(CaveDwellerAI), "GetAllPlayerBodiesInLineOfSight")] public static class GetAllPlayerBodiesInLineOfSightPatch { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction instruction in instructions) { if (instruction.opcode == OpCodes.Ldc_I4_4) { num++; instruction.opcode = OpCodes.Ldsfld; instruction.operand = AccessTools.Field(typeof(MainClass), "newPlayerCount"); } list.Add(instruction); } if (num != 2) { MainClass.StaticLogger.LogWarning((object)$"GetAllPlayerBodiesInLineOfSightPatch failed to replace newPlayerCount: {num}/2"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(HUDManager), "AddChatMessage")] public static class HudChatPatch { public static void Prefix(HUDManager __instance, ref string chatMessage, string nameOfUserWhoTyped = "") { if (!(__instance.lastChatMessage == chatMessage)) { StringBuilder stringBuilder = new StringBuilder(chatMessage); for (int i = 0; i < MainClass.newPlayerCount; i++) { string oldValue = $"[playerNum{i}]"; string playerUsername = StartOfRound.Instance.allPlayerScripts[i].playerUsername; stringBuilder.Replace(oldValue, playerUsername); } chatMessage = stringBuilder.ToString(); } } } [HarmonyPatch(typeof(MenuManager), "ClickHostButton")] [HarmonyPriority(0)] public static class MenuManagerHost { public static void UpdateTextBox(TMP_InputField inputField, string s) { if (inputField.text == MainClass.newPlayerCount.ToString()) { return; } if (int.TryParse(s, out var result)) { int newPlayerCount = MainClass.newPlayerCount; MainClass.newPlayerCount = Mathf.Clamp(result, MainClass.minPlayerCount, MainClass.maxPlayerCount); MainClass.StaticConfig.Save(); inputField.text = MainClass.newPlayerCount.ToString(); if (MainClass.newPlayerCount != newPlayerCount) { MainClass.StaticLogger.LogInfo((object)$"Changed Crew Count: {MainClass.newPlayerCount}"); } } else if (s.Length != 0) { inputField.text = MainClass.newPlayerCount.ToString(); inputField.caretPosition = 1; } } public static void SetupCrewCountInput(TMP_InputField inputField) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown inputField.text = MainClass.newPlayerCount.ToString(); if (!Object.op_Implicit((Object)(object)((Component)inputField).transform.Find("Registered"))) { ((UnityEvent<string>)(object)inputField.onSubmit).AddListener((UnityAction<string>)delegate(string s) { UpdateTextBox(inputField, s); }); ((UnityEvent<string>)(object)inputField.onDeselect).AddListener((UnityAction<string>)delegate(string s) { UpdateTextBox(inputField, s); }); GameObject val = new GameObject("Registered"); val.transform.parent = ((Component)inputField).transform; } } public static void CreateCrewCountInput(MenuManager __instance) { //IL_00bd: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)GameObject.Find("MC_CrewCount"))) { TMP_InputField componentInChildren = GameObject.Find("MC_CrewCount").GetComponentInChildren<TMP_InputField>(); SetupCrewCountInput(componentInChildren); return; } Transform val = __instance.HostSettingsScreen.transform.Find("HostSettingsContainer/LobbyHostOptions"); if ((Object)(object)val != (Object)null) { Transform val2 = val.Find(__instance.HostSettingsOptionsLAN.activeSelf ? "LANOptions" : "OptionsNormal"); if ((Object)(object)val2 != (Object)null) { GameObject val3 = Object.Instantiate<GameObject>(MainClass.crewCountUI, val2); ((Object)val3).name = "MC_CrewCount"; RectTransform component = val3.GetComponent<RectTransform>(); ((Transform)component).localPosition = new Vector3(96.9f, -70f, -6.7f); TMP_InputField componentInChildren2 = ((Component)val3.transform).GetComponentInChildren<TMP_InputField>(); componentInChildren2.characterLimit = 3; SetupCrewCountInput(componentInChildren2); } } } public static void Postfix(MenuManager __instance) { MainClass.newPlayerCount = (__instance.hostSettings_LobbyPublic ? 32 : 12); CreateCrewCountInput(__instance); } } [HarmonyPatch] public static class MenuManagerLogoOverridePatch { public static List<TMP_InputField> inputFields = new List<TMP_InputField>(); public static bool lanWarningShown = false; [HarmonyPatch(typeof(MenuManager), "Awake")] [HarmonyPostfix] [HarmonyPriority(0)] public static void Awake_Postfix(MenuManager __instance) { //IL_003c: 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_00cb: Unknown result type (might be due to invalid IL or missing references) if (__instance.isInitScene) { return; } MainClass.ReadSettingsFromFile(); try { Sprite sprite = Sprite.Create(MainClass.mainLogo, new Rect(0f, 0f, (float)((Texture)MainClass.mainLogo).width, (float)((Texture)MainClass.mainLogo).height), new Vector2(0.5f, 0.5f)); GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject; Transform val = gameObject.transform.Find("MenuContainer/MainButtons/HeaderImage"); if ((Object)(object)val != (Object)null) { ((Component)val).gameObject.GetComponent<Image>().sprite = sprite; } Transform val2 = gameObject.transform.Find("MenuContainer/LoadingScreen"); if ((Object)(object)val2 != (Object)null) { val2.localScale = new Vector3(1.02f, 1.06f, 1.02f); Transform val3 = val2.Find("Image"); if ((Object)(object)val3 != (Object)null) { ((Component)val3).GetComponent<Image>().sprite = sprite; } } } catch (Exception ex) { MainClass.StaticLogger.LogError((object)ex); } try { LANMenu.InitializeMenu(); } catch (Exception ex2) { MainClass.StaticLogger.LogError((object)ex2); } CosmeticRegistry.SpawnCosmeticGUI(mainMenu: true); } [HarmonyPatch(typeof(MenuManager), "Start")] [HarmonyPostfix] public static void Start_Postfix(MenuManager __instance) { if (!__instance.isInitScene && GameNetworkManager.Instance.disableSteam) { if (lanWarningShown) { __instance.lanWarningContainer.SetActive(false); } else { lanWarningShown = true; } } } } [HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")] public static class AddUserPlayerListPatch { private static bool Prefix(QuickMenuManager __instance, ulong steamId, string playerName, int playerObjectId) { QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance); return false; } } [HarmonyPatch(typeof(QuickMenuManager), "RemoveUserFromPlayerList")] public static class RemoveUserPlayerListPatch { public static bool Prefix(QuickMenuManager __instance) { QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance); return false; } } [HarmonyPatch(typeof(QuickMenuManager), "Update")] public static class QuickMenuUpdatePatch { public static bool Prefix() { return false; } } [HarmonyPatch(typeof(QuickMenuManager), "NonHostPlayerSlotsEnabled")] public static class QuickMenuDisplayPatch { public static bool Prefix(ref bool __result) { __result = false; for (int i = 1; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i]; if (val.isPlayerControlled || val.isPlayerDead) { __result = true; break; } } return false; } } [HarmonyPatch(typeof(QuickMenuManager), "Start")] public static class QuickmenuVisualInjectPatch { public static GameObject quickMenuScrollInstance; public static void Postfix(QuickMenuManager __instance) { //IL_0050: 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) GameObject gameObject = ((Component)__instance.playerListPanel.transform.Find("Image")).gameObject; GameObject val = Object.Instantiate<GameObject>(MainClass.quickMenuScrollParent); val.transform.SetParent(gameObject.transform); RectTransform component = val.GetComponent<RectTransform>(); ((Transform)component).localPosition = new Vector3(0f, -31.2f, 0f); ((Transform)component).localScale = Vector3.one; quickMenuScrollInstance = val; CosmeticRegistry.SpawnCosmeticGUI(mainMenu: false); } public static void PopulateQuickMenu(QuickMenuManager __instance) { //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0166: 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_0286: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Expected O, but got Unknown //IL_035f: Unknown result type (might be due to invalid IL or missing references) //IL_0369: Expected O, but got Unknown if ((Object)(object)quickMenuScrollInstance == (Object)null) { return; } Transform val = quickMenuScrollInstance.transform.Find("Holder"); if ((Object)(object)val == (Object)null) { return; } List<GameObject> list = new List<GameObject>(); int childCount = val.childCount; for (int i = 0; i < childCount; i++) { list.Add(((Component)val.GetChild(i)).gameObject); } foreach (GameObject item in list) { Object.Destroy((Object)(object)item); } if (!Object.op_Implicit((Object)(object)StartOfRound.Instance)) { return; } for (int j = 0; j < StartOfRound.Instance.allPlayerScripts.Length; j++) { PlayerControllerB playerScript = StartOfRound.Instance.allPlayerScripts[j]; if (!playerScript.isPlayerControlled && !playerScript.isPlayerDead) { continue; } GameObject val2 = Object.Instantiate<GameObject>(MainClass.playerEntry, val); RectTransform component = val2.GetComponent<RectTransform>(); ((Transform)component).localScale = Vector3.one; ((Transform)component).localPosition = new Vector3(0f, 0f - ((Transform)component).localPosition.y, 0f); TextMeshProUGUI component2 = ((Component)val2.transform.Find("PlayerNameButton").Find("PName")).GetComponent<TextMeshProUGUI>(); ((TMP_Text)component2).text = playerScript.playerUsername; Slider playerVolume = ((Component)val2.transform.Find("PlayerVolumeSlider")).GetComponent<Slider>(); int finalIndex = j; ((UnityEvent<float>)(object)playerVolume.onValueChanged).AddListener((UnityAction<float>)delegate(float f) { if (playerScript.isPlayerControlled || playerScript.isPlayerDead) { float num = (f - playerVolume.minValue) / (playerVolume.maxValue - playerVolume.minValue); if (num <= 0f) { num = -70f; } SoundManager.Instance.playerVoiceVolumes[finalIndex] = num; } }); playerVolume.value = Mathf.Clamp(SoundManager.Instance.playerVoiceVolumes[j] * (playerVolume.maxValue - playerVolume.minValue) + playerVolume.minValue, playerVolume.minValue, playerVolume.maxValue); Button component3 = ((Component)val2.transform.Find("KickButton")).GetComponent<Button>(); ((UnityEvent)component3.onClick).AddListener((UnityAction)delegate { __instance.KickUserFromServer(finalIndex); }); if ((Object)(object)StartOfRound.Instance.localPlayerController != (Object)null && StartOfRound.Instance.localPlayerController.playerClientId == playerScript.playerClientId) { ((Component)playerVolume).gameObject.SetActive(false); ((Component)val2.transform.Find("Text (1)")).gameObject.SetActive(false); ((Component)component3).gameObject.SetActive(false); } else if (!GameNetworkManager.Instance.isHostingGame) { ((Component)component3).gameObject.SetActive(false); } Button component4 = ((Component)val2.transform.Find("ProfileIcon")).GetComponent<Button>(); ((UnityEvent)component4.onClick).AddListener((UnityAction)delegate { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (!GameNetworkManager.Instance.disableSteam) { SteamFriends.OpenUserOverlay(SteamId.op_Implicit(playerScript.playerSteamId), "steamid"); } }); } } } [HarmonyPatch(typeof(QuickMenuManager), "ConfirmKickUserFromServer")] public static class KickPatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; foreach (CodeInstruction instruction in instructions) { if (!flag2) { if (!flag && ((object)instruction).ToString() == "ldfld int QuickMenuManager::playerObjToKick") { flag = true; } else if (flag && ((object)instruction).ToString() == "ldc.i4.3 NULL") { flag2 = true; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); continue; } } list.Add(instruction); } if (!flag2) { MainClass.StaticLogger.LogWarning((object)"KickPatch failed to replace newPlayerCount"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(HUDManager), "UpdateBoxesSpectateUI")] public static class SpectatorBoxUpdatePatch { public static void Postfix(HUDManager __instance) { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) Dictionary<Animator, PlayerControllerB> fieldValue = ReflectionUtils.GetFieldValue<Dictionary<Animator, PlayerControllerB>>(__instance, "spectatingPlayerBoxes"); int num = -64; int num2 = 0; int num3 = 0; int num4 = -70; int num5 = 230; int num6 = 4; foreach (KeyValuePair<Animator, PlayerControllerB> item in fieldValue) { if (((Component)item.Key).gameObject.activeInHierarchy) { GameObject gameObject = ((Component)item.Key).gameObject; RectTransform component = gameObject.GetComponent<RectTransform>(); int num7 = (int)Math.Floor((double)num3 / (double)num6); int num8 = num3 % num6; int num9 = num8 * num4; int num10 = num7 * num5; component.anchoredPosition = Vector2.op_Implicit(new Vector3((float)(num + num10), (float)(num2 + num9), 0f)); num3++; } } } } [HarmonyPatch(typeof(HUDManager), "Start")] public static class HudStartPatch { public static void Postfix(HUDManager __instance) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) EndOfGameStatUIElements statsUIElements = __instance.statsUIElements; GameObject gameObject = ((Component)((Component)statsUIElements.playerNamesText[0]).gameObject.transform.parent).gameObject; GameObject gameObject2 = ((Component)gameObject.transform.parent.parent).gameObject; GameObject gameObject3 = ((Component)gameObject2.transform.Find("BGBoxes")).gameObject; gameObject2.transform.parent.Find("DeathScreen").SetSiblingIndex(3); gameObject3.transform.localScale = new Vector3(2.5f, 1f, 1f); MakePlayerHolder(4, gameObject, statsUIElements, new Vector3(426.9556f, -0.7932f, 0f)); MakePlayerHolder(5, gameObject, statsUIElements, new Vector3(426.9556f, -115.4483f, 0f)); MakePlayerHolder(6, gameObject, statsUIElements, new Vector3(-253.6783f, -115.4483f, 0f)); MakePlayerHolder(7, gameObject, statsUIElements, new Vector3(-253.6783f, -0.7932f, 0f)); for (int i = 8; i < MainClass.newPlayerCount; i++) { MakePlayerHolder(i, gameObject, statsUIElements, new Vector3(10000f, 10000f, 0f)); } } public static void MakePlayerHolder(int index, GameObject original, EndOfGameStatUIElements uiElements, Vector3 localPosition) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) if (index + 1 <= MainClass.newPlayerCount) { GameObject val = Object.Instantiate<GameObject>(original); RectTransform component = val.GetComponent<RectTransform>(); RectTransform component2 = original.GetComponent<RectTransform>(); ((Transform)component).SetParent(((Transform)component2).parent); ((Transform)component).localScale = new Vector3(1f, 1f, 1f); ((Transform)component).localPosition = localPosition; GameObject gameObject = ((Component)val.transform.Find("PlayerName1")).gameObject; GameObject gameObject2 = ((Component)val.transform.Find("Notes")).gameObject; ((Transform)gameObject2.GetComponent<RectTransform>()).localPosition = new Vector3(-95.7222f, 43.3303f, 0f); GameObject gameObject3 = ((Component)val.transform.Find("Symbol")).gameObject; if (index >= uiElements.playerNamesText.Length) { Array.Resize(ref uiElements.playerNamesText, index + 1); Array.Resize(ref uiElements.playerStates, index + 1); Array.Resize(ref uiElements.playerNotesText, index + 1); } uiElements.playerNamesText[index] = gameObject.GetComponent<TextMeshProUGUI>(); uiElements.playerNotesText[index] = gameObject2.GetComponent<TextMeshProUGUI>(); uiElements.playerStates[index] = gameObject3.GetComponent<Image>(); } } } public class LANMenu : MonoBehaviour { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__0_0; internal void <InitializeMenu>b__0_0() { GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(true); } } public static void InitializeMenu() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //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_0069: Expected O, but got Unknown CreateUI(); GameObject val = GameObject.Find("Canvas/MenuContainer/MainButtons/StartLAN"); if (!((Object)(object)val != (Object)null)) { return; } MainClass.StaticLogger.LogInfo((object)"LANMenu startLAN Patched"); val.GetComponent<Button>().onClick = new ButtonClickedEvent(); ButtonClickedEvent onClick = val.GetComponent<Button>().onClick; object obj = <>c.<>9__0_0; if (obj == null) { UnityAction val2 = delegate { GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(true); }; <>c.<>9__0_0 = val2; obj = (object)val2; } ((UnityEvent)onClick).AddListener((UnityAction)obj); } private static GameObject CreateUI() { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Expected O, but got Unknown //IL_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Expected O, but got Unknown if ((Object)(object)GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings") != (Object)null) { return null; } GameObject val = GameObject.Find("Canvas/MenuContainer"); if ((Object)(object)val == (Object)null) { return null; } GameObject val2 = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings"); if ((Object)(object)val2 == (Object)null) { return null; } GameObject val3 = Object.Instantiate<GameObject>(val2, val2.transform.position, val2.transform.rotation, val.transform); ((Object)val3).name = "LobbyJoinSettings"; Transform val4 = val3.transform.Find("HostSettingsContainer"); if ((Object)(object)val4 != (Object)null) { ((Object)val4).name = "JoinSettingsContainer"; ((Object)((Component)val4).transform.Find("LobbyHostOptions")).name = "LobbyJoinOptions"; Object.Destroy((Object)(object)((Component)val3.transform.Find("ChallengeLeaderboard")).gameObject); Object.Destroy((Object)(object)((Component)val3.transform.Find("FilesPanel")).gameObject); Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/OptionsNormal")).gameObject); Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/AllowRemote")).gameObject); Object.Destroy((Object)(object)((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/Local")).gameObject); Transform val5 = ((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/Header"); if ((Object)(object)val5 != (Object)null) { ((TMP_Text)((Component)val5).GetComponent<TextMeshProUGUI>()).text = "Join LAN Server:"; } Transform val6 = ((Component)val4).transform.Find("LobbyJoinOptions/LANOptions/ServerNameField"); if ((Object)(object)val6 != (Object)null) { ((Component)val6).transform.localPosition = new Vector3(0f, 15f, -6.5f); ((Component)val6).gameObject.SetActive(true); } TMP_InputField ip_field = ((Component)val6).GetComponent<TMP_InputField>(); if ((Object)(object)ip_field != (Object)null) { TextMeshProUGUI ip_placeholder = ((Component)ip_field.placeholder).GetComponent<TextMeshProUGUI>(); ((TMP_Text)ip_placeholder).text = ES3.Load<string>("LANIPAddress", "LCGeneralSaveData", "127.0.0.1"); Transform obj = ((Component)val4).transform.Find("Confirm"); Button val7 = ((obj != null) ? ((Component)obj).GetComponent<Button>() : null); if ((Object)(object)val7 != (Object)null) { val7.onClick = new ButtonClickedEvent(); ((UnityEvent)val7.onClick).AddListener((UnityAction)delegate { string text = "127.0.0.1"; text = ((!(ip_field.text != "")) ? ((TMP_Text)ip_placeholder).text : ip_field.text); ES3.Save<string>("LANIPAddress", text, "LCGeneralSaveData"); GameObject.Find("Canvas/MenuContainer/LobbyJoinSettings").gameObject.SetActive(false); ((Component)NetworkManager.Singleton).GetComponent<UnityTransport>().ConnectionData.Address = text; MainClass.StaticLogger.LogInfo((object)("Listening to LAN server: " + text)); GameObject.Find("MenuManager").GetComponent<MenuManager>().StartAClient(); }); } } ((Component)((Component)val4).transform.Find("LobbyJoinOptions/LANOptions")).gameObject.SetActive(true); } return val3; } } [HarmonyPatch(typeof(GameNetworkManager), "OnLocalClientConnectionDisapproved")] public static class ConnectionDisapprovedPatch { private static int crewSizeMismatch; private static IEnumerator delayedReconnect() { yield return (object)new WaitForSeconds(0.5f); GameObject.Find("MenuManager").GetComponent<MenuManager>().StartAClient(); } private static void Prefix(GameNetworkManager __instance, ulong clientId) { crewSizeMismatch = 0; if (!__instance.disableSteam) { return; } try { if (!string.IsNullOrEmpty(NetworkManager.Singleton.DisconnectReason) && NetworkManager.Singleton.DisconnectReason.StartsWith("Crew size mismatch!")) { crewSizeMismatch = int.Parse(NetworkManager.Singleton.DisconnectReason.Split("Their size: ")[1].Split(". ")[0]); } } catch { } } private static void Postfix(GameNetworkManager __instance, ulong clientId) { if (__instance.disableSteam && crewSizeMismatch != 0) { MainClass.newPlayerCount = Mathf.Clamp(crewSizeMismatch, MainClass.minPlayerCount, MainClass.maxPlayerCount); if (MainClass.newPlayerCount == crewSizeMismatch) { GameObject.Find("MenuManager").GetComponent<MenuManager>().menuNotification.SetActive(false); Object.FindObjectOfType<MenuManager>().SetLoadingScreen(true, (RoomEnter)5, ""); ((MonoBehaviour)__instance).StartCoroutine(delayedReconnect()); } crewSizeMismatch = 0; } } } public static class PluginInformation { public const string PLUGIN_NAME = "MoreCompany"; public const string PLUGIN_VERSION = "1.11.0"; public const string PLUGIN_GUID = "me.swipez.melonloader.morecompany"; } [BepInPlugin("me.swipez.melonloader.morecompany", "MoreCompany", "1.11.0")] public class MainClass : BaseUnityPlugin { public static int defaultPlayerCount = 32; public static int minPlayerCount = 4; public static int maxPlayerCount = 50; public static int newPlayerCount = 32; public static ConfigFile StaticConfig; public static ConfigEntry<int> playerCount; public static ConfigEntry<bool> cosmeticsDeadBodies; public static ConfigEntry<bool> cosmeticsMaskedEnemy; public static ConfigEntry<bool> cosmeticsSyncOther; public static ConfigEntry<bool> defaultCosmetics; public static ConfigEntry<bool> cosmeticsPerProfile; public static ConfigEntry<string> disabledCosmetics; public static Texture2D mainLogo; public static GameObject quickMenuScrollParent; public static GameObject playerEntry; public static GameObject crewCountUI; public static GameObject cosmeticGUIInstance; public static GameObject cosmeticButton; public static ManualLogSource StaticLogger; public static Dictionary<int, List<string>> playerIdsAndCosmetics = new Dictionary<int, List<string>>(); public static string dynamicCosmeticsPath; public static string cosmeticSavePath; private void Awake() { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Expected O, but got Unknown StaticLogger = ((BaseUnityPlugin)this).Logger; StaticConfig = ((BaseUnityPlugin)this).Config; playerCount = StaticConfig.Bind<int>("General", "Player Count", defaultPlayerCount, new ConfigDescription("How many players can be in your lobby?", (AcceptableValueBase)(object)new AcceptableValueRange<int>(minPlayerCount, maxPlayerCount), Array.Empty<object>())); cosmeticsSyncOther = StaticConfig.Bind<bool>("Cosmetics", "Show Cosmetics", true, "Should you be able to see cosmetics of other players?"); cosmeticsDeadBodies = StaticConfig.Bind<bool>("Cosmetics", "Show On Dead Bodies", true, "Should you be able to see cosmetics on dead bodies?"); cosmeticsMaskedEnemy = StaticConfig.Bind<bool>("Cosmetics", "Show On Masked Enemy", true, "Should you be able to see cosmetics on the masked enemy?"); defaultCosmetics = StaticConfig.Bind<bool>("Cosmetics", "Default Cosmetics", true, "Should the default cosmetics be enabled?"); cosmeticsPerProfile = StaticConfig.Bind<bool>("Cosmetics", "Per Profile Cosmetics", false, "Should the cosmetics be saved per-profile?"); disabledCosmetics = StaticConfig.Bind<string>("Cosmetics", "Disabled Cosmetics", "", "Comma separated list of cosmetics to disable"); cosmeticsSyncOther.SettingChanged += delegate { PlayerControllerB[] array3 = Object.FindObjectsByType<PlayerControllerB>((FindObjectsSortMode)0); foreach (PlayerControllerB val6 in array3) { Transform val7 = ((Component)val6).transform.Find("ScavengerModel").Find("metarig"); if (!((Object)(object)val7 == (Object)null)) { CosmeticApplication component3 = ((Component)val7).gameObject.GetComponent<CosmeticApplication>(); if (!((Object)(object)component3 == (Object)null)) { component3.UpdateAllCosmeticVisibilities((int)val6.playerClientId == StartOfRound.Instance.thisClientPlayerId); } } } }; cosmeticsDeadBodies.SettingChanged += delegate { PlayerControllerB[] array2 = Object.FindObjectsByType<PlayerControllerB>((FindObjectsSortMode)0); foreach (PlayerControllerB val5 in array2) { Transform transform = ((Component)val5.deadBody).transform; if (!((Object)(object)transform == (Object)null)) { CosmeticApplication component2 = ((Component)transform).GetComponent<CosmeticApplication>(); if (!((Object)(object)component2 == (Object)null)) { component2.UpdateAllCosmeticVisibilities(); } } } }; cosmeticsMaskedEnemy.SettingChanged += delegate { MaskedPlayerEnemy[] array = Object.FindObjectsByType<MaskedPlayerEnemy>((FindObjectsSortMode)0); foreach (MaskedPlayerEnemy val3 in array) { Transform val4 = ((Component)val3).transform.Find("ScavengerModel").Find("metarig"); if (!((Object)(object)val4 == (Object)null)) { CosmeticApplication component = ((Component)val4).GetComponent<CosmeticApplication>(); if (!((Object)(object)component == (Object)null)) { component.UpdateAllCosmeticVisibilities(); ((EnemyAI)val3).skinnedMeshRenderers = ((Component)val3).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(); ((EnemyAI)val3).meshRenderers = ((Component)val3).gameObject.GetComponentsInChildren<MeshRenderer>(); } } } }; Harmony val = new Harmony("me.swipez.melonloader.morecompany"); try { val.PatchAll(); } catch (Exception ex) { StaticLogger.LogError((object)("Failed to patch: " + ex)); } StaticLogger.LogInfo((object)"Loading MoreCompany..."); SteamFriends.OnGameLobbyJoinRequested += delegate(Lobby lobby, SteamId steamId) { newPlayerCount = ((Lobby)(ref lobby)).MaxMembers; }; SteamMatchmaking.OnLobbyEntered += delegate(Lobby lobby) { newPlayerCount = ((Lobby)(ref lobby)).MaxMembers; }; StaticLogger.LogInfo((object)"Loading SETTINGS..."); ReadSettingsFromFile(); dynamicCosmeticsPath = Paths.PluginPath + "/MoreCompanyCosmetics"; if (cosmeticsPerProfile.Value) { cosmeticSavePath = Application.persistentDataPath + "/morecompanycosmetics-" + Directory.GetParent(Paths.BepInExRootPath).Name + ".txt"; } else { cosmeticSavePath = Application.persistentDataPath + "/morecompanycosmetics.txt"; } cosmeticsPerProfile.SettingChanged += delegate { if (cosmeticsPerProfile.Value) { cosmeticSavePath = Application.persistentDataPath + "/MCCosmeticsSave-" + Directory.GetParent(Paths.BepInExRootPath).Name + ".mcs"; } else { cosmeticSavePath = Application.persistentDataPath + "/MCCosmeticsSave.mcs"; } }; StaticLogger.LogInfo((object)("Checking: " + dynamicCosmeticsPath)); if (!Directory.Exists(dynamicCosmeticsPath)) { StaticLogger.LogInfo((object)"Creating cosmetics directory"); Directory.CreateDirectory(dynamicCosmeticsPath); } StaticLogger.LogInfo((object)"Loading COSMETICS..."); ReadCosmeticsFromFile(); if (defaultCosmetics.Value) { StaticLogger.LogInfo((object)"Loading DEFAULT COSMETICS..."); AssetBundle val2 = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.cosmetics", Assembly.GetExecutingAssembly()); CosmeticRegistry.LoadCosmeticsFromBundle(val2, "morecompany.cosmetics"); val2.Unload(false); } StaticLogger.LogInfo((object)"Loading USER COSMETICS..."); RecursiveCosmeticLoad(Paths.PluginPath); AssetBundle bundle = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.assets", Assembly.GetExecutingAssembly()); LoadAssets(bundle); StaticLogger.LogInfo((object)"Loaded MoreCompany FULLY"); } private void RecursiveCosmeticLoad(string directory) { string[] directories = Directory.GetDirectories(directory); foreach (string directory2 in directories) { RecursiveCosmeticLoad(directory2); } string[] files = Directory.GetFiles(directory); foreach (string text in files) { if (text.EndsWith(".cosmetics")) { AssetBundle val = AssetBundle.LoadFromFile(text); CosmeticRegistry.LoadCosmeticsFromBundle(val, text); val.Unload(false); } } } private void ReadCosmeticsFromFile() { if (File.Exists(cosmeticSavePath)) { string[] array = File.ReadAllLines(cosmeticSavePath); string[] array2 = array; foreach (string item in array2) { CosmeticRegistry.locallySelectedCosmetics.Add(item); } } } public static void WriteCosmeticsToFile() { string text = ""; foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics) { text = text + locallySelectedCosmetic + "\n"; } File.WriteAllText(cosmeticSavePath, text); } public static void SaveSettingsToFile() { playerCount.Value = newPlayerCount; StaticConfig.Save(); } public static void ReadSettingsFromFile() { try { newPlayerCount = Mathf.Clamp(playerCount.Value, minPlayerCount, maxPlayerCount); } catch { newPlayerCount = defaultPlayerCount; playerCount.Value = newPlayerCount; StaticConfig.Save(); } } private static void LoadAssets(AssetBundle bundle) { if (Object.op_Implicit((Object)(object)bundle)) { mainLogo = bundle.LoadPersistentAsset<Texture2D>("assets/morecompanyassets/morecompanytransparentred.png"); quickMenuScrollParent = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/quickmenuoverride.prefab"); playerEntry = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/playerlistslot.prefab"); cosmeticGUIInstance = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/testoverlay.prefab"); cosmeticButton = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/cosmeticinstance.prefab"); crewCountUI = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/crewcountfield.prefab"); bundle.Unload(false); } } public static void ResizePlayerCache(Dictionary<uint, Dictionary<int, NetworkObject>> ScenePlacedObjects) { //IL_0111: 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_0240: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Expected O, but got Unknown //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Expected O, but got Unknown StartOfRound instance = StartOfRound.Instance; if (instance.allPlayerObjects.Length != newPlayerCount) { uint num = 10000u; int num2 = instance.allPlayerObjects.Length; int num3 = newPlayerCount - num2; StaticLogger.LogInfo((object)$"Resizing arrays from {num2} to {newPlayerCount} with difference of {num3}"); Array.Resize(ref instance.allPlayerObjects, newPlayerCount); Array.Resize(ref instance.allPlayerScripts, newPlayerCount); Array.Resize(ref instance.gameStats.allPlayerStats, newPlayerCount); Array.Resize(ref instance.playerSpawnPositions, newPlayerCount); if (num3 > 0) { GameObject val = instance.allPlayerObjects[num2 - 1]; for (int i = 0; i < num3; i++) { uint num4 = num + (uint)i; GameObject val2 = Object.Instantiate<GameObject>(val, val.transform.parent); NetworkObject component = val2.GetComponent<NetworkObject>(); ReflectionUtils.SetFieldValue(component, "GlobalObjectIdHash", num4); Scene scene = ((Component)component).gameObject.scene; int handle = ((Scene)(ref scene)).handle; uint num5 = num4; if (!ScenePlacedObjects.ContainsKey(num5)) { ScenePlacedObjects.Add(num5, new Dictionary<int, NetworkObject>()); } if (ScenePlacedObjects[num5].ContainsKey(handle)) { string arg = (((Object)(object)ScenePlacedObjects[num5][handle] != (Object)null) ? ((Object)ScenePlacedObjects[num5][handle]).name : "Null Entry"); throw new Exception(((Object)component).name + " tried to registered with ScenePlacedObjects which already contains " + string.Format("the same {0} value {1} for {2}!", "GlobalObjectIdHash", num5, arg)); } ScenePlacedObjects[num5].Add(handle, component); ((Object)val2).name = $"Player ({num2 + i})"; PlayerControllerB componentInChildren = val2.GetComponentInChildren<PlayerControllerB>(); componentInChildren.playerClientId = (ulong)(num2 + i); componentInChildren.playerUsername = $"Player #{componentInChildren.playerClientId}"; componentInChildren.isPlayerControlled = false; componentInChildren.isPlayerDead = false; componentInChildren.DropAllHeldItems(false, false); componentInChildren.TeleportPlayer(instance.notSpawnedPosition.position, false, 0f, false, true); instance.allPlayerObjects[num2 + i] = val2; instance.gameStats.allPlayerStats[num2 + i] = new PlayerStats(); instance.allPlayerScripts[num2 + i] = componentInChildren; instance.playerSpawnPositions[num2 + i] = instance.playerSpawnPositions[3]; StartOfRound.Instance.mapScreen.radarTargets.Add(new TransformAndName(((Component)componentInChildren).transform, componentInChildren.playerUsername, false)); } } } PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val3 in allPlayerScripts) { ((TMP_Text)val3.usernameBillboardText).text = val3.playerUsername; } } } [HarmonyPatch(typeof(PlayerControllerB), "Start")] public static class PlayerControllerBStartPatch { public static void Postfix(ref PlayerControllerB __instance) { Collider[] value = (Collider[])(object)new Collider[MainClass.newPlayerCount]; ReflectionUtils.SetFieldValue(__instance, "nearByPlayers", value); } } [HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesServerRpc")] public static class SendNewPlayerValuesServerRpcPatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; foreach (CodeInstruction instruction in instructions) { if (!flag2) { if (!flag && ((object)instruction).ToString() == "callvirt virtual void System.Collections.Generic.List<ulong>::Add(ulong item)") { flag = true; } else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL") { flag2 = true; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); continue; } } list.Add(instruction); } if (!flag2) { MainClass.StaticLogger.LogWarning((object)"SendNewPlayerValuesServerRpcPatch failed to replace newPlayerCount"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[] { })] public static class SyncAllPlayerLevelsPatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); int num = 0; foreach (CodeInstruction instruction in instructions) { if (((object)instruction).ToString() == "ldc.i4.4 NULL") { num++; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); } else { list.Add(instruction); } } if (num != 2) { MainClass.StaticLogger.LogWarning((object)$"SyncAllPlayerLevelsPatch failed to replace newPlayerCount: {num}/2"); } return list.AsEnumerable(); } } [HarmonyPatch] public static class SyncShipUnlockablesPatch { [HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesServerRpc")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> ServerTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; int num = 0; foreach (CodeInstruction instruction in instructions) { if (num != 2) { if (!flag && ((object)instruction).ToString() == "callvirt bool Unity.Netcode.NetworkManager::get_IsHost()") { flag = true; } else if (((object)instruction).ToString().StartsWith("ldc.i4.4 NULL")) { num++; CodeInstruction val = new CodeInstruction(instruction); val.opcode = OpCodes.Ldsfld; val.operand = AccessTools.Field(typeof(MainClass), "newPlayerCount"); list.Add(val); continue; } } list.Add(instruction); } if (num != 2) { MainClass.StaticLogger.LogWarning((object)$"SyncShipUnlockablesServerRpc failed to replace newPlayerCount: {num}/2"); } return list.AsEnumerable(); } [HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> ClientTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; foreach (CodeInstruction instruction in instructions) { if (!flag2) { if (!flag && ((object)instruction).ToString() == "callvirt void UnityEngine.Renderer::set_sharedMaterial(UnityEngine.Material value)") { flag = true; } else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL") { flag2 = true; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); continue; } } list.Add(instruction); } if (!flag2) { MainClass.StaticLogger.LogWarning((object)"SyncShipUnlockablesClientRpc failed to replace newPlayerCount"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")] public static class ScenePlacedObjectsInitPatch { public static void Postfix(ref Dictionary<uint, Dictionary<int, NetworkObject>> ___ScenePlacedObjects) { MainClass.ResizePlayerCache(___ScenePlacedObjects); } } [HarmonyPatch(typeof(GameNetworkManager), "LobbyDataIsJoinable")] public static class LobbyDataJoinablePatch { public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; foreach (CodeInstruction instruction in instructions) { if (!flag2) { if (!flag && ((object)instruction).ToString() == "call int Steamworks.Data.Lobby::get_MemberCount()") { flag = true; } else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL") { flag2 = true; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "maxPlayerCount")); list.Add(item); continue; } } list.Add(instruction); } if (!flag2) { MainClass.StaticLogger.LogWarning((object)"LobbyDataIsJoinable failed to replace maxPlayerCount"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")] public static class LobbyThingPatch { public static void Prefix(ref int maxMembers) { MainClass.ReadSettingsFromFile(); maxMembers = MainClass.newPlayerCount; } } [HarmonyPatch(typeof(GameNetworkManager), "SetConnectionDataBeforeConnecting")] public static class ConnectionDataPatch { public static void Postfix(ref GameNetworkManager __instance) { string @string = Encoding.ASCII.GetString(NetworkManager.Singleton.NetworkConfig.ConnectionData); List<string> list = new List<string> { @string }; if (__instance.disableSteam) { list.Add($"maxslots:{MainClass.newPlayerCount}"); } else { list.Add("maxslots:-1"); } string s = string.Join(',', list); NetworkManager.Singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(s); } } [HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")] public static class ConnectionApproval { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; foreach (CodeInstruction instruction in instructions) { if (!flag2) { if (!flag && ((object)instruction).ToString() == "ldfld int GameNetworkManager::connectedPlayers") { flag = true; } else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL") { flag2 = true; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); continue; } } list.Add(instruction); } if (!flag2) { MainClass.StaticLogger.LogWarning((object)"ConnectionApproval failed to replace newPlayerCount"); } return list.AsEnumerable(); } private static void Postfix(ref GameNetworkManager __instance, ref ConnectionApprovalRequest request, ref ConnectionApprovalResponse response) { if (!response.Approved) { return; } string @string = Encoding.ASCII.GetString(request.Payload); string[] source = @string.Split(","); int num = 4; if (!string.IsNullOrEmpty(@string)) { if (__instance.disableSteam) { if (source.Any((string x) => Regex.IsMatch(x, "^maxslots:\\d+$"))) { string text = source.First((string x) => Regex.IsMatch(x, "^maxslots:\\d+$")); int num2 = int.Parse(text.Substring(9)); num = num2; } } else if (source.Contains("maxslots:-1")) { num = MainClass.newPlayerCount; } } if (response.Approved && MainClass.newPlayerCount > 4 && MainClass.newPlayerCount != num) { response.Reason = $"Crew size mismatch! Their size: {MainClass.newPlayerCount}. Your size: {num}"; response.Approved = false; } } } [HarmonyPatch] public static class TogglePlayerObjectsPatch { [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPrefix] private static void ConnectClientToPlayerObject() { PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (val.isPlayerControlled || val.isPlayerDead) { ((Component)val).gameObject.SetActive(true); } else { ((Component)val).gameObject.SetActive(false); } } } [HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")] [HarmonyPrefix] private static void OnPlayerConnectedClientRpc(StartOfRound __instance, ulong clientId, int connectedPlayers, ulong[] connectedPlayerIdsOrdered, int assignedPlayerObjectId, int serverMoneyAmount, int levelID, int profitQuota, int timeUntilDeadline, int quotaFulfilled, int randomSeed, bool isChallenge) { ((Component)__instance.allPlayerScripts[assignedPlayerObjectId]).gameObject.SetActive(true); SoundManager.Instance.playerVoiceVolumes[assignedPlayerObjectId] = 0.5f; } [HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")] [HarmonyPostfix] private static void OnPlayerDC(StartOfRound __instance, int playerObjectNumber, ulong clientId) { ((Component)__instance.allPlayerScripts[playerObjectNumber]).gameObject.SetActive(false); } [HarmonyPatch(typeof(StartOfRound), "KickPlayer")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> KickPlayer_Reason(IEnumerable<CodeInstruction> instructions) { //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; foreach (CodeInstruction instruction in instructions) { if (!flag2) { if (!flag && instruction.opcode == OpCodes.Ldfld && instruction.operand?.ToString() == "System.UInt64 actualClientId") { flag = true; list.Add(instruction); CodeInstruction item = new CodeInstruction(OpCodes.Ldstr, (object)"You have been kicked."); list.Add(item); continue; } if (flag && instruction.opcode == OpCodes.Callvirt && instruction.operand?.ToString() == "Void DisconnectClient(UInt64)") { flag2 = true; instruction.operand = AccessTools.Method(typeof(NetworkManager), "DisconnectClient", new Type[2] { typeof(ulong), typeof(string) }, (Type[])null); } } list.Add(instruction); } if (!flag2) { MainClass.StaticLogger.LogWarning((object)"KickPlayer failed to append reason"); return instructions.AsEnumerable(); } return list.AsEnumerable(); } } public class ReflectionUtils { public static void InvokeMethod(object obj, string methodName, object[] parameters) { Type type = obj.GetType(); MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); method.Invoke(obj, parameters); } public static void InvokeMethod(object obj, Type forceType, string methodName, object[] parameters) { MethodInfo method = forceType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); method.Invoke(obj, parameters); } public static void SetPropertyValue(object obj, string propertyName, object value) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); property.SetValue(obj, value); } public static T InvokeMethod<T>(object obj, string methodName, object[] parameters) { Type type = obj.GetType(); MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return (T)method.Invoke(obj, parameters); } public static T GetFieldValue<T>(object obj, string fieldName) { Type type = obj.GetType(); FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return (T)field.GetValue(obj); } public static void SetFieldValue(object obj, string fieldName, object value) { Type type = obj.GetType(); FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); field.SetValue(obj, value); } } [HarmonyPatch(typeof(ShipTeleporter), "Awake")] public static class ShipTeleporterAwakePatch { public static void Postfix(ref ShipTeleporter __instance) { int[] array = new int[MainClass.newPlayerCount]; for (int i = 0; i < MainClass.newPlayerCount; i++) { array[i] = -1; } ReflectionUtils.SetFieldValue(__instance, "playersBeingTeleported", array); } } [HarmonyPatch] public static class SoundManagerPatch { internal const float defaultPlayerVolume = 0.5f; internal static bool initialVolumeSet; [HarmonyPatch(typeof(SoundManager), "Start")] [HarmonyPostfix] public static void SM_Start(ref SoundManager __instance) { initialVolumeSet = false; float num = 16f; __instance.diageticMixer.SetFloat("PlayerVolume0", num); __instance.diageticMixer.SetFloat("PlayerVolume1", num); __instance.diageticMixer.SetFloat("PlayerVolume2", num); __instance.diageticMixer.SetFloat("PlayerVolume3", num); initialVolumeSet = true; Array.Resize(ref __instance.playerVoicePitchLerpSpeed, MainClass.newPlayerCount); Array.Resize(ref __instance.playerVoicePitchTargets, MainClass.newPlayerCount); Array.Resize(ref __instance.playerVoicePitches, MainClass.newPlayerCount); Array.Resize(ref __instance.playerVoiceVolumes, MainClass.newPlayerCount); Array.Resize(ref __instance.playerVoiceMixers, MainClass.newPlayerCount); AudioMixerGroup val = ((IEnumerable<AudioMixerGroup>)Resources.FindObjectsOfTypeAll<AudioMixerGroup>()).FirstOrDefault((Func<AudioMixerGroup, bool>)((AudioMixerGroup x) => ((Object)x).name.StartsWith("VoicePlayer"))); for (int i = 0; i < MainClass.newPlayerCount; i++) { __instance.playerVoicePitchLerpSpeed[i] = 3f; __instance.playerVoicePitchTargets[i] = 1f; __instance.playerVoicePitches[i] = 1f; __instance.playerVoiceVolumes[i] = 0.5f; if (!Object.op_Implicit((Object)(object)__instance.playerVoiceMixers[i])) { __instance.playerVoiceMixers[i] = val; } } } } [HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")] public static class SpawnPositionClampPatch { public static void Prefix(ref StartOfRound __instance, ref int playerNum, bool simpleTeleport = false) { if (!Object.op_Implicit((Object)(object)__instance.playerSpawnPositions[playerNum])) { playerNum = __instance.playerSpawnPositions.Length - 1; } } } [HarmonyPatch(typeof(StartOfRound), "OnClientConnect")] public static class OnClientConnectedPatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); bool flag = false; bool flag2 = false; foreach (CodeInstruction instruction in instructions) { if (!flag2) { if (!flag && ((object)instruction).ToString() == "callvirt virtual bool System.Collections.Generic.List<int>::Contains(int item)") { flag = true; } else if (flag && ((object)instruction).ToString() == "ldc.i4.4 NULL") { flag2 = true; CodeInstruction item = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(MainClass), "newPlayerCount")); list.Add(item); continue; } } list.Add(instruction); } if (!flag2) { MainClass.StaticLogger.LogWarning((object)"OnClientConnect failed to replace newPlayerCount"); } return list.AsEnumerable(); } } [HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")] public static class OnPlayerDCPatch { public static void Postfix(int playerObjectNumber, ulong clientId) { if (MainClass.playerIdsAndCosmetics.ContainsKey(playerObjectNumber)) { MainClass.playerIdsAndCosmetics.Remove(playerObjectNumber); } } } [HarmonyPatch(typeof(GameNetworkManager), "Awake")] public static class GameNetworkAwakePatch { public static int originalVersion; public static void Postfix(GameNetworkManager __instance) { originalVersion = __instance.gameVersionNum; if (!Chainloader.PluginInfos.ContainsKey("LC_API")) { __instance.gameVersionNum = 9950 + originalVersion; } } } [HarmonyPatch(typeof(MenuManager), "Awake")] public static class MenuManagerVersionDisplayPatch { public static void Postfix(MenuManager __instance) { if ((Object)(object)GameNetworkManager.Instance != (Object)null && (Object)(object)__instance.versionNumberText != (Object)null) { ((TMP_Text)__instance.versionNumberText).text = $"v{GameNetworkAwakePatch.originalVersion} (MC)"; } } } [HarmonyPatch(typeof(SteamLobbyManager), "loadLobbyListAndFilter")] public static class LoadLobbyListAndFilterPatch { public static IEnumerator Postfix(IEnumerator result) { while (result.MoveNext()) { yield return result.Current; } LobbySlot[] lobbySlots = Object.FindObjectsOfType<LobbySlot>(); LobbySlot[] array = lobbySlots; foreach (LobbySlot lobbySlot in array) { ((TMP_Text)lobbySlot.playerCount).text = $"{((Lobby)(ref lobbySlot.thisLobby)).MemberCount} / {((Lobby)(ref lobbySlot.thisLobby)).MaxMembers}"; } } } } namespace MoreCompany.Utils { public class BundleUtilities { public static byte[] GetResourceBytes(string filename, Assembly assembly) { string[] manifestResourceNames = assembly.GetManifestResourceNames(); foreach (string text in manifestResourceNames) { if (!text.Contains(filename)) { continue; } using Stream stream = assembly.GetManifestResourceStream(text); if (stream == null) { return null; } byte[] array = new byte[stream.Length]; stream.Read(array, 0, array.Length); return array; } return null; } public static AssetBundle LoadBundleFromInternalAssembly(string filename, Assembly assembly) { return AssetBundle.LoadFromMemory(GetResourceBytes(filename, assembly)); } } public static class AssetBundleExtension { public static T LoadPersistentAsset<T>(this AssetBundle bundle, string name) where T : Object { Object val = bundle.LoadAsset(name); if (val != (Object)null) { val.hideFlags = (HideFlags)32; return (T)(object)val; } return default(T); } } } namespace MoreCompany.Cosmetics { public enum ParentType { Player, DeadBody, MaskedEnemy, DisplayGuy } public class CosmeticApplication : MonoBehaviour { public bool detachedHead = false; public ParentType parentType; public Transform head; public Transform hip; public Transform lowerArmRight; public Transform shinLeft; public Transform shinRight; public Transform chest; public List<CosmeticInstance> spawnedCosmetics = new List<CosmeticInstance>(); public List<string> spawnedCosmeticsIds = new List<string>(); public void Awake() { Transform val = ((Component)this).transform.Find("spine") ?? ((Component)this).transform; chest = val.Find("spine.001").Find("spine.002").Find("spine.003"); head = chest.Find("spine.004"); lowerArmRight = chest.Find("shoulder.R").Find("arm.R_upper").Find("arm.R_lower"); hip = val; shinLeft = val.Find("thigh.L").Find("shin.L"); shinRight = val.Find("thigh.R").Find("shin.R"); if (parentType == ParentType.DisplayGuy) { CosmeticRegistry.UpdateCosmeticsOnDisplayGuy(startEnabled: false); } RefreshAllCosmeticPositions(); } private void OnDisable() { foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics) { ((Component)spawnedCosmetic).gameObject.SetActive(false); } } private void OnEnable() { if (spawnedCosmetics.Count <= 0) { return; } if (parentType == ParentType.Player) { PlayerControllerB componentInParent = ((Component)((Component)this).transform).GetComponentInParent<PlayerControllerB>(); UpdateAllCosmeticVisibilities((Object)(object)componentInParent != (Object)null && (int)componentInParent.playerClientId == StartOfRound.Instance.thisClientPlayerId); } else if (parentType == ParentType.MaskedEnemy) { UpdateAllCosmeticVisibilities(); MaskedPlayerEnemy componentInParent2 = ((Component)((Component)this).transform).GetComponentInParent<MaskedPlayerEnemy>(); if ((Object)(object)componentInParent2 != (Object)null) { ((EnemyAI)componentInParent2).skinnedMeshRenderers = ((Component)componentInParent2).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(); ((EnemyAI)componentInParent2).meshRenderers = ((Component)componentInParent2).gameObject.GetComponentsInChildren<MeshRenderer>(); } } else { UpdateAllCosmeticVisibilities(); } } public void ClearCosmetics() { foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics) { Object.Destroy((Object)(object)((Component)spawnedCosmetic).gameObject); } spawnedCosmetics.Clear(); spawnedCosmeticsIds.Clear(); } public bool ApplyCosmetic(string cosmeticId, bool startEnabled) { if (CosmeticRegistry.cosmeticInstances.ContainsKey(cosmeticId) && !spawnedCosmeticsIds.Contains(cosmeticId)) { CosmeticInstance cosmeticInstance = CosmeticRegistry.cosmeticInstances[cosmeticId]; if (startEnabled && cosmeticInstance.cosmeticType == CosmeticType.HAT && detachedHead) { return false; } GameObject val = Object.Instantiate<GameObject>(((Component)cosmeticInstance).gameObject); val.SetActive(startEnabled); CosmeticInstance component = val.GetComponent<CosmeticInstance>(); spawnedCosmetics.Add(component); ParentCosmetic(component); spawnedCosmeticsIds.Add(cosmeticId); return true; } return false; } public void UpdateAllCosmeticVisibilities(bool isLocalPlayer = false) { bool active = false; if (parentType == ParentType.Player) { active = MainClass.cosmeticsSyncOther.Value && !isLocalPlayer; } else if (parentType == ParentType.DeadBody) { active = MainClass.cosmeticsDeadBodies.Value; } else if (parentType == ParentType.MaskedEnemy) { active = MainClass.cosmeticsMaskedEnemy.Value; } else if (parentType == ParentType.DisplayGuy) { active = true; } foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics) { if (spawnedCosmetic.cosmeticType != 0 || !detachedHead) { ((Component)spawnedCosmetic).gameObject.SetActive(active); } } } public void RefreshAllCosmeticPositions() { foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics) { ParentCosmetic(spawnedCosmetic); } } private bool ParentCosmetic(CosmeticInstance cosmeticInstance) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) Transform val = null; switch (cosmeticInstance.cosmeticType) { case CosmeticType.HAT: val = head; break; case CosmeticType.R_LOWER_ARM: val = lowerArmRight; break; case CosmeticType.HIP: val = hip; break; case CosmeticType.L_SHIN: val = shinLeft; break; case CosmeticType.R_SHIN: val = shinRight; break; case CosmeticType.CHEST: val = chest; break; } if ((Object)(object)val == (Object)null) { MainClass.StaticLogger.LogError((object)("Failed to find transform of type: " + cosmeticInstance.cosmeticType)); return false; } ((Component)cosmeticInstance).transform.position = val.position; ((Component)cosmeticInstance).transform.rotation = val.rotation; ((Component)cosmeticInstance).transform.parent = val; return true; } } public class CosmeticInstance : MonoBehaviour { public CosmeticType cosmeticType; public string cosmeticId; public Texture2D icon; } public class CosmeticGeneric { public virtual string gameObjectPath { get; } public virtual string cosmeticId { get; } public virtual string textureIconPath { get; } public CosmeticType cosmeticType { get; } public void LoadFromBundle(AssetBundle bundle) { GameObject val = bundle.LoadPersistentAsset<GameObject>(gameObjectPath); Texture2D icon = bundle.LoadPersistentAsset<Texture2D>(textureIconPath); CosmeticInstance cosmeticInstance = val.AddComponent<CosmeticInstance>(); cosmeticInstance.cosmeticId = cosmeticId; cosmeticInstance.icon = icon; cosmeticInstance.cosmeticType = cosmeticType; MainClass.StaticLogger.LogInfo((object)("Loaded cosmetic: " + cosmeticId + " from bundle: " + ((Object)bundle).name)); CosmeticRegistry.cosmeticInstances.Add(cosmeticId, cosmeticInstance); } } public enum CosmeticType { HAT, WRIST, CHEST, R_LOWER_ARM, HIP, L_SHIN, R_SHIN } public class CosmeticRegistry { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__10_0; public static UnityAction <>9__10_1; public static Func<string, bool> <>9__16_0; internal void <SpawnCosmeticGUI>b__10_0() { MainClass.cosmeticsSyncOther.Value = true; MainClass.StaticConfig.Save(); } internal void <SpawnCosmeticGUI>b__10_1() { MainClass.cosmeticsSyncOther.Value = false; MainClass.StaticConfig.Save(); } internal bool <GetCosmeticsToSync>b__16_0(string x) { return cosmeticInstances.ContainsKey(x); } } public static Dictionary<string, CosmeticInstance> cosmeticInstances = new Dictionary<string, CosmeticInstance>(); public static Transform cosmeticGUIGlobalScale; private static GameObject displayGuy; internal static CosmeticApplication displayGuyCosmeticApplication; public static List<string> locallySelectedCosmetics = new List<string>(); public static bool menuIsInGame = false; public const float COSMETIC_PLAYER_SCALE_MULT = 0.38f; public static void LoadCosmeticsFromBundle(AssetBundle bundle, string bundleName = null) { string[] allAssetNames = bundle.GetAllAssetNames(); foreach (string text in allAssetNames) { if (!text.EndsWith(".prefab")) { continue; } GameObject val = bundle.LoadPersistentAsset<GameObject>(text); CosmeticInstance component = val.GetComponent<CosmeticInstance>(); if (!((Object)(object)component == (Object)null)) { if (MainClass.disabledCosmetics.Value.Split(',').Contains(component.cosmeticId)) { MainClass.StaticLogger.LogInfo((object)("Skipped cosmetic: " + component.cosmeticId + ", bundle: " + bundleName + ", reason: disabled")); } else if (cosmeticInstances.ContainsKey(component.cosmeticId)) { MainClass.StaticLogger.LogWarning((object)("Skipped cosmetic: " + component.cosmeticId + ", bundle: " + bundleName + ", reason: duplicate id")); } else { MainClass.StaticLogger.LogInfo((object)("Loaded cosmetic: " + component.cosmeticId + " from bundle: " + bundleName)); cosmeticInstances.Add(component.cosmeticId, component); } } } } public static void LoadCosmeticsFromAssembly(Assembly assembly, AssetBundle bundle) { Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (type.IsSubclassOf(typeof(CosmeticGeneric))) { CosmeticGeneric cosmeticGeneric = (CosmeticGeneric)type.GetConstructor(new Type[0]).Invoke(new object[0]); cosmeticGeneric.LoadFromBundle(bundle); } } } public static void UpdateVisibilityCheckbox(GameObject enableCosmeticsButton, GameObject disableCosmeticsButton) { if (MainClass.cosmeticsSyncOther.Value) { enableCosmeticsButton.SetActive(false); disableCosmeticsButton.SetActive(true); } else { enableCosmeticsButton.SetActive(true); disableCosmeticsButton.SetActive(false); } } public static void SpawnCosmeticGUI(bool mainMenu) { //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Expected O, but got Unknown //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Expected O, but got Unknown if (cosmeticInstances.Count == 0) { return; } menuIsInGame = !mainMenu; GameObject val = Object.Instantiate<GameObject>(MainClass.cosmeticGUIInstance); cosmeticGUIGlobalScale = val.transform.Find("Canvas").Find("GlobalScale"); if (menuIsInGame) { ((Component)cosmeticGUIGlobalScale).transform.parent = GameObject.Find("Systems/UI/Canvas/").transform; ((Component)cosmeticGUIGlobalScale).transform.localPosition = new Vector3(0f, 0f, 0f); ((Component)cosmeticGUIGlobalScale).transform.localScale = new Vector3(0.9f, 0.9f, 0.9f); Object.Destroy((Object)(object)val); ((Component)cosmeticGUIGlobalScale.Find("CosmeticsScreen").Find("ObjectHolder")).transform.localPosition = new Vector3(210f, 0f, -100f); ((Component)cosmeticGUIGlobalScale.Find("CosmeticsScreen").Find("ObjectHolder").Find("Spot Light")).GetComponent<Light>().intensity = 30f; ((Component)cosmeticGUIGlobalScale.Find("ActivateButton")).gameObject.SetActive(false); } else { ((Component)cosmeticGUIGlobalScale).transform.localScale = new Vector3(2f, 2f, 2f); } displayGuy = ((Component)cosmeticGUIGlobalScale.Find("CosmeticsScreen").Find("ObjectHolder").Find("ScavengerModel") .Find("metarig")).gameObject; displayGuyCosmeticApplication = displayGuy.AddComponent<CosmeticApplication>(); displayGuyCosmeticApplication.parentType = ParentType.DisplayGuy; GameObject gameObject = ((Component)cosmeticGUIGlobalScale.Find("CosmeticsScreen").Find("EnableButton")).gameObject; GameObject gameObject2 = ((Component)cosmeticGUIGlobalScale.Find("CosmeticsScreen").Find("DisableButton")).gameObject; ButtonClickedEvent onClick = gameObject.GetComponent<Button>().onClick; object obj = <>c.<>9__10_0; if (obj == null) { UnityAction val2 = delegate { MainClass.cosmeticsSyncOther.Value = true; MainClass.StaticConfig.Save(); }; <>c.<>9__10_0 = val2; obj = (object)val2; } ((UnityEvent)onClick).AddListener((UnityAction)obj); ButtonClickedEvent onClick2 = gameObject2.GetComponent<Button>().onClick; object obj2 = <>c.<>9__10_1; if (obj2 == null) { UnityAction val3 = delegate { MainClass.cosmeticsSyncOther.Value = false; MainClass.StaticConfig.Save(); }; <>c.<>9__10_1 = val3; obj2 = (object)val3; } ((UnityEvent)onClick2).AddListener((UnityAction)obj2); UpdateVisibilityCheckbox(gameObject, gameObject2); PopulateCosmetics(); } public static void PopulateCosmetics() { //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Expected O, but got Unknown GameObject gameObject = ((Component)cosmeticGUIGlobalScale.Find("CosmeticsScreen").Find("CosmeticsHolder").Find("Content")).gameObject; List<Transform> list = new List<Transform>(); for (int i = 0; i < gameObject.transform.childCount; i++) { list.Add(gameObject.transform.GetChild(i)); } foreach (Transform item in list) { Object.Destroy((Object)(object)((Component)item).gameObject); } foreach (KeyValuePair<string, CosmeticInstance> cosmeticInstance in cosmeticInstances) { GameObject val = Object.Instantiate<GameObject>(MainClass.cosmeticButton, gameObject.transform); val.transform.localScale = Vector3.one; GameObject disabledOverlay = ((Component)val.transform.Find("Deselected")).gameObject; disabledOverlay.SetActive(true); GameObject enabledOverlay = ((Component)val.transform.Find("Selected")).gameObject; enabledOverlay.SetActive(true); if (IsEquipped(cosmeticInstance.Value.cosmeticId)) { enabledOverlay.SetActive(true); disabledOverlay.SetActive(false); } else { enabledOverlay.SetActive(false); disabledOverlay.SetActive(true); } RawImage component = ((Component)val.transform.Find("Icon")).GetComponent<RawImage>(); component.texture = (Texture)(object)cosmeticInstance.Value.icon; Button component2 = val.GetComponent<Button>(); ((UnityEvent)component2.onClick).AddListener((UnityAction)delegate { ToggleCosmetic(cosmeticInstance.Value.cosmeticId); if (IsEquipped(cosmeticInstance.Value.c
plugins/NoSellLimit.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: AssemblyCompany("NoSellLimit")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Remove the limit of items that can be placed on the deposit desk")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyProduct("NoSellLimit")] [assembly: AssemblyTitle("NoSellLimit")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.1.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 NoSellLimit { [BepInPlugin("viviko.NoSellLimit", "NoSellLimit", "1.0.1")] public class NoSellLimit : BaseUnityPlugin { [HarmonyPatch(typeof(DepositItemsDesk))] [HarmonyPatch("PlaceItemOnCounter")] public static class PlaceItemOnCounterPatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Expected O, but got Unknown //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Expected O, but got Unknown //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0136: 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) CodeMatch[] array = (CodeMatch[])(object)new CodeMatch[7] { new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Ldarg_0), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => CodeInstructionExtensions.LoadsField(i, AccessTools.Field(typeof(DepositItemsDesk), "deskObjectsContainer"), false)), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Callvirt), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Ldlen), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Conv_I4), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Ldc_I4_S), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction i) => i.opcode == OpCodes.Bge), (string)null) }; CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val.Start(); val.MatchForward(false, array); val.SetOpcodeAndAdvance(OpCodes.Nop); val.RemoveInstructions(array.Length - 1); return val.Instructions(); } } private const string modGUID = "viviko.NoSellLimit"; private const string modName = "NoSellLimit"; private const string modVersion = "1.0.1"; private readonly Harmony harmony = new Harmony("viviko.NoSellLimit"); private static NoSellLimit Instance; public static ManualLogSource mls; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("NoSellLimit"); harmony.PatchAll(); mls.LogInfo((object)"Plugin NoSellLimit is loaded!"); } } internal static class GeneratedPluginInfo { public const string Identifier = "viviko.NoSellLimit"; public const string Name = "NoSellLimit"; public const string Version = "1.0.1"; } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ExperimentalAttribute : Attribute { public string DiagnosticId { get; } public string? UrlFormat { get; set; } public ExperimentalAttribute(string diagnosticId) { DiagnosticId = diagnosticId; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class SetsRequiredMembersAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object?[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = new object[0]; } public StringSyntaxAttribute(string syntax, params object?[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class UnscopedRefAttribute : Attribute { } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiresPreviewFeaturesAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string? message) { Message = message; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CollectionBuilderAttribute : Attribute { public Type BuilderType { get; } public string MethodName { get; } public CollectionBuilderAttribute(Type builderType, string methodName) { BuilderType = builderType; MethodName = methodName; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; set; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class InterpolatedStringHandlerAttribute : Attribute { } [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal sealed class RequiresLocationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class SkipLocalsInitAttribute : Attribute { } }
plugins/SolosBodycams.dll
Decompiled 5 hours agousing System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("SolosBodycams")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Solo's Bodycams")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("SolosBodycams")] [assembly: AssemblyTitle("SolosBodycams")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace SolosBodycams; [BepInPlugin("SolosBodycams", "Solo's Bodycams", "1.0")] public class Plugin : BaseUnityPlugin { private GameObject ShipExternalCamera = null; private int TransformIndexCopy; private bool ActivateCamera1 = false; private bool ActivateCamera2 = false; private bool SwitchedMonitors = false; private RenderTexture NewRT; private Vector3 CameraOriginalPosition; private Quaternion CameraOriginalRotation; private string Spine4Addition = ""; private float yadd = 0f; private static Plugin Instance; private static ConfigFile SoloBodycamConfigs { get; set; } internal static ConfigEntry<bool> BodycamOrHeadcam { get; set; } internal static ConfigEntry<int> RenderTextureX { get; set; } public void Awake() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Expected O, but got Unknown if ((Object)(object)Instance == (Object)null) { Instance = this; ((Object)((Component)this).gameObject).hideFlags = (HideFlags)61; } else if ((Object)(object)Instance != (Object)(object)this) { Object.Destroy((Object)(object)((Component)this).gameObject); } SoloBodycamConfigs = new ConfigFile(Paths.ConfigPath + "\\SoloMods\\CameraPlacement.cfg", true); BodycamOrHeadcam = SoloBodycamConfigs.Bind<bool>("CameraPlacement", "Bool", true, "True for HEADCAM, False for BODYCAM"); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Headcam: " + BodycamOrHeadcam.Value)); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Bodycam: " + !BodycamOrHeadcam.Value)); RenderTextureX = SoloBodycamConfigs.Bind<int>("Camera Resolution", "Width (pixels)", 160, "Width of the camera display, Height is calculated internally from width (4:3). WARNING: SETTING THIS NUMBER HIGHER THAN 160 COULD CAUSE PERFORMANCE ISSUES"); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Render Texture X value: " + RenderTextureX.Value)); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Render Texture Y value: " + RenderTextureX.Value / 4 * 3)); if (BodycamOrHeadcam.Value) { Spine4Addition = "/spine.004"; } else { Spine4Addition = ""; } Object.DontDestroyOnLoad((Object)((Component)this).gameObject); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin SolosBodycams is loaded!"); SceneManager.sceneLoaded += OnSceneLoaded; } public void OnSceneLoaded(Scene scene, LoadSceneMode mode) { ActivateCamera2 = false; if (!(((Scene)(ref scene)).name == "MainMenu") && !(((Scene)(ref scene)).name == "InitScene") && !(((Scene)(ref scene)).name == "InitSceneLaunchOptions")) { ActivateCamera1 = true; ((MonoBehaviour)this).StartCoroutine(LoadSceneEnter()); } else { ActivateCamera1 = false; SwitchedMonitors = false; } } private IEnumerator LoadSceneEnter() { yield return (object)new WaitForSeconds(5f); ActivateCamera2 = true; if (!((Object)(object)GameObject.Find("Environment/HangarShip/Cameras/ShipCamera") == (Object)null) && !SwitchedMonitors) { NewRT = new RenderTexture(RenderTextureX.Value, RenderTextureX.Value / 4 * 3, 32, (RenderTextureFormat)0); ((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube").GetComponent<MeshRenderer>()).materials[2].mainTexture = ((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001").GetComponent<MeshRenderer>()).materials[2].mainTexture; ((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001").GetComponent<MeshRenderer>()).materials[2].mainTexture = (Texture)(object)NewRT; if ((Object)(object)ShipExternalCamera == (Object)null) { ShipExternalCamera = Object.Instantiate<GameObject>(GameObject.Find("Environment/HangarShip/Cameras/ShipCamera")); ShipExternalCamera.transform.SetParent(GameObject.Find("Environment/HangarShip/Cameras/ShipCamera").transform.parent); ShipExternalCamera.transform.SetLocalPositionAndRotation(GameObject.Find("Environment/HangarShip/Cameras/ShipCamera").transform.localPosition, GameObject.Find("Environment/HangarShip/Cameras/ShipCamera").transform.localRotation); ShipExternalCamera.AddComponent<Camera>(); ShipExternalCamera.GetComponent<Camera>().cullingMask = 557520895; ShipExternalCamera.GetComponent<Camera>().nearClipPlane = 0.35f; CameraOriginalPosition = ShipExternalCamera.transform.localPosition; CameraOriginalRotation = ShipExternalCamera.transform.localRotation; Object.Destroy((Object)(object)((Component)ShipExternalCamera.transform.Find("VolumeMain (1)")).GetComponent<BoxCollider>()); Object.Destroy((Object)(object)ShipExternalCamera.GetComponent<Animator>()); Object.Destroy((Object)(object)ShipExternalCamera.GetComponent<MeshRenderer>()); } ShipExternalCamera.GetComponent<Camera>().targetTexture = NewRT; SwitchedMonitors = true; } } public void Update() { //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_022b: 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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_0148: 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_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) if (!ActivateCamera1 || !ActivateCamera2) { return; } TransformIndexCopy = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001/CameraMonitorScript").GetComponent<ManualCameraRenderer>().targetTransformIndex; TransformAndName val = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001/CameraMonitorScript").GetComponent<ManualCameraRenderer>().radarTargets[TransformIndexCopy]; if (!val.isNonPlayer) { ShipExternalCamera.transform.SetPositionAndRotation(val.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003" + Spine4Addition).position + new Vector3(0f, 0.1f, 0f), val.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003" + Spine4Addition).rotation * Quaternion.Euler(0f, 0f, 0f)); DeadBodyInfo[] array = Object.FindObjectsOfType<DeadBodyInfo>(); for (int i = 0; i < array.Length; i++) { if (array[i].playerScript.playerUsername == val.name) { ShipExternalCamera.transform.SetPositionAndRotation(((Component)array[i]).gameObject.transform.Find("spine.001/spine.002/spine.003" + Spine4Addition).position + new Vector3(0f, 0.1f, 0f), ((Component)array[i]).gameObject.transform.Find("spine.001/spine.002/spine.003" + Spine4Addition).rotation * Quaternion.Euler(0f, 0f, 0f)); } } } else { yadd += 1f; ShipExternalCamera.transform.SetPositionAndRotation(val.transform.position + new Vector3(0f, 1.6f, 0f), Quaternion.Euler(val.transform.eulerAngles + new Vector3(0f, -90f + yadd, 0f))); } } } public static class PluginInfo { public const string PLUGIN_GUID = "SolosBodycams"; public const string PLUGIN_NAME = "SolosBodycams"; public const string PLUGIN_VERSION = "1.0.0"; }
patchers/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using BepInEx.Configuration; using BepInEx.Logging; using Mono.Cecil; using MonoMod; using MonoMod.RuntimeDetour.HookGen; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Bepinex.Monomod.HookGenPatcher")] [assembly: AssemblyDescription("Runtime HookGen for BepInEx")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HarbingerOfMe")] [assembly: AssemblyProduct("Bepinex.Monomod.HookGenPatcher")] [assembly: AssemblyCopyright("HarbingerOfMe-2022")] [assembly: AssemblyTrademark("MIT")] [assembly: ComVisible(false)] [assembly: Guid("12032e45-9577-4195-8f4f-a729911b2f08")] [assembly: AssemblyFileVersion("1.2.1.0")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("1.2.1.0")] namespace BepInEx.MonoMod.HookGenPatcher; public static class HookGenPatcher { internal static ManualLogSource Logger = Logger.CreateLogSource("HookGenPatcher"); private const string CONFIG_FILE_NAME = "HookGenPatcher.cfg"; private static readonly ConfigFile Config = new ConfigFile(Path.Combine(Paths.ConfigPath, "HookGenPatcher.cfg"), true); private const char EntrySeparator = ','; private static readonly ConfigEntry<string> AssemblyNamesToHookGenPatch = Config.Bind<string>("General", "MMHOOKAssemblyNames", "Assembly-CSharp.dll", $"Assembly names to make mmhooks for, separate entries with : {','} "); private static readonly ConfigEntry<bool> preciseHash = Config.Bind<bool>("General", "Preciser filehashing", false, "Hash file using contents instead of size. Minor perfomance impact."); private static bool skipHashing => !preciseHash.Value; public static IEnumerable<string> TargetDLLs { get; } = new string[0]; public static void Initialize() { //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Expected O, but got Unknown //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Expected O, but got Unknown //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Expected O, but got Unknown //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Expected O, but got Unknown string[] array = AssemblyNamesToHookGenPatch.Value.Split(new char[1] { ',' }); string text = Path.Combine(Paths.PluginPath, "MMHOOK"); string[] array2 = array; foreach (string text2 in array2) { string text3 = "MMHOOK_" + text2; string text4 = Path.Combine(Paths.ManagedPath, text2); string text5 = Path.Combine(text, text3); bool flag = true; string[] files = Directory.GetFiles(Paths.PluginPath, text3, SearchOption.AllDirectories); foreach (string text6 in files) { if (Path.GetFileName(text6).Equals(text3)) { text5 = text6; Logger.LogInfo((object)"Previous MMHOOK location found. Using that location to save instead."); flag = false; break; } } if (flag) { Directory.CreateDirectory(text); } FileInfo fileInfo = new FileInfo(text4); long length = fileInfo.Length; long num = 0L; if (File.Exists(text5)) { try { AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text5); try { if (val.MainModule.GetType("BepHookGen.size" + length) != null) { if (skipHashing) { Logger.LogInfo((object)"Already ran for this version, reusing that file."); continue; } num = fileInfo.makeHash(); if (val.MainModule.GetType("BepHookGen.content" + num) != null) { Logger.LogInfo((object)"Already ran for this version, reusing that file."); continue; } } } finally { ((IDisposable)val)?.Dispose(); } } catch (BadImageFormatException) { Logger.LogWarning((object)("Failed to read " + Path.GetFileName(text5) + ", probably corrupted, remaking one.")); } } Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1"); Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0"); MonoModder val2 = new MonoModder { InputPath = text4, OutputPath = text5, ReadingMode = (ReadingMode)2 }; try { IAssemblyResolver assemblyResolver = val2.AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(Paths.BepInExAssemblyDirectory); } val2.Read(); val2.MapDependencies(); if (File.Exists(text5)) { Logger.LogDebug((object)("Clearing " + text5)); File.Delete(text5); } Logger.LogInfo((object)"Starting HookGenerator"); HookGenerator val3 = new HookGenerator(val2, Path.GetFileName(text5)); ModuleDefinition outputModule = val3.OutputModule; try { val3.Generate(); outputModule.Types.Add(new TypeDefinition("BepHookGen", "size" + length, (TypeAttributes)1, outputModule.TypeSystem.Object)); if (!skipHashing) { outputModule.Types.Add(new TypeDefinition("BepHookGen", "content" + ((num == 0L) ? fileInfo.makeHash() : num), (TypeAttributes)1, outputModule.TypeSystem.Object)); } outputModule.Write(text5); } finally { ((IDisposable)outputModule)?.Dispose(); } Logger.LogInfo((object)"Done."); } finally { ((IDisposable)val2)?.Dispose(); } } } public static void Patch(AssemblyDefinition _) { } private static long makeHash(this FileInfo fileInfo) { FileStream inputStream = fileInfo.OpenRead(); byte[] value = null; using (MD5 mD = new MD5CryptoServiceProvider()) { value = mD.ComputeHash(inputStream); } long num = BitConverter.ToInt64(value, 0); if (num == 0L) { return 1L; } return num; } }
patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Mdb; using Mono.Cecil.Pdb; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.InlineRT; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021 0x0ade")] [assembly: AssemblyDescription("General purpose .NET assembly modding \"basework\". This package contains the core IL patcher and relinker.")] [assembly: AssemblyFileVersion("21.8.5.1")] [assembly: AssemblyInformationalVersion("21.08.05.01")] [assembly: AssemblyProduct("MonoMod")] [assembly: AssemblyTitle("MonoMod")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("21.8.5.1")] [module: UnverifiableCode] internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace MonoMod { [MonoMod__SafeToCopy__] public class MonoModAdded : Attribute { } [MonoMod__SafeToCopy__] public class MonoModConstructor : Attribute { } [MonoMod__SafeToCopy__] public class MonoModCustomAttributeAttribute : Attribute { public MonoModCustomAttributeAttribute(string h) { } } [MonoMod__SafeToCopy__] public class MonoModCustomMethodAttributeAttribute : Attribute { public MonoModCustomMethodAttributeAttribute(string h) { } } [MonoMod__SafeToCopy__] public class MonoModEnumReplace : Attribute { } [MonoMod__SafeToCopy__] public class MonoModForceCall : Attribute { } [MonoMod__SafeToCopy__] public class MonoModForceCallvirt : Attribute { } [MonoMod__SafeToCopy__] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [Obsolete("Use MonoModLinkFrom or RuntimeDetour / HookGen instead.")] public class MonoModHook : Attribute { public string FindableID; public Type Type; public MonoModHook(string findableID) { FindableID = findableID; } public MonoModHook(Type type) { Type = type; FindableID = type.FullName; } } [MonoMod__SafeToCopy__] public class MonoModIfFlag : Attribute { public MonoModIfFlag(string key) { } public MonoModIfFlag(string key, bool fallback) { } } [MonoMod__SafeToCopy__] public class MonoModIgnore : Attribute { } [MonoMod__SafeToCopy__] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MonoModLinkFrom : Attribute { public string FindableID; public Type Type; public MonoModLinkFrom(string findableID) { FindableID = findableID; } public MonoModLinkFrom(Type type) { Type = type; FindableID = type.FullName; } } [MonoMod__SafeToCopy__] public class MonoModLinkTo : Attribute { public MonoModLinkTo(string t) { } public MonoModLinkTo(Type t) { } public MonoModLinkTo(string t, string n) { } public MonoModLinkTo(Type t, string n) { } } [MonoMod__SafeToCopy__] public class MonoModNoNew : Attribute { } [MonoMod__SafeToCopy__] public class MonoModOnPlatform : Attribute { public MonoModOnPlatform(params Platform[] p) { } } [MonoMod__SafeToCopy__] public class MonoModOriginal : Attribute { } [MonoMod__SafeToCopy__] public class MonoModOriginalName : Attribute { public MonoModOriginalName(string n) { } } [MonoMod__SafeToCopy__] public class MonoModPatch : Attribute { public MonoModPatch(string name) { } } [MonoMod__SafeToCopy__] public class MonoModPublic : Attribute { } [MonoMod__SafeToCopy__] public class MonoModRemove : Attribute { } [MonoMod__SafeToCopy__] public class MonoModReplace : Attribute { } [MonoMod__SafeToCopy__] public class MonoModTargetModule : Attribute { public MonoModTargetModule(string name) { } } [MonoMod__SafeToCopy__] internal class MonoMod__SafeToCopy__ : Attribute { } public delegate bool MethodParser(MonoModder modder, MethodBody body, Instruction instr, ref int instri); public delegate void MethodRewriter(MonoModder modder, MethodDefinition method); public delegate void MethodBodyRewriter(MonoModder modder, MethodBody body, Instruction instr, int instri); public delegate ModuleDefinition MissingDependencyResolver(MonoModder modder, ModuleDefinition main, string name, string fullName); public delegate void PostProcessor(MonoModder modder); public delegate void ModReadEventHandler(MonoModder modder, ModuleDefinition mod); public class RelinkMapEntry { public string Type; public string FindableID; public RelinkMapEntry() { } public RelinkMapEntry(string type, string findableID) { Type = type; FindableID = findableID; } } public enum DebugSymbolFormat { Auto, MDB, PDB } public class MonoModder : IDisposable { public static readonly bool IsMono = (object)Type.GetType("Mono.Runtime") != null; public static readonly Version Version = typeof(MonoModder).Assembly.GetName().Version; public Dictionary<string, object> SharedData = new Dictionary<string, object>(); public Dictionary<string, object> RelinkMap = new Dictionary<string, object>(); public Dictionary<string, ModuleDefinition> RelinkModuleMap = new Dictionary<string, ModuleDefinition>(); public HashSet<string> SkipList = new HashSet<string>(EqualityComparer<string>.Default); public Dictionary<string, IMetadataTokenProvider> RelinkMapCache = new Dictionary<string, IMetadataTokenProvider>(); public Dictionary<string, TypeReference> RelinkModuleMapCache = new Dictionary<string, TypeReference>(); public Dictionary<string, OpCode> ForceCallMap = new Dictionary<string, OpCode>(); public ModReadEventHandler OnReadMod; public PostProcessor PostProcessors; public Dictionary<string, Action<object, object[]>> CustomAttributeHandlers = new Dictionary<string, Action<object, object[]>> { { "MonoMod.MonoModPublic", delegate { } } }; public Dictionary<string, Action<object, object[]>> CustomMethodAttributeHandlers = new Dictionary<string, Action<object, object[]>>(); public MissingDependencyResolver MissingDependencyResolver; public MethodParser MethodParser; public MethodRewriter MethodRewriter; public MethodBodyRewriter MethodBodyRewriter; public Stream Input; public string InputPath; public Stream Output; public string OutputPath; public List<string> DependencyDirs = new List<string>(); public ModuleDefinition Module; public Dictionary<ModuleDefinition, List<ModuleDefinition>> DependencyMap = new Dictionary<ModuleDefinition, List<ModuleDefinition>>(); public Dictionary<string, ModuleDefinition> DependencyCache = new Dictionary<string, ModuleDefinition>(); public Func<ICustomAttributeProvider, TypeReference, bool> ShouldCleanupAttrib; public bool LogVerboseEnabled; public bool CleanupEnabled; public bool PublicEverything; public List<ModuleReference> Mods = new List<ModuleReference>(); public bool Strict; public bool MissingDependencyThrow; public bool RemovePatchReferences; public bool PreventInline; public bool? UpgradeMSCORLIB; public ReadingMode ReadingMode = (ReadingMode)1; public DebugSymbolFormat DebugSymbolOutputFormat; public int CurrentRID; protected IAssemblyResolver _assemblyResolver; protected ReaderParameters _readerParameters; protected WriterParameters _writerParameters; public bool GACEnabled; private string[] _GACPathsNone = new string[0]; protected string[] _GACPaths; protected MethodDefinition _mmOriginalCtor; protected MethodDefinition _mmOriginalNameCtor; protected MethodDefinition _mmAddedCtor; protected MethodDefinition _mmPatchCtor; public virtual IAssemblyResolver AssemblyResolver { get { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown if (_assemblyResolver == null) { DefaultAssemblyResolver val = new DefaultAssemblyResolver(); foreach (string dependencyDir in DependencyDirs) { ((BaseAssemblyResolver)val).AddSearchDirectory(dependencyDir); } _assemblyResolver = (IAssemblyResolver)(object)val; } return _assemblyResolver; } set { _assemblyResolver = value; } } public virtual ReaderParameters ReaderParameters { get { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown if (_readerParameters == null) { _readerParameters = new ReaderParameters(ReadingMode) { AssemblyResolver = AssemblyResolver, ReadSymbols = true }; } return _readerParameters; } set { _readerParameters = value; } } public virtual WriterParameters WriterParameters { get { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0067: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown if (_writerParameters == null) { bool flag = DebugSymbolOutputFormat == DebugSymbolFormat.PDB; bool flag2 = DebugSymbolOutputFormat == DebugSymbolFormat.MDB; if (DebugSymbolOutputFormat == DebugSymbolFormat.Auto) { if ((PlatformHelper.Current & 0x25) == 37) { flag = true; } else { flag2 = true; } } WriterParameters val = new WriterParameters { WriteSymbols = true }; object symbolWriterProvider; if (!flag) { if (!flag2) { symbolWriterProvider = null; } else { ISymbolWriterProvider val2 = (ISymbolWriterProvider)new MdbWriterProvider(); symbolWriterProvider = val2; } } else { ISymbolWriterProvider val2 = (ISymbolWriterProvider)new NativePdbWriterProvider(); symbolWriterProvider = val2; } val.SymbolWriterProvider = (ISymbolWriterProvider)symbolWriterProvider; _writerParameters = val; } return _writerParameters; } set { _writerParameters = value; } } public string[] GACPaths { get { if (!GACEnabled) { return _GACPathsNone; } if (_GACPaths != null) { return _GACPaths; } if (!IsMono) { string environmentVariable = Environment.GetEnvironmentVariable("windir"); if (string.IsNullOrEmpty(environmentVariable)) { return _GACPaths = _GACPathsNone; } environmentVariable = Path.Combine(environmentVariable, "Microsoft.NET"); environmentVariable = Path.Combine(environmentVariable, "assembly"); _GACPaths = new string[3] { Path.Combine(environmentVariable, "GAC_32"), Path.Combine(environmentVariable, "GAC_64"), Path.Combine(environmentVariable, "GAC_MSIL") }; } else { List<string> list = new List<string>(); string text = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)), "gac"); if (Directory.Exists(text)) { list.Add(text); } string environmentVariable2 = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX"); if (!string.IsNullOrEmpty(environmentVariable2)) { string[] array = environmentVariable2.Split(new char[1] { Path.PathSeparator }); foreach (string text2 in array) { if (!string.IsNullOrEmpty(text2)) { string path = text2; path = Path.Combine(path, "lib"); path = Path.Combine(path, "mono"); path = Path.Combine(path, "gac"); if (Directory.Exists(path) && !list.Contains(path)) { list.Add(path); } } } } _GACPaths = list.ToArray(); } return _GACPaths; } set { GACEnabled = true; _GACPaths = value; } } public MonoModder() { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) MethodParser = DefaultParser; MissingDependencyResolver = DefaultMissingDependencyResolver; PostProcessors = (PostProcessor)Delegate.Combine(PostProcessors, new PostProcessor(DefaultPostProcessor)); string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DEPDIRS"); if (!string.IsNullOrEmpty(environmentVariable)) { foreach (string item in from dir in environmentVariable.Split(new char[1] { Path.PathSeparator }) select dir.Trim()) { IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(item); } DependencyDirs.Add(item); } } LogVerboseEnabled = Environment.GetEnvironmentVariable("MONOMOD_LOG_VERBOSE") == "1"; CleanupEnabled = Environment.GetEnvironmentVariable("MONOMOD_CLEANUP") != "0"; PublicEverything = Environment.GetEnvironmentVariable("MONOMOD_PUBLIC_EVERYTHING") == "1"; PreventInline = Environment.GetEnvironmentVariable("MONOMOD_PREVENTINLINE") == "1"; Strict = Environment.GetEnvironmentVariable("MONOMOD_STRICT") == "1"; MissingDependencyThrow = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") != "0"; RemovePatchReferences = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_REMOVE_PATCH") != "0"; string environmentVariable2 = Environment.GetEnvironmentVariable("MONOMOD_DEBUG_FORMAT"); if (environmentVariable2 != null) { environmentVariable2 = environmentVariable2.ToLowerInvariant(); if (environmentVariable2 == "pdb") { DebugSymbolOutputFormat = DebugSymbolFormat.PDB; } else if (environmentVariable2 == "mdb") { DebugSymbolOutputFormat = DebugSymbolFormat.MDB; } } string environmentVariable3 = Environment.GetEnvironmentVariable("MONOMOD_MSCORLIB_UPGRADE"); UpgradeMSCORLIB = (string.IsNullOrEmpty(environmentVariable3) ? null : new bool?(environmentVariable3 != "0")); GACEnabled = Environment.GetEnvironmentVariable("MONOMOD_GAC_ENABLED") != "0"; MonoModRulesManager.Register(this); } public virtual void ClearCaches(bool all = false, bool shareable = false, bool moduleSpecific = false) { if (all || shareable) { foreach (KeyValuePair<string, ModuleDefinition> item in DependencyCache) { item.Value.Dispose(); } DependencyCache.Clear(); } if (all || moduleSpecific) { RelinkMapCache.Clear(); RelinkModuleMapCache.Clear(); } } public virtual void Dispose() { //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) ClearCaches(all: true); ModuleDefinition module = Module; if (module != null) { module.Dispose(); } Module = null; ((IDisposable)AssemblyResolver)?.Dispose(); AssemblyResolver = null; foreach (ModuleDefinition mod in Mods) { if ((int)mod != 0) { mod.Dispose(); } } foreach (List<ModuleDefinition> value in DependencyMap.Values) { foreach (ModuleDefinition item in value) { if (item != null) { item.Dispose(); } } } DependencyMap.Clear(); Input?.Dispose(); Output?.Dispose(); } public virtual void Log(object value) { Log(value.ToString()); } public virtual void Log(string text) { Console.Write("[MonoMod] "); Console.WriteLine(text); } public virtual void LogVerbose(object value) { if (LogVerboseEnabled) { Log(value); } } public virtual void LogVerbose(string text) { if (LogVerboseEnabled) { Log(text); } } private static ModuleDefinition _ReadModule(Stream input, ReaderParameters args) { if (args.ReadSymbols) { try { return ModuleDefinition.ReadModule(input, args); } catch { args.ReadSymbols = false; input.Seek(0L, SeekOrigin.Begin); } } return ModuleDefinition.ReadModule(input, args); } private static ModuleDefinition _ReadModule(string input, ReaderParameters args) { if (args.ReadSymbols) { try { return ModuleDefinition.ReadModule(input, args); } catch { args.ReadSymbols = false; } } return ModuleDefinition.ReadModule(input, args); } public virtual void Read() { if (Module != null) { return; } if (Input != null) { Log("Reading input stream into module."); Module = _ReadModule(Input, GenReaderParameters(mainModule: true)); } else if (InputPath != null) { Log("Reading input file into module."); IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(Path.GetDirectoryName(InputPath)); } DependencyDirs.Add(Path.GetDirectoryName(InputPath)); Module = _ReadModule(InputPath, GenReaderParameters(mainModule: true, InputPath)); } string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_MODS"); if (string.IsNullOrEmpty(environmentVariable)) { return; } foreach (string item in from path in environmentVariable.Split(new char[1] { Path.PathSeparator }) select path.Trim()) { ReadMod(item); } } public virtual void MapDependencies() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown foreach (ModuleDefinition mod in Mods) { ModuleDefinition main = mod; MapDependencies(main); } MapDependencies(Module); } public virtual void MapDependencies(ModuleDefinition main) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (DependencyMap.ContainsKey(main)) { return; } DependencyMap[main] = new List<ModuleDefinition>(); Enumerator<AssemblyNameReference> enumerator = main.AssemblyReferences.GetEnumerator(); try { while (enumerator.MoveNext()) { AssemblyNameReference current = enumerator.Current; MapDependency(main, current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void MapDependency(ModuleDefinition main, AssemblyNameReference depRef) { MapDependency(main, depRef.Name, depRef.FullName, depRef); } public virtual void MapDependency(ModuleDefinition main, string name, string fullName = null, AssemblyNameReference depRef = null) { if (!DependencyMap.TryGetValue(main, out var value)) { value = (DependencyMap[main] = new List<ModuleDefinition>()); } if (fullName != null && (DependencyCache.TryGetValue(fullName, out var value2) || DependencyCache.TryGetValue(fullName + " [RT:" + main.RuntimeVersion + "]", out value2))) { LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) from cache"); value.Add(value2); MapDependencies(value2); return; } if (DependencyCache.TryGetValue(name, out value2) || DependencyCache.TryGetValue(name + " [RT:" + main.RuntimeVersion + "]", out value2)) { LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " (" + name + ") from cache"); value.Add(value2); MapDependencies(value2); return; } string text = Path.GetExtension(name).ToLowerInvariant(); bool flag = text == "pdb" || text == "mdb"; string text2 = null; foreach (string dependencyDir in DependencyDirs) { text2 = Path.Combine(dependencyDir, name + ".dll"); if (!File.Exists(text2)) { text2 = Path.Combine(dependencyDir, name + ".exe"); } if (!File.Exists(text2) && !flag) { text2 = Path.Combine(dependencyDir, name); } if (File.Exists(text2)) { break; } text2 = null; } if (text2 == null && depRef != null) { try { AssemblyDefinition obj = AssemblyResolver.Resolve(depRef); value2 = ((obj != null) ? obj.MainModule : null); } catch { } if (value2 != null) { text2 = value2.FileName; } } if (text2 == null) { string[] gACPaths = GACPaths; for (int i = 0; i < gACPaths.Length; i++) { text2 = Path.Combine(gACPaths[i], name); if (Directory.Exists(text2)) { string[] directories = Directory.GetDirectories(text2); int num = 0; int num2 = 0; for (int j = 0; j < directories.Length; j++) { string text3 = directories[j]; if (text3.StartsWith(text2)) { text3 = text3.Substring(text2.Length + 1); } Match match = Regex.Match(text3, "\\d+"); if (match.Success) { int num3 = int.Parse(match.Value); if (num3 > num) { num = num3; num2 = j; } } } text2 = Path.Combine(directories[num2], name + ".dll"); break; } text2 = null; } } if (text2 == null) { try { AssemblyDefinition obj3 = AssemblyResolver.Resolve(AssemblyNameReference.Parse(fullName ?? name)); value2 = ((obj3 != null) ? obj3.MainModule : null); } catch { } if (value2 != null) { text2 = value2.FileName; } } if (value2 == null) { if (text2 != null && File.Exists(text2)) { value2 = _ReadModule(text2, GenReaderParameters(mainModule: false, text2)); } else if ((value2 = MissingDependencyResolver?.Invoke(this, main, name, fullName)) == null) { return; } } LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) loaded"); value.Add(value2); if (fullName == null) { fullName = value2.Assembly.FullName; } DependencyCache[fullName] = value2; DependencyCache[name] = value2; MapDependencies(value2); } public virtual ModuleDefinition DefaultMissingDependencyResolver(MonoModder mod, ModuleDefinition main, string name, string fullName) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (MissingDependencyThrow && Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") == "0") { Log("[MissingDependencyResolver] [WARNING] Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW"); MissingDependencyThrow = false; } if (MissingDependencyThrow || Strict) { throw new RelinkTargetNotFoundException("MonoMod cannot map dependency " + ((ModuleReference)main).Name + " -> ((" + fullName + "), (" + name + ")) - not found", (IMetadataTokenProvider)(object)main, (IMetadataTokenProvider)null); } return null; } public virtual void Write(Stream output = null, string outputPath = null) { output = output ?? Output; outputPath = outputPath ?? OutputPath; PatchRefsInType(PatchWasHere()); if (output != null) { Log("[Write] Writing modded module into output stream."); Module.Write(output, WriterParameters); } else { Log("[Write] Writing modded module into output file."); Module.Write(outputPath, WriterParameters); } } public virtual ReaderParameters GenReaderParameters(bool mainModule, string path = null) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown ReaderParameters readerParameters = ReaderParameters; ReaderParameters val = new ReaderParameters(readerParameters.ReadingMode); val.AssemblyResolver = readerParameters.AssemblyResolver; val.MetadataResolver = readerParameters.MetadataResolver; val.InMemory = readerParameters.InMemory; val.MetadataImporterProvider = readerParameters.MetadataImporterProvider; val.ReflectionImporterProvider = readerParameters.ReflectionImporterProvider; val.ThrowIfSymbolsAreNotMatching = readerParameters.ThrowIfSymbolsAreNotMatching; val.ApplyWindowsRuntimeProjections = readerParameters.ApplyWindowsRuntimeProjections; val.SymbolStream = readerParameters.SymbolStream; val.SymbolReaderProvider = readerParameters.SymbolReaderProvider; val.ReadSymbols = readerParameters.ReadSymbols; if (path != null && !File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb"))) { val.ReadSymbols = false; } return val; } public virtual void ReadMod(string path) { if (Directory.Exists(path)) { Log("[ReadMod] Loading mod dir: " + path); string text = ((ModuleReference)Module).Name.Substring(0, ((ModuleReference)Module).Name.Length - 3); string value = text.Replace(" ", ""); if (!DependencyDirs.Contains(path)) { IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(path); } DependencyDirs.Add(path); } string[] files = Directory.GetFiles(path); foreach (string text2 in files) { if ((Path.GetFileName(text2).StartsWith(text) || Path.GetFileName(text2).StartsWith(value)) && text2.ToLower().EndsWith(".mm.dll")) { ReadMod(text2); } } return; } Log("[ReadMod] Loading mod: " + path); ModuleDefinition val = _ReadModule(path, GenReaderParameters(mainModule: false, path)); string directoryName = Path.GetDirectoryName(path); if (!DependencyDirs.Contains(directoryName)) { IAssemblyResolver assemblyResolver2 = AssemblyResolver; IAssemblyResolver obj2 = ((assemblyResolver2 is BaseAssemblyResolver) ? assemblyResolver2 : null); if (obj2 != null) { ((BaseAssemblyResolver)obj2).AddSearchDirectory(directoryName); } DependencyDirs.Add(directoryName); } Mods.Add((ModuleReference)(object)val); OnReadMod?.Invoke(this, val); } public virtual void ReadMod(Stream stream) { Log($"[ReadMod] Loading mod: stream#{(uint)stream.GetHashCode()}"); ModuleDefinition val = _ReadModule(stream, GenReaderParameters(mainModule: false)); Mods.Add((ModuleReference)(object)val); OnReadMod?.Invoke(this, val); } public virtual void ParseRules(ModuleDefinition mod) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) TypeDefinition type = mod.GetType("MonoMod.MonoModRules"); Type rulesTypeMMILRT = null; if (type != null) { rulesTypeMMILRT = this.ExecuteRules(type); mod.Types.Remove(type); } Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; ParseRulesInType(current, rulesTypeMMILRT); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void ParseRulesInType(TypeDefinition type, Type rulesTypeMMILRT = null) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0431: Unknown result type (might be due to invalid IL or missing references) //IL_0436: Unknown result type (might be due to invalid IL or missing references) Extensions.GetPatchFullName((MemberReference)(object)type); if (!MatchingConditionals((ICustomAttributeProvider)(object)type, Module)) { return; } CustomAttribute customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomAttributeAttribute"); CustomAttributeArgument val; if (customAttribute != null) { val = customAttribute.ConstructorArguments[0]; MethodInfo method2 = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value); CustomAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { method2.Invoke(self, args); }; } customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomMethodAttributeAttribute"); if (customAttribute != null) { val = customAttribute.ConstructorArguments[0]; MethodInfo method = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 2 && Extensions.IsCompatible(parameters[0].ParameterType, typeof(ILContext))) { CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown ILContext il = new ILContext((MethodDefinition)args[0]); il.Invoke((Manipulator)delegate { method.Invoke(self, new object[2] { il, args[1] }); }); if (il.IsReadOnly) { il.Dispose(); } }; } else { CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { method.Invoke(self, args); }; } } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)type, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)type, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)type, val2); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) { return; } Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current, val2); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCall")) { ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Call; } else if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCallvirt")) { ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Callvirt; } } } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<FieldDefinition> enumerator2 = type.Fields.GetEnumerator(); try { while (enumerator2.MoveNext()) { FieldDefinition current2 = enumerator2.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current2, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current2, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current2, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current2, val2); } } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<PropertyDefinition> enumerator3 = type.Properties.GetEnumerator(); try { while (enumerator3.MoveNext()) { PropertyDefinition current3 = enumerator3.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current3, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current3, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current3, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current3, val2); } } } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<TypeDefinition> enumerator4 = type.NestedTypes.GetEnumerator(); try { while (enumerator4.MoveNext()) { TypeDefinition current4 = enumerator4.Current; ParseRulesInType(current4, rulesTypeMMILRT); } } finally { ((IDisposable)enumerator4).Dispose(); } } public virtual void ParseLinkFrom(MemberReference target, CustomAttribute hook) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_003c: 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_005a: Expected O, but got Unknown //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = hook.ConstructorArguments[0]; string key = (string)((CustomAttributeArgument)(ref val)).Value; object value; if (target is TypeReference) { value = Extensions.GetPatchFullName((MemberReference)(TypeReference)target); } else if (target is MethodReference) { value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(MethodReference)target).DeclaringType), Extensions.GetID((MethodReference)target, (string)null, (string)null, false, false)); } else if (target is FieldReference) { value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(FieldReference)target).DeclaringType), ((MemberReference)(FieldReference)target).Name); } else { if (!(target is PropertyReference)) { return; } value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(PropertyReference)target).DeclaringType), ((MemberReference)(PropertyReference)target).Name); } RelinkMap[key] = value; } public virtual void ParseLinkTo(MemberReference from, CustomAttribute hook) { //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_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) MemberReference obj = ((from is MethodReference) ? from : null); string key = ((obj != null) ? Extensions.GetID((MethodReference)(object)obj, (string)null, (string)null, true, false) : null) ?? Extensions.GetPatchFullName(from); CustomAttributeArgument val; if (hook.ConstructorArguments.Count == 1) { Dictionary<string, object> relinkMap = RelinkMap; val = hook.ConstructorArguments[0]; relinkMap[key] = (string)((CustomAttributeArgument)(ref val)).Value; } else { Dictionary<string, object> relinkMap2 = RelinkMap; val = hook.ConstructorArguments[0]; string type = (string)((CustomAttributeArgument)(ref val)).Value; val = hook.ConstructorArguments[1]; relinkMap2[key] = new RelinkMapEntry(type, (string)((CustomAttributeArgument)(ref val)).Value); } } public virtual void RunCustomAttributeHandlers(ICustomAttributeProvider cap) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown if (!cap.HasCustomAttributes) { return; } CustomAttribute[] array = cap.CustomAttributes.ToArray(); foreach (CustomAttribute val in array) { if (CustomAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out var value)) { value?.Invoke(null, new object[2] { cap, val }); } if (cap is MethodReference && CustomMethodAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out value)) { value?.Invoke(null, new object[2] { (object)(MethodDefinition)cap, val }); } } } public virtual void AutoPatch() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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 //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Expected O, but got Unknown Log("[AutoPatch] Parsing rules in loaded mods"); foreach (ModuleDefinition mod4 in Mods) { ModuleDefinition mod = mod4; ParseRules(mod); } Log("[AutoPatch] PrePatch pass"); foreach (ModuleDefinition mod5 in Mods) { ModuleDefinition mod2 = mod5; PrePatchModule(mod2); } Log("[AutoPatch] Patch pass"); foreach (ModuleDefinition mod6 in Mods) { ModuleDefinition mod3 = mod6; PatchModule(mod3); } Log("[AutoPatch] PatchRefs pass"); PatchRefs(); if (PostProcessors != null) { Delegate[] invocationList = PostProcessors.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { Log($"[PostProcessor] PostProcessor pass #{i + 1}"); ((PostProcessor)invocationList[i])?.Invoke(this); } } } public virtual IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { //IL_0027: 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) try { return PostRelinker(MainRelinker(mtp, context) ?? mtp, context) ?? throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context); } catch (Exception ex) { throw new RelinkFailedException((string)null, ex, mtp, (IMetadataTokenProvider)(object)context); } } public virtual IMetadataTokenProvider MainRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null); if (val != null) { if (((MemberReference)val).Module == Module) { return (IMetadataTokenProvider)(object)val; } if (((MemberReference)val).Module != null && !Mods.Contains((ModuleReference)(object)((MemberReference)val).Module)) { return (IMetadataTokenProvider)(object)Module.ImportReference(val); } val = (TypeReference)(((object)Extensions.SafeResolve(val)) ?? ((object)val)); TypeReference val2 = FindTypeDeep(Extensions.GetPatchFullName((MemberReference)(object)val)); if (val2 == null) { if (RelinkMap.ContainsKey(((MemberReference)val).FullName)) { return null; } throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context); } return (IMetadataTokenProvider)(object)Module.ImportReference(val2); } if (mtp is FieldReference || mtp is MethodReference || mtp is PropertyReference || mtp is EventReference) { return Extensions.ImportReference(Module, mtp); } throw new InvalidOperationException($"MonoMod default relinker can't handle metadata token providers of the type {((object)mtp).GetType()}"); } public virtual IMetadataTokenProvider PostRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { return ResolveRelinkTarget(mtp) ?? mtp; } public virtual IMetadataTokenProvider ResolveRelinkTarget(IMetadataTokenProvider mtp, bool relink = true, bool relinkModule = true) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_004b: 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_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Expected O, but got Unknown //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Expected O, but got Unknown //IL_023c: Expected O, but got Unknown //IL_02d2: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: 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_01b3: Expected O, but got Unknown //IL_0193: Unknown result type (might be due to invalid IL or missing references) string text = null; string text2; if (mtp is TypeReference) { text2 = ((MemberReference)(TypeReference)mtp).FullName; } else if (mtp is MethodReference) { text2 = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, false); text = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, true); } else if (mtp is FieldReference) { text2 = ((MemberReference)(FieldReference)mtp).FullName; } else { if (!(mtp is PropertyReference)) { return null; } text2 = ((MemberReference)(PropertyReference)mtp).FullName; } if (RelinkMapCache.TryGetValue(text2, out var value)) { return value; } if (relink && (RelinkMap.TryGetValue(text2, out var value2) || (text != null && RelinkMap.TryGetValue(text, out value2)))) { if (value2 is IMetadataTokenProvider) { return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2); } if (value2 is RelinkMapEntry) { string type = ((RelinkMapEntry)value2).Type; string findableID = ((RelinkMapEntry)value2).FindableID; TypeReference obj = FindTypeDeep(type); TypeDefinition val2 = ((obj != null) ? Extensions.SafeResolve(obj) : null); if (val2 == null) { return RelinkMapCache[text2] = ResolveRelinkTarget(mtp, relink: false, relinkModule); } value2 = Extensions.FindMethod(val2, findableID, true) ?? ((object)Extensions.FindField(val2, findableID)) ?? ((object)(Extensions.FindProperty(val2, findableID) ?? null)); if (value2 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} ({1}, {2}) (remap: {3})", "MonoMod relinker failed finding", type, findableID, mtp), mtp, (IMetadataTokenProvider)null); } return null; } return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2); } if (value2 is string && mtp is TypeReference) { IMetadataTokenProvider val5 = (IMetadataTokenProvider)(object)FindTypeDeep((string)value2); if (val5 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", value2, mtp), mtp, (IMetadataTokenProvider)null); } return null; } value2 = Extensions.ImportReference(Module, ResolveRelinkTarget(val5, relink: false, relinkModule) ?? val5); } if (value2 is IMetadataTokenProvider) { Dictionary<string, IMetadataTokenProvider> relinkMapCache = RelinkMapCache; string key = text2; IMetadataTokenProvider val6 = (IMetadataTokenProvider)value2; IMetadataTokenProvider result = val6; relinkMapCache[key] = val6; return result; } throw new InvalidOperationException($"MonoMod doesn't support RelinkMap value of type {value2.GetType()} (remap: {mtp})"); } if (relinkModule && mtp is TypeReference) { if (RelinkModuleMapCache.TryGetValue(text2, out var value3)) { return (IMetadataTokenProvider)(object)value3; } value3 = (TypeReference)mtp; if (RelinkModuleMap.TryGetValue(value3.Scope.Name, out var value4)) { TypeReference type2 = (TypeReference)(object)value4.GetType(((MemberReference)value3).FullName); if (type2 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", ((MemberReference)value3).FullName, mtp), mtp, (IMetadataTokenProvider)null); } return null; } return (IMetadataTokenProvider)(object)(RelinkModuleMapCache[text2] = Module.ImportReference(type2)); } return (IMetadataTokenProvider)(object)Module.ImportReference(value3); } return null; } public virtual bool DefaultParser(MonoModder mod, MethodBody body, Instruction instr, ref int instri) { return true; } public virtual TypeReference FindType(string name) { return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, false); } public virtual TypeReference FindType(string name, bool runtimeName) { return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, runtimeName); } protected virtual TypeReference FindType(ModuleDefinition main, string fullName, Stack<ModuleDefinition> crawled) { TypeReference type; if ((type = main.GetType(fullName, false)) != null) { return type; } if (fullName.StartsWith("<PrivateImplementationDetails>/")) { return null; } if (crawled.Contains(main)) { return null; } crawled.Push(main); foreach (ModuleDefinition item in DependencyMap[main]) { if ((!RemovePatchReferences || !((AssemblyNameReference)item.Assembly.Name).Name.EndsWith(".mm")) && (type = FindType(item, fullName, crawled)) != null) { return type; } } return null; } public virtual TypeReference FindTypeDeep(string name) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown TypeReference val = FindType(name, runtimeName: false); if (val != null) { return val; } Stack<ModuleDefinition> crawled = new Stack<ModuleDefinition>(); val = null; foreach (ModuleDefinition mod in Mods) { ModuleDefinition key = mod; foreach (ModuleDefinition item in DependencyMap[key]) { if ((val = FindType(item, name, crawled)) != null) { IMetadataScope scope = val.Scope; AssemblyNameReference dllRef = (AssemblyNameReference)(object)((scope is AssemblyNameReference) ? scope : null); if (dllRef != null && !((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference n) => n.Name == dllRef.Name)) { Module.AssemblyReferences.Add(dllRef); } return Module.ImportReference(val); } } } return null; } public virtual void PrePatchModule(ModuleDefinition mod) { //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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: 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) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Expected O, but got Unknown Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PrePatchType(current); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<ModuleReference> enumerator2 = mod.ModuleReferences.GetEnumerator(); try { while (enumerator2.MoveNext()) { ModuleReference current2 = enumerator2.Current; if (!Module.ModuleReferences.Contains(current2)) { Module.ModuleReferences.Add(current2); } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<Resource> enumerator3 = mod.Resources.GetEnumerator(); try { while (enumerator3.MoveNext()) { Resource current3 = enumerator3.Current; if (current3 is EmbeddedResource) { Module.Resources.Add((Resource)new EmbeddedResource(current3.Name.StartsWith(((AssemblyNameReference)mod.Assembly.Name).Name) ? (((AssemblyNameReference)Module.Assembly.Name).Name + current3.Name.Substring(((AssemblyNameReference)mod.Assembly.Name).Name.Length)) : current3.Name, current3.Attributes, ((EmbeddedResource)current3).GetResourceData())); } } } finally { ((IDisposable)enumerator3).Dispose(); } } public virtual void PrePatchType(TypeDefinition type, bool forceAdd = false) { //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: 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_0161: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Expected O, but got Unknown //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Expected O, but got Unknown string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type); if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module) || (((MemberReference)type).FullName == "MonoMod.MonoModRules" && !forceAdd)) { return; } TypeReference val = (forceAdd ? null : Module.GetType(patchFullName, false)); TypeDefinition val2 = ((val != null) ? Extensions.SafeResolve(val) : null); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModReplace") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove")) { if (val2 != null) { if (val2.DeclaringType == null) { Module.Types.Remove(val2); } else { val2.DeclaringType.NestedTypes.Remove(val2); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove")) { return; } } else if (val != null) { PrePatchNested(type); return; } LogVerbose("[PrePatchType] Adding " + patchFullName + " to the target module."); TypeDefinition val3 = new TypeDefinition(((TypeReference)type).Namespace, ((MemberReference)type).Name, type.Attributes, type.BaseType); Enumerator<GenericParameter> enumerator = ((TypeReference)type).GenericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { GenericParameter current = enumerator.Current; ((TypeReference)val3).GenericParameters.Add(Extensions.Clone(current)); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<InterfaceImplementation> enumerator2 = type.Interfaces.GetEnumerator(); try { while (enumerator2.MoveNext()) { InterfaceImplementation current2 = enumerator2.Current; val3.Interfaces.Add(current2); } } finally { ((IDisposable)enumerator2).Dispose(); } val3.ClassSize = type.ClassSize; if (type.DeclaringType != null) { val3.DeclaringType = Extensions.Relink((TypeReference)(object)type.DeclaringType, new Relinker(Relinker), (IGenericParameterProvider)(object)val3).Resolve(); val3.DeclaringType.NestedTypes.Add(val3); } else { Module.Types.Add(val3); } val3.PackingSize = type.PackingSize; Extensions.AddRange<SecurityDeclaration>(val3.SecurityDeclarations, (IEnumerable<SecurityDeclaration>)type.SecurityDeclarations); val3.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val = (TypeReference)(object)val3; PrePatchNested(type); } protected virtual void PrePatchNested(TypeDefinition type) { for (int i = 0; i < type.NestedTypes.Count; i++) { PrePatchType(type.NestedTypes[i]); } } public virtual void PatchModule(ModuleDefinition mod) { //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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; if ((((TypeReference)current).Namespace == "MonoMod" || ((TypeReference)current).Namespace.StartsWith("MonoMod.")) && ((MemberReference)current.BaseType).FullName == "System.Attribute") { PatchType(current); } } } finally { ((IDisposable)enumerator).Dispose(); } enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current2 = enumerator.Current; if ((!(((TypeReference)current2).Namespace == "MonoMod") && !((TypeReference)current2).Namespace.StartsWith("MonoMod.")) || !(((MemberReference)current2.BaseType).FullName == "System.Attribute")) { PatchType(current2); } } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchType(TypeDefinition type) { //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_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type); TypeReference type2 = Module.GetType(patchFullName, false); if (type2 == null) { return; } TypeDefinition val = ((type2 != null) ? Extensions.SafeResolve(type2) : null); Enumerator<CustomAttribute> enumerator; if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module)) { if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore") && val != null) { enumerator = type.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } PatchNested(type); return; } if (patchFullName == ((MemberReference)type).FullName) { LogVerbose("[PatchType] Patching type " + patchFullName); } else { LogVerbose("[PatchType] Patching type " + patchFullName + " (prefixed: " + ((MemberReference)type).FullName + ")"); } enumerator = type.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current2 = enumerator.Current; if (!Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)val, ((MemberReference)current2.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current2)); } } } finally { ((IDisposable)enumerator).Dispose(); } HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>(); Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator(); try { while (enumerator2.MoveNext()) { PropertyDefinition current3 = enumerator2.Current; PatchProperty(val, current3, hashSet); } } finally { ((IDisposable)enumerator2).Dispose(); } HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>(); Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator(); try { while (enumerator3.MoveNext()) { EventDefinition current4 = enumerator3.Current; PatchEvent(val, current4, hashSet2); } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator(); try { while (enumerator4.MoveNext()) { MethodDefinition current5 = enumerator4.Current; if (!hashSet.Contains(current5) && !hashSet2.Contains(current5)) { PatchMethod(val, current5); } } } finally { ((IDisposable)enumerator4).Dispose(); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModEnumReplace")) { int num = 0; while (num < val.Fields.Count) { if (((MemberReference)val.Fields[num]).Name == "value__") { num++; } else { val.Fields.RemoveAt(num); } } } Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator(); try { while (enumerator5.MoveNext()) { FieldDefinition current6 = enumerator5.Current; PatchField(val, current6); } } finally { ((IDisposable)enumerator5).Dispose(); } PatchNested(type); } protected virtual void PatchNested(TypeDefinition type) { for (int i = 0; i < type.NestedTypes.Count; i++) { PatchType(type.NestedTypes[i]); } } public virtual void PatchProperty(TypeDefinition targetType, PropertyDefinition prop, HashSet<MethodDefinition> propMethods = null) { //IL_006e: 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_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Expected O, but got Unknown //IL_022b: Expected O, but got Unknown //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Expected O, but got Unknown //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Expected O, but got Unknown //IL_02b5: Expected O, but got Unknown //IL_0363: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Unknown result type (might be due to invalid IL or missing references) if (!MatchingConditionals((ICustomAttributeProvider)(object)prop, Module)) { return; } ((MemberReference)prop).Name = Extensions.GetPatchName((MemberReference)(object)prop); PropertyDefinition val = Extensions.FindProperty(targetType, ((MemberReference)prop).Name); string text = "<" + ((MemberReference)prop).Name + ">__BackingField"; FieldDefinition val2 = Extensions.FindField(prop.DeclaringType, text); FieldDefinition val3 = Extensions.FindField(targetType, text); Enumerator<CustomAttribute> enumerator; Enumerator<MethodDefinition> enumerator2; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModIgnore")) { if (val != null) { enumerator = prop.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 != null) { val2.DeclaringType.Fields.Remove(val2); } if (prop.GetMethod != null) { propMethods?.Add(prop.GetMethod); } if (prop.SetMethod != null) { propMethods?.Add(prop.SetMethod); } enumerator2 = prop.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current2 = enumerator2.Current; propMethods?.Add(current2); } return; } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModReplace")) { if (val != null) { targetType.Properties.Remove(val); if (val3 != null) { targetType.Fields.Remove(val3); } if (val.GetMethod != null) { targetType.Methods.Remove(val.GetMethod); } if (val.SetMethod != null) { targetType.Methods.Remove(val.SetMethod); } enumerator2 = val.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current3 = enumerator2.Current; targetType.Methods.Remove(current3); } } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove")) { return; } } if (val == null) { PropertyDefinition val4 = new PropertyDefinition(((MemberReference)prop).Name, prop.Attributes, ((PropertyReference)prop).PropertyType); val = val4; PropertyDefinition val5 = val4; val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); Enumerator<ParameterDefinition> enumerator3 = ((PropertyReference)prop).Parameters.GetEnumerator(); try { while (enumerator3.MoveNext()) { ParameterDefinition current4 = enumerator3.Current; ((PropertyReference)val5).Parameters.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator3).Dispose(); } val5.DeclaringType = targetType; targetType.Properties.Add(val5); if (val2 != null) { FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType); val3 = val6; FieldDefinition val7 = val6; targetType.Fields.Add(val7); } } enumerator = prop.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current5 = enumerator.Current; val.CustomAttributes.Add(Extensions.Clone(current5)); } } finally { ((IDisposable)enumerator).Dispose(); } MethodDefinition getMethod = prop.GetMethod; MethodDefinition getMethod2; if (getMethod != null && (getMethod2 = PatchMethod(targetType, getMethod)) != null) { val.GetMethod = getMethod2; propMethods?.Add(getMethod); } MethodDefinition setMethod = prop.SetMethod; if (setMethod != null && (getMethod2 = PatchMethod(targetType, setMethod)) != null) { val.SetMethod = getMethod2; propMethods?.Add(setMethod); } enumerator2 = prop.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current6 = enumerator2.Current; if ((getMethod2 = PatchMethod(targetType, current6)) != null) { val.OtherMethods.Add(getMethod2); propMethods?.Add(current6); } } } finally { ((IDisposable)enumerator2).Dispose(); } } public virtual void PatchEvent(TypeDefinition targetType, EventDefinition srcEvent, HashSet<MethodDefinition> propMethods = null) { //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_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Expected O, but got Unknown //IL_0252: Expected O, but got Unknown //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Expected O, but got Unknown //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) ((MemberReference)srcEvent).Name = Extensions.GetPatchName((MemberReference)(object)srcEvent); EventDefinition val = Extensions.FindEvent(targetType, ((MemberReference)srcEvent).Name); string text = "<" + ((MemberReference)srcEvent).Name + ">__BackingField"; FieldDefinition val2 = Extensions.FindField(srcEvent.DeclaringType, text); FieldDefinition val3 = Extensions.FindField(targetType, text); Enumerator<CustomAttribute> enumerator; Enumerator<MethodDefinition> enumerator2; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModIgnore")) { if (val != null) { enumerator = srcEvent.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 != null) { val2.DeclaringType.Fields.Remove(val2); } if (srcEvent.AddMethod != null) { propMethods?.Add(srcEvent.AddMethod); } if (srcEvent.RemoveMethod != null) { propMethods?.Add(srcEvent.RemoveMethod); } if (srcEvent.InvokeMethod != null) { propMethods?.Add(srcEvent.InvokeMethod); } enumerator2 = srcEvent.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current2 = enumerator2.Current; propMethods?.Add(current2); } return; } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModReplace")) { if (val != null) { targetType.Events.Remove(val); if (val3 != null) { targetType.Fields.Remove(val3); } if (val.AddMethod != null) { targetType.Methods.Remove(val.AddMethod); } if (val.RemoveMethod != null) { targetType.Methods.Remove(val.RemoveMethod); } if (val.InvokeMethod != null) { targetType.Methods.Remove(val.InvokeMethod); } if (val.OtherMethods != null) { enumerator2 = val.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current3 = enumerator2.Current; targetType.Methods.Remove(current3); } } finally { ((IDisposable)enumerator2).Dispose(); } } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove")) { return; } } if (val == null) { EventDefinition val4 = new EventDefinition(((MemberReference)srcEvent).Name, srcEvent.Attributes, ((EventReference)srcEvent).EventType); val = val4; EventDefinition val5 = val4; val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val5.DeclaringType = targetType; targetType.Events.Add(val5); if (val2 != null) { FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType); targetType.Fields.Add(val6); } } enumerator = srcEvent.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current4 = enumerator.Current; val.CustomAttributes.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator).Dispose(); } MethodDefinition addMethod = srcEvent.AddMethod; MethodDefinition addMethod2; if (addMethod != null && (addMethod2 = PatchMethod(targetType, addMethod)) != null) { val.AddMethod = addMethod2; propMethods?.Add(addMethod); } MethodDefinition removeMethod = srcEvent.RemoveMethod; if (removeMethod != null && (addMethod2 = PatchMethod(targetType, removeMethod)) != null) { val.RemoveMethod = addMethod2; propMethods?.Add(removeMethod); } MethodDefinition invokeMethod = srcEvent.InvokeMethod; if (invokeMethod != null && (addMethod2 = PatchMethod(targetType, invokeMethod)) != null) { val.InvokeMethod = addMethod2; propMethods?.Add(invokeMethod); } enumerator2 = srcEvent.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current5 = enumerator2.Current; if ((addMethod2 = PatchMethod(targetType, current5)) != null) { val.OtherMethods.Add(addMethod2); propMethods?.Add(current5); } } } finally { ((IDisposable)enumerator2).Dispose(); } } public virtual void PatchField(TypeDefinition targetType, FieldDefinition field) { //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_011b: 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_012c: Expected O, but got Unknown //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)field.DeclaringType); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModNoNew") || SkipList.Contains(patchFullName + "::" + ((MemberReference)field).Name) || !MatchingConditionals((ICustomAttributeProvider)(object)field, Module)) { return; } ((MemberReference)field).Name = Extensions.GetPatchName((MemberReference)(object)field); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModReplace")) { FieldDefinition val = Extensions.FindField(targetType, ((MemberReference)field).Name); if (val != null) { targetType.Fields.Remove(val); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove")) { return; } } FieldDefinition val2 = Extensions.FindField(targetType, ((MemberReference)field).Name); Enumerator<CustomAttribute> enumerator; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModIgnore") && val2 != null) { enumerator = field.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val2.CustomAttributes.Add(Extensions.Clone(current)); } } return; } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 == null) { val2 = new FieldDefinition(((MemberReference)field).Name, field.Attributes, ((FieldReference)field).FieldType); val2.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val2.InitialValue = field.InitialValue; if (field.HasConstant) { val2.Constant = field.Constant; } targetType.Fields.Add(val2); } enumerator = field.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current2 = enumerator.Current; val2.CustomAttributes.Add(Extensions.Clone(current2)); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual MethodDefinition PatchMethod(TypeDefinition targetType, MethodDefinition method) { //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Expected O, but got Unknown //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0255: 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_0268: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_049f: Unknown result type (might be due to invalid IL or missing references) //IL_04b4: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Expected O, but got Unknown //IL_04c3: Unknown result type (might be due to invalid IL or missing references) //IL_04d0: Unknown result type (might be due to invalid IL or missing references) //IL_04f7: Unknown result type (might be due to invalid IL or missing references) //IL_0504: Unknown result type (might be due to invalid IL or missing references) //IL_0511: Unknown result type (might be due to invalid IL or missing references) //IL_0564: Unknown result type (might be due to invalid IL or missing references) //IL_0569: Unknown result type (might be due to invalid IL or missing references) //IL_0453: Unknown result type (might be due to invalid IL or missing references) //IL_0458: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Expected O, but got Unknown //IL_05a8: Unknown result type (might be due to invalid IL or missing references) //IL_05ad: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_0305: Unknown result type (might be due to invalid IL or missing references) //IL_069a: Unknown result type (might be due to invalid IL or missing references) //IL_06a1: Expected O, but got Unknown //IL_06be: Unknown result type (might be due to invalid IL or missing references) //IL_05ec: Unknown result type (might be due to invalid IL or missing references) //IL_05f1: Unknown result type (might be due to invalid IL or missing references) //IL_0630: Unknown result type (might be due to invalid IL or missing references) //IL_0635: Unknown result type (might be due to invalid IL or missing references) //IL_0676: Unknown result type (might be due to invalid IL or missing references) //IL_0680: Expected O, but got Unknown if (((MemberReference)method).Name.StartsWith("orig_") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginal")) { return null; } if (!AllowedSpecialName(method, targetType) || !MatchingConditionals((ICustomAttributeProvider)(object)method, Module)) { return null; } string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)targetType); if (SkipList.Contains(Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false))) { return null; } ((MemberReference)method).Name = Extensions.GetPatchName((MemberReference)(object)method); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor")) { if (!method.IsSpecialName && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginalName")) { CustomAttribute val = new CustomAttribute(GetMonoModOriginalNameCtor()); val.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)("orig_" + ((MemberReference)method).Name))); method.CustomAttributes.Add(val); } ((MemberReference)method).Name = (method.IsStatic ? ".cctor" : ".ctor"); method.IsSpecialName = true; method.IsRuntimeSpecialName = true; } MethodDefinition val2 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false), true); MethodDefinition obj = method; string text = patchFullName; MethodDefinition val3 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)obj, method.GetOriginalName(), text, true, false), true); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModIgnore")) { if (val2 != null) { Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val2.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } return null; } if (val2 == null && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModNoNew")) { return null; } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModRemove")) { if (val2 != null) { targetType.Methods.Remove(val2); } return null; } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModReplace")) { if (val2 != null) { val2.CustomAttributes.Clear(); val2.Attributes = method.Attributes; val2.IsPInvokeImpl = method.IsPInvokeImpl; val2.ImplAttributes = method.ImplAttributes; } } else if (val2 != null && val3 == null) { val3 = Extensions.Clone(val2, (MethodDefinition)null); ((MemberReference)val3).Name = method.GetOriginalName(); val3.Attributes = (MethodAttributes)(val2.Attributes & 0xF7FF & 0xEFFF); ((MemberReference)val3).MetadataToken = GetMetadataToken((TokenType)100663296); val3.IsVirtual = false; val3.Overrides.Clear(); Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodReference current2 = enumerator2.Current; val3.Overrides.Add(current2); } } finally { ((IDisposable)enumerator2).Dispose(); } val3.CustomAttributes.Add(new CustomAttribute(GetMonoModOriginalCtor())); MethodDefinition val4 = Extensions.FindMethod(method.DeclaringType, Extensions.GetID((MethodReference)(object)method, method.GetOriginalName(), (string)null, true, false), true); if (val4 != null) { Enumerator<CustomAttribute> enumerator = val4.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current3 = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName)) { val3.CustomAttributes.Add(Extensions.Clone(current3)); } } } finally { ((IDisposable)enumerator).Dispose(); } } targetType.Methods.Add(val3); } if (val3 != null && method.IsConstructor && method.IsStatic && method.HasBody && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor")) { Collection<Instruction> instructions = method.Body.Instructions; ILProcessor iLProcessor = method.Body.GetILProcessor(); iLProcessor.InsertBefore(instructions[instructions.Count - 1], iLProcessor.Create(OpCodes.Call, (MethodReference)(object)val3)); } if (val2 != null) { val2.Body = Extensions.Clone(method.Body, val2); val2.IsManaged = method.IsManaged; val2.IsIL = method.IsIL; val2.IsNative = method.IsNative; val2.PInvokeInfo = method.PInvokeInfo; val2.IsPreserveSig = method.IsPreserveSig; val2.IsInternalCall = method.IsInternalCall; val2.IsPInvokeImpl = method.IsPInvokeImpl; Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current4 = enumerator.Current; val2.CustomAttributes.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator).Dispose(); } method = val2; } else { MethodDefinition val5 = new MethodDefinition(((MemberReference)method).Name, method.Attributes, Module.TypeSystem.Void); ((MemberReference)val5).MetadataToken = GetMetadataToken((TokenType)100663296); ((MethodReference)val5).CallingConvention = ((MethodReference)method).CallingConvention; ((MethodReference)val5).ExplicitThis = ((MethodReference)method).ExplicitThis; ((MethodReference)val5).MethodReturnType = ((MethodReference)method).MethodReturnType; val5.Attributes = method.Attributes; val5.ImplAttributes = method.ImplAttributes; val5.SemanticsAttributes = method.SemanticsAttributes; val5.DeclaringType = targetType; ((MethodReference)val5).ReturnType = ((MethodReference)method).ReturnType; val5.Body = Extensions.Clone(method.Body, val5); val5.PInvokeInfo = method.PInvokeInfo; val5.IsPInvokeImpl = method.IsPInvokeImpl; Enumerator<GenericParameter> enumerator3 = ((MethodReference)method).GenericParameters.GetEnumerator(); try { while (enumerator3.MoveNext()) { GenericParameter current5 = enumerator3.Current; ((MethodReference)val5).GenericParameters.Add(Extensions.Clone(current5)); } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<ParameterDefinition> enumerator4 = ((MethodReference)method).Parameters.GetEnumerator(); try { while (enumerator4.MoveNext()) { ParameterDefinition current6 = enumerator4.Current; ((MethodReference)val5).Parameters.Add(Extensions.Clone(current6)); } } finally { ((IDisposable)enumerator4).Dispose(); } Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current7 = enumerator.Current; val5.CustomAttributes.Add(Extensions.Clone(current7)); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodReference current8 = enumerator2.Current; val5.Overrides.Add(current8); } } finally { ((IDisposable)enumerator2).Dispose(); } val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); targetType.Methods.Add(val5); method = val5; } if (val3 != null) { CustomAttribute val6 = new CustomAttribute(GetMonoModOriginalNameCtor()); val6.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)((MemberReference)val3).Name)); method.CustomAttributes.Add(val6); } return method; } public virtual void PatchRefs() { //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) if (!UpgradeMSCORLIB.HasValue) { Version fckUnity = new Version(2, 0, 5, 0); UpgradeMSCORLIB = ((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference x) => x.Version == fckUnity); } if (UpgradeMSCORLIB.Value) { List<AssemblyNameReference> list = new List<AssemblyNameReference>(); for (int i = 0; i < Module.AssemblyReferences.Count; i++) { AssemblyNameReference val = Module.AssemblyReferences[i]; if (val.Name == "mscorlib") { list.Add(val); } } if (list.Count > 1) { AssemblyNameReference val2 = list.OrderByDescending((AssemblyNameReference x) => x.Version).First(); if (DependencyCache.TryGetValue(val2.FullName, out var value)) { for (int j = 0; j < Module.AssemblyReferences.Count; j++) { AssemblyNameReference val3 = Module.AssemblyReferences[j]; if (val3.Name == "mscorlib" && val2.Version > val3.Version) { LogVerbose("[PatchRefs] Removing and relinking duplicate mscorlib: " + val3.Version); RelinkModuleMap[val3.FullName] = value; Module.AssemblyReferences.RemoveAt(j); j--; } } } } } Enumerator<TypeDefinition> enumerator = Module.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PatchRefsInType(current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchRefs(ModuleDefinition mod) { //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<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PatchRefsInType(current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchRefsInType(TypeDefinition type) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //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_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Expected O, but got Unknown //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016e: 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_00dc: Expected O, but got Unknown //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Expected O, but got Unknown //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Expected O, but got Unknown //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Expected O, but got Unknown //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Expected O, but got Unknown //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Expected O, but got Unknown LogVerbose($"[VERBOSE] [PatchRefsInType] Patching refs in {type}"); if (type.BaseType != null) { type.BaseType = Extensions.Relink(type.BaseType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); } for (int i = 0; i < ((TypeReference)type).GenericParameters.Count; i++) { ((TypeReference)type).GenericParameters[i] = Extensions.Relink(((TypeReference)type).GenericParameters[i], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } for (int j = 0; j < type.Interfaces.Count; j++) { InterfaceImplementation obj = type.Interfaces[j]; InterfaceImplementation val = new InterfaceImplementation(Extensions.Relink(obj.InterfaceType, new Relinker(Relinker), (IGenericParameterProvider)(object)type)); Enumerator<CustomAttribute> enumerator = obj.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; val.CustomAttributes.Add(Extensions.Relink(current, new Relinker(Relinker), (IGenericParameterProvider)(object)type)); } } finally { ((IDisposable)enumerator).Dispose(); } type.Interfaces[j] = val; } for (int k = 0; k < type.CustomAttributes.Count; k++) { type.CustomAttributes[k] = Extensions.Relink(type.CustomAttributes[k], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator(); try { while (enumerator2.MoveNext()) { PropertyDefinition current2 = enumerator2.Current; ((PropertyReference)current2).PropertyType = Extensions.Relink(((PropertyReference)current2).PropertyType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int l = 0; l < current2.CustomAttributes.Count; l++) { current2.CustomAttributes[l] = Extensions.Relink(current2.CustomAttributes[l], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator(); try { while (enumerator3.MoveNext()) { EventDefinition current3 = enumerator3.Current; ((EventReference)current3).EventType = Extensions.Relink(((EventReference)current3).EventType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int m = 0; m < current3.CustomAttributes.Count; m++) { current3.CustomAttributes[m] = Extensions.Relink(current3.CustomAttributes[m], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator(); try { while (enumerator4.MoveNext()) { MethodDefinition current4 = enumerator4.Current; PatchRefsInMethod(current4); } } finally { ((IDisposable)enumerator4).Dispose(); } Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator(); try { while (enumerator5.MoveNext()) { FieldDefinition current5 = enumerator5.Current; ((FieldReference)current5).FieldType = Extensions.Relink(((FieldReference)current5).FieldType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int n = 0; n < current5.CustomAttributes.Count; n++) { current5.CustomAttributes[n] = Extensions.Relink(current5.CustomAttributes[n], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator5).Dispose(); } for (int num = 0; num < type.NestedTypes.Count; num++) { PatchRefsInType(type.NestedTypes[num]); } } public virtual void PatchRefsInMethod(MethodDefinition method) { //IL_0030: Unknown result t
patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.RuntimeDetour.HookGen.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021 0x0ade")] [assembly: AssemblyDescription("Auto-generate hook helper .dlls, hook arbitrary methods via events: On.Namespace.Type.Method += YourHandlerHere;")] [assembly: AssemblyFileVersion("21.8.5.1")] [assembly: AssemblyInformationalVersion("21.08.05.01")] [assembly: AssemblyProduct("MonoMod.RuntimeDetour.HookGen")] [assembly: AssemblyTitle("MonoMod.RuntimeDetour.HookGen")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("21.8.5.1")] [module: UnverifiableCode] internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace MonoMod { internal static class MMDbgLog { public static readonly string Tag; public static TextWriter Writer; public static bool Debugging; static MMDbgLog() { Tag = typeof(MMDbgLog).Assembly.GetName().Name; if (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1" || (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG")?.ToLowerInvariant()?.Contains(Tag.ToLowerInvariant())).GetValueOrDefault()) { Start(); } } public static void WaitForDebugger() { if (!Debugging) { Debugging = true; Debugger.Launch(); Thread.Sleep(6000); Debugger.Break(); } } public static void Start() { if (Writer != null) { return; } string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH"); if (text == "-") { Writer = Console.Out; return; } if (string.IsNullOrEmpty(text)) { text = "mmdbglog.txt"; } text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text)); try { if (File.Exists(text)) { File.Delete(text); } } catch { } try { string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8); } catch { } } public static void Log(string str) { TextWriter writer = Writer; if (writer != null) { writer.WriteLine(str); writer.Flush(); } } public static T Log<T>(string str, T value) { TextWriter writer = Writer; if (writer == null) { return value; } writer.WriteLine(string.Format(str, value)); writer.Flush(); return value; } } } namespace MonoMod.RuntimeDetour.HookGen { public class HookGenerator { private const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes."; private static readonly Regex NameVerifyRegex; private static readonly Dictionary<Type, string> ReflTypeNameMap; private static readonly Dictionary<string, string> TypeNameMap; public MonoModder Modder; public ModuleDefinition OutputModule; public string Namespace; public string NamespaceIL; public bool HookOrig; public bool HookPrivate; public string HookExtName; public ModuleDefinition module_RuntimeDetour; public ModuleDefinition module_Utils; public TypeReference t_MulticastDelegate; public TypeReference t_IAsyncResult; public TypeReference t_AsyncCallback; public TypeReference t_MethodBase; public TypeReference t_RuntimeMethodHandle; public TypeReference t_EditorBrowsableState; public MethodReference m_Object_ctor; public MethodReference m_ObsoleteAttribute_ctor; public MethodReference m_EditorBrowsableAttribute_ctor; public MethodReference m_GetMethodFromHandle; public MethodReference m_Add; public MethodReference m_Remove; public MethodReference m_Modify; public MethodReference m_Unmodify; public TypeReference t_ILManipulator; static HookGenerator() { NameVerifyRegex = new Regex("[^a-zA-Z]"); ReflTypeNameMap = new Dictionary<Type, string> { { typeof(string), "string" }, { typeof(object), "object" }, { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(char), "char" }, { typeof(decimal), "decimal" }, { typeof(double), "double" }, { typeof(short), "short" }, { typeof(int), "int" }, { typeof(long), "long" }, { typeof(sbyte), "sbyte" }, { typeof(float), "float" }, { typeof(ushort), "ushort" }, { typeof(uint), "uint" }, { typeof(ulong), "ulong" }, { typeof(void), "void" } }; TypeNameMap = new Dictionary<string, string>(); foreach (KeyValuePair<Type, string> item in ReflTypeNameMap) { TypeNameMap[item.Key.FullName] = item.Value; } } public HookGenerator(MonoModder modder, string name) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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_003d: 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_0053: Expected O, but got Unknown //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Expected O, but got Unknown //IL_0326: Expected O, but got Unknown Modder = modder; OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters { Architecture = modder.Module.Architecture, AssemblyResolver = modder.Module.AssemblyResolver, Kind = (ModuleKind)0, Runtime = modder.Module.Runtime }); modder.MapDependencies(); Extensions.AddRange<AssemblyNameReference>(OutputModule.AssemblyReferences, (IEnumerable<AssemblyNameReference>)modder.Module.AssemblyReferences); modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]); Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE"); if (string.IsNullOrEmpty(Namespace)) { Namespace = "On"; } NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL"); if (string.IsNullOrEmpty(NamespaceIL)) { NamespaceIL = "IL"; } HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1"; HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1"; modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour", (string)null, (AssemblyNameReference)null); if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour)) { throw new FileNotFoundException("MonoMod.RuntimeDetour not found!"); } modder.MapDependency(modder.Module, "MonoMod.Utils", (string)null, (AssemblyNameReference)null); if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils)) { throw new FileNotFoundException("MonoMod.Utils not found!"); } t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate")); t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult")); t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback")); t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase")); t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle")); t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState")); TypeDefinition type = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager"); t_ILManipulator = OutputModule.ImportReference((TypeReference)(object)module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator")); m_Object_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.Object").Resolve(), "System.Void .ctor()", true)); m_ObsoleteAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ObsoleteAttribute").Resolve(), "System.Void .ctor(System.String,System.Boolean)", true)); m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve(), "System.Void .ctor(System.ComponentModel.EditorBrowsableState)", true)); ModuleDefinition outputModule = OutputModule; MethodReference val = new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase); val.Parameters.Add(new ParameterDefinition(t_RuntimeMethodHandle)); m_GetMethodFromHandle = outputModule.ImportReference(val); m_Add = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Add", true)); m_Remove = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Remove", true)); m_Modify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Modify", true)); m_Unmodify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Unmodify", true)); } public void Generate() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) Enumerator<TypeDefinition> enumerator = Modder.Module.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; GenerateFor(current, out var hookType, out var hookILType); if (hookType != null && hookILType != null && !((TypeReference)hookType).IsNested) { OutputModule.Types.Add(hookType); OutputModule.Types.Add(hookILType); } } } finally { ((IDisposable)enumerator).Dispose(); } } public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType) { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Expected O, but got Unknown //IL_0141: 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_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) hookType = (hookILType = null); if (((TypeReference)type).HasGenericParameters || type.IsRuntimeSpecialName || ((MemberReference)type).Name.StartsWith("<") || (!HookPrivate && type.IsNotPublic)) { return; } Modder.LogVerbose("[HookGen] Generating for type " + ((MemberReference)type).FullName); hookType = new TypeDefinition(((TypeReference)type).IsNested ? null : (Namespace + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object); hookILType = new TypeDefinition(((TypeReference)type).IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object); bool flag = false; Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; flag |= GenerateFor(hookType, hookILType, current); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<TypeDefinition> enumerator2 = type.NestedTypes.GetEnumerator(); try { while (enumerator2.MoveNext()) { TypeDefinition current2 = enumerator2.Current; GenerateFor(current2, out var hookType2, out var hookILType2); if (hookType2 != null && hookILType2 != null) { flag = true; hookType.NestedTypes.Add(hookType2); hookILType.NestedTypes.Add(hookILType2); } } } finally { ((IDisposable)enumerator2).Dispose(); } if (!flag) { hookType = (hookILType = null); } } public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method) { //IL_02fa: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Expected O, but got Unknown //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Expected O, but got Unknown //IL_0380: Unknown result type (might be due to invalid IL or missing references) //IL_0387: Expected O, but got Unknown //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_039c: Expected O, but got Unknown //IL_03a0: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Expected O, but got Unknown //IL_03b7: Unknown result type (might be due to invalid IL or missing references) //IL_03c4: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Expected O, but got Unknown //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_044a: Expected O, but got Unknown //IL_0455: Unknown result type (might be due to invalid IL or missing references) //IL_045f: Expected O, but got Unknown //IL_0463: Unknown result type (might be due to invalid IL or missing references) //IL_046d: Expected O, but got Unknown //IL_047a: Unknown result type (might be due to invalid IL or missing references) //IL_0487: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) //IL_04a8: Unknown result type (might be due to invalid IL or missing references) //IL_04af: Expected O, but got Unknown //IL_04be: 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_04ea: Unknown result type (might be due to invalid IL or missing references) //IL_04ef: Unknown result type (might be due to invalid IL or missing references) //IL_04f7: Unknown result type (might be due to invalid IL or missing references) //IL_0501: Expected O, but got Unknown //IL_0533: Unknown result type (might be due to invalid IL or missing references) //IL_053a: Expected O, but got Unknown //IL_0549: Unknown result type (might be due to invalid IL or missing references) //IL_0553: Expected O, but got Unknown //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_0561: Expected O, but got Unknown //IL_056e: Unknown result type (might be due to invalid IL or missing references) //IL_057b: Unknown result type (might be due to invalid IL or missing references) //IL_058c: Unknown result type (might be due to invalid IL or missing references) //IL_059c: Unknown result type (might be due to invalid IL or missing references) //IL_05a3: Expected O, but got Unknown //IL_05b2: Unknown result type (might be due to invalid IL or missing references) //IL_05be: Unknown result type (might be due to invalid IL or missing references) //IL_05fa: Unknown result type (might be due to invalid IL or missing references) //IL_0601: Expected O, but got Unknown //IL_0610: Unknown result type (might be due to invalid IL or missing references) //IL_061a: Expected O, but got Unknown //IL_061e: Unknown result type (might be due to invalid IL or missing references) //IL_0628: Expected O, but got Unknown //IL_0635: Unknown result type (might be due to invalid IL or missing references) //IL_0642: Unknown result type (might be due to invalid IL or missing references) //IL_0653: Unknown result type (might be due to invalid IL or missing references) //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_066a: Expected O, but got Unknown //IL_0679: Unknown result type (might be due to invalid IL or missing references) //IL_0685: Unknown result type (might be due to invalid IL or missing references) //IL_06a9: Unknown result type (might be due to invalid IL or missing references) //IL_06ae: Unknown result type (might be due to invalid IL or missing references) //IL_06b6: Unknown result type (might be due to invalid IL or missing references) //IL_06c0: Expected O, but got Unknown if (((MethodReference)method).HasGenericParameters || method.IsAbstract || (method.IsSpecialName && !method.IsConstructor)) { return false; } if (!HookOrig && ((MemberReference)method).Name.StartsWith("orig_")) { return false; } if (!HookPrivate && method.IsPrivate) { return false; } string name = GetFriendlyName((MethodReference)(object)method); bool flag = true; if (((MethodReference)method).Parameters.Count == 0) { flag = false; } IEnumerable<MethodDefinition> source = null; if (flag) { source = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name && other != method); if (source.Count() == 0) { flag = false; } } if (flag) { StringBuilder stringBuilder = new StringBuilder(); for (int parami = 0; parami < ((MethodReference)method).Parameters.Count; parami++) { ParameterDefinition param = ((MethodReference)method).Parameters[parami]; if (!TypeNameMap.TryGetValue(((MemberReference)((ParameterReference)param).ParameterType).FullName, out var typeName)) { typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: false); } if (source.Any(delegate(MethodDefinition other) { ParameterDefinition val11 = ((IEnumerable<ParameterDefinition>)((MethodReference)other).Parameters).ElementAtOrDefault(parami); return val11 != null && GetFriendlyName(((ParameterReference)val11).ParameterType, full: false) == typeName && ((ParameterReference)val11).ParameterType.Namespace != ((ParameterReference)param).ParameterType.Namespace; })) { typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: true); } stringBuilder.Append("_"); stringBuilder.Append(typeName.Replace(".", "").Replace("`", "")); } name += stringBuilder.ToString(); } if (Extensions.FindEvent(hookType, name) != null) { int num = 1; string text; while (Extensions.FindEvent(hookType, text = name + "_" + num) != null) { num++; } name = text; } TypeDefinition val = GenerateDelegateFor(method); ((MemberReference)val).Name = "orig_" + name; val.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never)); hookType.NestedTypes.Add(val); TypeDefinition val2 = GenerateDelegateFor(method); ((MemberReference)val2).Name = "hook_" + name; ((MethodReference)Extensions.FindMethod(val2, "Invoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val)); ((MethodReference)Extensions.FindMethod(val2, "BeginInvoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val)); val2.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never)); hookType.NestedTypes.Add(val2); MethodReference val3 = OutputModule.ImportReference((MethodReference)(object)method); MethodDefinition val4 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val4).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2)); val4.Body = new MethodBody(val4); ILProcessor iLProcessor = val4.Body.GetILProcessor(); iLProcessor.Emit(OpCodes.Ldtoken, val3); iLProcessor.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor.Emit(OpCodes.Ldarg_0); GenericInstanceMethod val5 = new GenericInstanceMethod(m_Add); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor.Emit(OpCodes.Ret); hookType.Methods.Add(val4); MethodDefinition val6 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val6).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2)); val6.Body = new MethodBody(val6); ILProcessor iLProcessor2 = val6.Body.GetILProcessor(); iLProcessor2.Emit(OpCodes.Ldtoken, val3); iLProcessor2.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor2.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Remove); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor2.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor2.Emit(OpCodes.Ret); hookType.Methods.Add(val6); EventDefinition val7 = new EventDefinition(name, (EventAttributes)0, (TypeReference)(object)val2) { AddMethod = val4, RemoveMethod = val6 }; hookType.Events.Add(val7); MethodDefinition val8 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val8).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator)); val8.Body = new MethodBody(val8); ILProcessor iLProcessor3 = val8.Body.GetILProcessor(); iLProcessor3.Emit(OpCodes.Ldtoken, val3); iLProcessor3.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor3.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Modify); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor3.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor3.Emit(OpCodes.Ret); hookILType.Methods.Add(val8); MethodDefinition val9 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val9).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator)); val9.Body = new MethodBody(val9); ILProcessor iLProcessor4 = val9.Body.GetILProcessor(); iLProcessor4.Emit(OpCodes.Ldtoken, val3); iLProcessor4.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor4.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Unmodify); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor4.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor4.Emit(OpCodes.Ret); hookILType.Methods.Add(val9); EventDefinition val10 = new EventDefinition(name, (EventAttributes)0, t_ILManipulator) { AddMethod = val8, RemoveMethod = val9 }; hookILType.Events.Add(val10); return true; } public TypeDefinition GenerateDelegateFor(MethodDefinition method) { //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00ed: 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_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Expected O, but got Unknown //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0174: 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_0184: Expected O, but got Unknown //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Expected O, but got Unknown //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Expected O, but got Unknown //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Expected O, but got Unknown //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Expected O, but got Unknown //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Expected O, but got Unknown //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Expected O, but got Unknown //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Expected O, but got Unknown //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Expected O, but got Unknown //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Expected O, but got Unknown //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0344: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_0354: Expected O, but got Unknown //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Expected O, but got Unknown //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_037f: Expected O, but got Unknown string name = GetFriendlyName((MethodReference)(object)method); int num = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name).ToList().IndexOf(method); if (num != 0) { string suffix = num.ToString(); do { name = name + "_" + suffix; } while (((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Any((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name + suffix)); } name = "d_" + name; TypeDefinition val = new TypeDefinition((string)null, (string)null, (TypeAttributes)258, t_MulticastDelegate); MethodDefinition val2 = new MethodDefinition(".ctor", (MethodAttributes)6278, OutputModule.TypeSystem.Void) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; ((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object)); ((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr)); val2.Body = new MethodBody(val2); val.Methods.Add(val2); MethodDefinition val3 = new MethodDefinition("Invoke", (MethodAttributes)454, ImportVisible(((MethodReference)method).ReturnType)) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; if (!method.IsStatic) { TypeReference val4 = ImportVisible((TypeReference)(object)method.DeclaringType); if (((TypeReference)method.DeclaringType).IsValueType) { val4 = (TypeReference)new ByReferenceType(val4); } ((MethodReference)val3).Parameters.Add(new ParameterDefinition("self", (ParameterAttributes)0, val4)); } Enumerator<ParameterDefinition> enumerator = ((MethodReference)method).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; ((MethodReference)val3).Parameters.Add(new ParameterDefinition(((ParameterReference)current).Name, (ParameterAttributes)(current.Attributes & 0xFFEF & 0xEFFF), ImportVisible(((ParameterReference)current).ParameterType))); } } finally { ((IDisposable)enumerator).Dispose(); } val3.Body = new MethodBody(val3); val.Methods.Add(val3); MethodDefinition val5 = new MethodDefinition("BeginInvoke", (MethodAttributes)454, t_IAsyncResult) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; enumerator = ((MethodReference)val3).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current2 = enumerator.Current; ((MethodReference)val5).Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType)); } } finally { ((IDisposable)enumerator).Dispose(); } ((MethodReference)val5).Parameters.Add(new ParameterDefinition("callback", (ParameterAttributes)0, t_AsyncCallback)); ((MethodReference)val5).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, OutputModule.TypeSystem.Object)); val5.Body = new MethodBody(val5); val.Methods.Add(val5); MethodDefinition val6 = new MethodDefinition("EndInvoke", (MethodAttributes)454, OutputModule.TypeSystem.Object) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; ((MethodReference)val6).Parameters.Add(new ParameterDefinition("result", (ParameterAttributes)0, t_IAsyncResult)); val6.Body = new MethodBody(val6); val.Methods.Add(val6); return val; } private string GetFriendlyName(MethodReference method) { string text = ((MemberReference)method).Name; if (text.StartsWith(".")) { text = text.Substring(1); } return text.Replace('.', '_'); } private string GetFriendlyName(TypeReference type, bool full) { if (type is TypeSpecification) { StringBuilder stringBuilder = new StringBuilder(); BuildFriendlyName(stringBuilder, type, full); return stringBuilder.ToString(); } if (!full) { return ((MemberReference)type).Name; } return ((MemberReference)type).FullName; } private void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) if (!(type is TypeSpecification)) { builder.Append((full ? ((MemberReference)type).FullName : ((MemberReference)type).Name).Replace("_", "")); return; } if (type.IsByReference) { builder.Append("ref"); } else if (type.IsPointer) { builder.Append("ptr"); } BuildFriendlyName(builder, ((TypeSpecification)type).ElementType, full); if (type.IsArray) { builder.Append("Array"); } } private bool IsPublic(TypeDefinition typeDef) { if (typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic)) { return !typeDef.IsNotPublic; } return false; } private bool HasPublicArgs(GenericInstanceType typeGen) { //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<TypeReference> enumerator = typeGen.GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current = enumerator.Current; if (current.IsGenericParameter) { return false; } GenericInstanceType val = (GenericInstanceType)(object)((current is GenericInstanceType) ? current : null); if (val != null && !HasPublicArgs(val)) { return false; } if (!IsPublic(Extensions.SafeResolve(current))) { return false; } } } finally { ((IDisposable)enumerator).Dispose(); } return true; } private TypeReference ImportVisible(TypeReference typeRef) { for (TypeDefinition val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null); val != null; val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null)) { GenericInstanceType val2 = (GenericInstanceType)(object)((typeRef is GenericInstanceType) ? typeRef : null); if (val2 == null || HasPublicArgs(val2)) { TypeDefinition val3 = val; while (true) { if (val3 != null) { if (IsPublic(val3) && (val3 == val || !((TypeReference)val3).HasGenericParameters)) { val3 = val3.DeclaringType; continue; } if (!val.IsEnum) { break; } typeRef = ((FieldReference)Extensions.FindField(val, "value__")).FieldType; } try { return OutputModule.ImportReference(typeRef); } catch { return OutputModule.TypeSystem.Object; } } } typeRef = val.BaseType; } return OutputModule.TypeSystem.Object; } private CustomAttribute GenerateObsolete(string message, bool error) { //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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown CustomAttribute val = new CustomAttribute(m_ObsoleteAttribute_ctor); val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, (object)message)); val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, (object)error)); return val; } private CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state) { //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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown CustomAttribute val = new CustomAttribute(m_EditorBrowsableAttribute_ctor); val.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, (object)state)); return val; } } internal class Program { private static void Main(string[] args) { //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Expected O, but got Unknown Console.WriteLine("MonoMod.RuntimeDetour.HookGen " + typeof(Program).Assembly.GetName().Version); Console.WriteLine("using MonoMod " + typeof(MonoModder).Assembly.GetName().Version); Console.WriteLine("using MonoMod.RuntimeDetour " + typeof(Detour).Assembly.GetName().Version); if (args.Length == 0) { Console.WriteLine("No valid arguments (assembly path) passed."); if (Debugger.IsAttached) { Console.ReadKey(); } return; } int num = 0; for (int i = 0; i < args.Length; i++) { if (args[i] == "--namespace" && i + 2 < args.Length) { i++; Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE", args[i]); continue; } if (args[i] == "--namespace-il" && i + 2 < args.Length) { i++; Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL", args[i]); continue; } if (args[i] == "--orig") { Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG", "1"); continue; } if (args[i] == "--private") { Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1"); continue; } num = i; break; } if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW"))) { Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0"); } if (num >= args.Length) { Console.WriteLine("No assembly path passed."); if (Debugger.IsAttached) { Console.ReadKey(); } return; } string text = args[num]; string text2 = ((args.Length != 1 && num != args.Length - 1) ? args[^1] : null); text2 = text2 ?? Path.Combine(Path.GetDirectoryName(text), "MMHOOK_" + Path.ChangeExtension(Path.GetFileName(text), "dll")); MonoModder val = new MonoModder { InputPath = text, OutputPath = text2, ReadingMode = (ReadingMode)2 }; try { val.Read(); val.MapDependencies(); if (File.Exists(text2)) { val.Log("[HookGen] Clearing " + text2); File.Delete(text2); } val.Log("[HookGen] Starting HookGenerator"); HookGenerator hookGenerator = new HookGenerator(val, Path.GetFileName(text2)); ModuleDefinition outputModule = hookGenerator.OutputModule; try { hookGenerator.Generate(); outputModule.Write(text2); } finally { ((IDisposable)outputModule)?.Dispose(); } val.Log("[HookGen] Done."); } finally { ((IDisposable)val)?.Dispose(); } if (Debugger.IsAttached) { Console.ReadKey(); } } } }
patchers/FixPluginTypesSerialization/FixPluginTypesSerialization.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using FixPluginTypesSerialization.Patchers; using FixPluginTypesSerialization.UnityPlayer; using FixPluginTypesSerialization.UnityPlayer.Structs.Default; using FixPluginTypesSerialization.Util; using Microsoft.CodeAnalysis; using Microsoft.Deployment.Compression; using Microsoft.Deployment.Compression.Cab; using Mono.Cecil; using MonoMod.RuntimeDetour; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("FixPluginTypesSerialization")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3eee0b205c9f04c6e93663e6e8aa9a38a267e6fd")] [assembly: AssemblyProduct("FixPluginTypesSerialization")] [assembly: AssemblyTitle("FixPluginTypesSerialization")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.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 NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = 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 FixPluginTypesSerialization { internal static class Config { private static readonly ConfigFile _config = new ConfigFile(Path.Combine(Paths.ConfigPath, "FixPluginTypesSerialization.cfg"), true); internal static ConfigEntry<string> UnityVersionOverride = _config.Bind<string>("Overrides", "UnityVersionOverride", "", "Unity version is Major.Minor.Patch format i.e. 2017.2.1." + Environment.NewLine + "If specified, this version will be used instead of auto-detection" + Environment.NewLine + "from executable info. Specify only if the patcher doesn't work otherwise."); internal static ConfigEntry<FunctionOffsetLookup> FunctionOffsetLookupType = _config.Bind<FunctionOffsetLookup>("Overrides", "FunctionOffsetLookupType", FunctionOffsetLookup.PreferSupportedVersions, "PreferSupportedVersions - using values for supported versions, if a version is not supported trying to use pdb." + Environment.NewLine + "PreferPdb - using pdb, it will be downloaded from Unity symbols server,if there is no pdb or download failed trying to use values for supported versions." + Environment.NewLine + "Manual - using offsets from [Cache] section of the config, which you need to specify yourself as hex values."); internal static ConfigEntry<string> LastDownloadedGUID = _config.Bind<string>("Cache", "LastDownloadedGUID", "000000000000000000000000000000000", "The GUID of the last downloaded UnityPlayer pdb file." + Environment.NewLine + "If this GUID matches with the current one," + Environment.NewLine + "the offsets for the functions below will be used" + Environment.NewLine + "instead of generating them at runtime."); internal static ConfigEntry<string> MonoManagerAwakeFromLoadOffset = _config.Bind<string>("Cache", "MonoManagerAwakeFromLoadOffset", "00", "The in-memory offset of the MonoManager::AwakeFromLoad function."); internal static ConfigEntry<string> MonoManagerIsAssemblyCreatedOffset = _config.Bind<string>("Cache", "MonoManagerIsAssemblyCreatedOffset", "00", "The in-memory offset of the MonoManager::IsAssemblyCreated function."); internal static ConfigEntry<string> IsFileCreatedOffset = _config.Bind<string>("Cache", "IsFileCreatedOffset", "00", "The in-memory offset of the IsFileCreated function."); internal static ConfigEntry<string> ScriptingManagerDeconstructorOffset = _config.Bind<string>("Cache", "ScriptingManagerDeconstructorOffset", "00", "The in-memory offset of the ScriptingManagerDeconstructor function."); internal static ConfigEntry<string> ConvertSeparatorsToPlatformOffset = _config.Bind<string>("Cache", "ConvertSeparatorsToPlatformOffset", "00", "The in-memory offset of the ConvertSeparatorsToPlatform function."); internal static ConfigEntry<string> FreeAllocInternalOffset = _config.Bind<string>("Cache", "FreeAllocInternalOffset", "00", "The in-memory offset of the free_alloc_internal function."); internal static ConfigEntry<string> MallocInternalOffset = _config.Bind<string>("Cache", "MallocInternalOffset", "00", "The in-memory offset of the malloc_internal function."); internal static ConfigEntry<string> ScriptingAssembliesOffset = _config.Bind<string>("Cache", "ScriptingAssembliesOffset", "00", "The in-memory offset of the m_ScriptingAssemblies global field."); } internal static class FixPluginTypesSerializationPatcher { public static List<string> PluginPaths = (from f in Directory.GetFiles(Paths.PluginPath, "*.dll", SearchOption.AllDirectories) where IsNetAssembly(f) select f).ToList(); public static List<string> PluginNames = PluginPaths.Select((string p) => Path.GetFileName(p)).ToList(); public static IEnumerable<string> TargetDLLs { get; } = new string[0]; public static bool IsNetAssembly(string fileName) { try { AssemblyName.GetAssemblyName(fileName); } catch (BadImageFormatException) { return false; } return true; } public static void Patch(AssemblyDefinition ass) { } public static void Initialize() { Log.Init(); try { InitializeInternal(); } catch (Exception ex) { Log.Error($"Failed to initialize plugin types serialization fix: ({ex.GetType()}) {ex.Message}. Some plugins may not work properly."); Log.Error(ex); } } private static void InitializeInternal() { DetourUnityPlayer(); } private static void DetourUnityPlayer() { string text = Path.Combine(Paths.GameRootPath, "UnityPlayer.dll"); if (!File.Exists(text)) { text = Paths.ExecutablePath; } PatternDiscoverer patternDiscoverer = new PatternDiscoverer((Process.GetCurrentProcess().Modules.Cast<ProcessModule>().FirstOrDefault(IsUnityPlayer) ?? Process.GetCurrentProcess().MainModule).BaseAddress, text); CommonUnityFunctions.Init(patternDiscoverer); AwakeFromLoad awakeFromLoad = new AwakeFromLoad(); IsAssemblyCreated isAssemblyCreated = new IsAssemblyCreated(); IsFileCreated isFileCreated = new IsFileCreated(); ScriptingManagerDeconstructor scriptingManagerDeconstructor = new ScriptingManagerDeconstructor(); ConvertSeparatorsToPlatform convertSeparatorsToPlatform = new ConvertSeparatorsToPlatform(); awakeFromLoad.Patch(patternDiscoverer, Config.MonoManagerAwakeFromLoadOffset); isAssemblyCreated.Patch(patternDiscoverer, Config.MonoManagerIsAssemblyCreatedOffset); if (!IsAssemblyCreated.IsApplied) { isFileCreated.Patch(patternDiscoverer, Config.IsFileCreatedOffset); } convertSeparatorsToPlatform.Patch(patternDiscoverer, Config.ConvertSeparatorsToPlatformOffset); scriptingManagerDeconstructor.Patch(patternDiscoverer, Config.ScriptingManagerDeconstructorOffset); static bool IsUnityPlayer(ProcessModule p) { return p.ModuleName.ToLowerInvariant().Contains("unityplayer"); } } } internal static class Log { internal static ManualLogSource _logSource; internal static void Init() { _logSource = Logger.CreateLogSource("FixPluginTypesSerialization"); } internal static void Debug(object data) { _logSource.LogDebug(data); } internal static void Error(object data) { _logSource.LogError(data); } internal static void Fatal(object data) { _logSource.LogFatal(data); } internal static void Info(object data) { _logSource.LogInfo(data); } internal static void Message(object data) { _logSource.LogMessage(data); } internal static void Warning(object data) { _logSource.LogWarning(data); } } } namespace FixPluginTypesSerialization.Util { internal class BytePattern { private readonly byte?[] pattern; private int[] jumpTable; public int Length => pattern.Length; public bool IsE8 => pattern[0] == 232; public BytePattern(string bytes) { pattern = bytes.ParseHexBytes(); CreateJumpTable(); } public BytePattern(byte[] bytes) { pattern = bytes.Cast<byte?>().ToArray(); CreateJumpTable(); } public static implicit operator BytePattern(string pattern) { return new BytePattern(pattern); } public static implicit operator BytePattern(byte[] pattern) { return new BytePattern(pattern); } private void CreateJumpTable() { jumpTable = new int[pattern.Length]; int num = 0; jumpTable[0] = -1; int num2 = 1; while (num2 < pattern.Length) { if (pattern[num2] == pattern[num]) { jumpTable[num2] = jumpTable[num]; } else { jumpTable[num2] = num; while (num >= 0 && pattern[num2] != pattern[num]) { num = jumpTable[num]; } } num2++; num++; } } public unsafe long Match(IntPtr start, long maxSize) { byte* ptr = (byte*)start.ToPointer(); long num = 0L; long num2 = 0L; while (num < maxSize) { if (!pattern[num2].HasValue || ptr[num] == pattern[num2]) { num++; num2++; if (num2 == pattern.Length) { return num - num2; } } else { num2 = jumpTable[num2]; if (num2 < 0) { num++; num2++; } } } return 0L; } } internal class CommonUnityFunctions { public enum AllocateOptions { None, NullIfOutOfMemory } private delegate IntPtr MallocInternalFunc(ulong size, ulong allign, int label, AllocateOptions allocateOptions, IntPtr file, int line); private delegate void FreeAllocInternalV1Func(IntPtr ptr, int label); private delegate void FreeAllocInternalV2Func(IntPtr ptr, int label, IntPtr file, int line); private static MallocInternalFunc mallocInternal; private static FreeAllocInternalV1Func freeAllocInternalV1; private static FreeAllocInternalV2Func freeAllocInternalV2; public static IntPtr ScriptingAssemblies { get; private set; } public static void Init(PatternDiscoverer patternDiscoverer) { IntPtr intPtr = patternDiscoverer.Discover(Config.MallocInternalOffset, new BytePattern[1] { Encoding.ASCII.GetBytes("malloc_internal") }); if (intPtr != IntPtr.Zero) { mallocInternal = (MallocInternalFunc)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(MallocInternalFunc)); } IntPtr intPtr2 = patternDiscoverer.Discover(Config.FreeAllocInternalOffset, new BytePattern[1] { Encoding.ASCII.GetBytes("free_alloc_internal") }); if (intPtr2 != IntPtr.Zero) { if (UseRightStructs.UnityVersion >= new Version(2019, 3)) { freeAllocInternalV2 = (FreeAllocInternalV2Func)Marshal.GetDelegateForFunctionPointer(intPtr2, typeof(FreeAllocInternalV2Func)); } else { freeAllocInternalV1 = (FreeAllocInternalV1Func)Marshal.GetDelegateForFunctionPointer(intPtr2, typeof(FreeAllocInternalV1Func)); } } IntPtr intPtr3 = patternDiscoverer.Discover(Config.ScriptingAssembliesOffset, new BytePattern[1] { Encoding.ASCII.GetBytes("m_ScriptingAssemblies@") }); if (intPtr3 != IntPtr.Zero) { ScriptingAssemblies = intPtr3; } } public unsafe static IntPtr MallocString(string str, int label, out ulong length) { IntPtr intPtr = Marshal.StringToHGlobalAnsi(str); length = (ulong)str.Length; byte* ptr = (byte*)(void*)intPtr + length; while (*ptr != 0) { ptr++; length++; } IntPtr intPtr2 = mallocInternal(length + 1, 16uL, label, AllocateOptions.NullIfOutOfMemory, IntPtr.Zero, 0); for (ulong num = 0uL; num <= length; num++) { ((byte*)(void*)intPtr2)[num] = ((byte*)(void*)intPtr)[num]; } Marshal.FreeHGlobal(intPtr); return intPtr2; } public static IntPtr MallocInternal(ulong size, ulong allign, int label) { return mallocInternal(size, allign, label, AllocateOptions.NullIfOutOfMemory, IntPtr.Zero, 0); } public static void FreeAllocInternal(IntPtr ptr, int label) { if (UseRightStructs.UnityVersion >= new Version(2019, 3)) { freeAllocInternalV2(ptr, label, IntPtr.Zero, 0); } else { freeAllocInternalV1(ptr, label); } } } internal static class DictionaryExtensions { public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value) { key = tuple.Key; value = tuple.Value; } public static void Deconstruct(this VersionedHandler versionedHandler, out Version version, out object handler) { version = versionedHandler.version; handler = versionedHandler.handler; } } public enum FunctionOffsetLookup { PreferSupportedVersions, PreferPdb, Manual } public static class FunctionOffsets { public static bool TryGet(Version unityVersion, out Dictionary<string, long> offsets) { offsets = ((IntPtr.Size == 4) ? Get32(unityVersion) : Get64(unityVersion)); return offsets != null; } private static Dictionary<string, long> Get32(Version unityVersion) { return null; } private static Dictionary<string, long> Get64(Version unityVersion) { switch (unityVersion.Major) { case 5: switch (unityVersion.Minor) { case 0: switch (unityVersion.Build) { case 0: return CreateOffsets(1519584L, 0L, 2772736L, 1572448L, 2795760L, 11808L, 9536L, 0L); case 1: return CreateOffsets(1526224L, 0L, 2776448L, 1578976L, 2799424L, 11808L, 9536L, 0L); case 2: return CreateOffsets(1526512L, 0L, 2780208L, 1578704L, 2803280L, 11984L, 9712L, 0L); case 3: return CreateOffsets(1532016L, 0L, 2788720L, 1584288L, 2811408L, 11984L, 9712L, 0L); case 4: return CreateOffsets(1532352L, 0L, 2787216L, 1585264L, 2810400L, 11824L, 9552L, 0L); } break; case 1: switch (unityVersion.Build) { case 0: return CreateOffsets(1539536L, 0L, 2895136L, 1591456L, 2914064L, 11792L, 9520L, 0L); case 1: return CreateOffsets(1532352L, 0L, 2889568L, 1584848L, 2909008L, 11776L, 9504L, 0L); case 2: return CreateOffsets(1536608L, 0L, 2895968L, 1588528L, 2914816L, 11968L, 9696L, 0L); case 3: return CreateOffsets(1534064L, 0L, 2893280L, 1586352L, 2912464L, 11792L, 9520L, 0L); case 4: return CreateOffsets(1534560L, 0L, 2897920L, 1586960L, 2917712L, 11776L, 9504L, 0L); case 5: return CreateOffsets(1536544L, 0L, 2895200L, 1589008L, 2914736L, 11776L, 9504L, 0L); } break; case 2: switch (unityVersion.Build) { case 0: return CreateOffsets(1601024L, 0L, 2917232L, 1653200L, 2938816L, 11936L, 9664L, 0L); case 1: return CreateOffsets(1604832L, 0L, 2921792L, 1657232L, 2942912L, 11776L, 9504L, 0L); case 2: return CreateOffsets(1608448L, 0L, 2921632L, 1660080L, 2943344L, 11952L, 9680L, 0L); case 3: return CreateOffsets(1609760L, 0L, 2918432L, 1661824L, 2940192L, 11824L, 9552L, 0L); case 4: return CreateOffsets(1610208L, 0L, 2923312L, 1661584L, 2945072L, 11760L, 9488L, 0L); case 5: return CreateOffsets(1603040L, 0L, 2920608L, 1655584L, 2942368L, 11760L, 9488L, 0L); } break; case 3: switch (unityVersion.Build) { case 0: return CreateOffsets(2058016L, 0L, 3148928L, 2107216L, 3172256L, 1179552L, 1176448L, 0L); case 1: return CreateOffsets(2054016L, 0L, 3149200L, 2102688L, 3173328L, 1171392L, 1168288L, 0L); case 2: return CreateOffsets(2054240L, 0L, 3147872L, 2103040L, 3172048L, 1176608L, 1173504L, 0L); case 3: return CreateOffsets(2055600L, 0L, 3152432L, 2104288L, 3175856L, 1174752L, 1171648L, 0L); case 4: return CreateOffsets(1996128L, 0L, 3090368L, 2045792L, 3114800L, 1133136L, 1129424L, 0L); case 5: return CreateOffsets(2003360L, 0L, 3112208L, 2052592L, 3136096L, 1137840L, 1133504L, 0L); case 6: return CreateOffsets(2018064L, 0L, 3116768L, 2067408L, 3140608L, 1147680L, 1143344L, 0L); case 7: return CreateOffsets(2025424L, 0L, 3130592L, 2074400L, 3154544L, 1152864L, 1148528L, 0L); case 8: return CreateOffsets(2026160L, 0L, 3131296L, 2075056L, 3155232L, 1158080L, 1153744L, 0L); } break; case 4: switch (unityVersion.Build) { case 0: return CreateOffsets(2151120L, 0L, 3326704L, 2192800L, 3343888L, 1307984L, 1304112L, 0L); case 1: return CreateOffsets(2164448L, 0L, 3345952L, 2206416L, 3362960L, 1322688L, 1318816L, 0L); case 2: return CreateOffsets(2167920L, 0L, 3344976L, 2210608L, 3362080L, 1323072L, 1319200L, 0L); case 3: return CreateOffsets(2157424L, 0L, 3344160L, 2199552L, 3361968L, 1314432L, 1310560L, 0L); case 4: return CreateOffsets(2167120L, 0L, 3346880L, 2209696L, 3363392L, 1325200L, 1321328L, 0L); case 5: return CreateOffsets(2164688L, 0L, 3352400L, 2206656L, 3369104L, 1320624L, 1316752L, 0L); case 6: return CreateOffsets(2167600L, 0L, 3355312L, 2209344L, 3372816L, 1324048L, 1320176L, 0L); } break; case 5: switch (unityVersion.Build) { case 0: return CreateOffsets(3187616L, 0L, 2666208L, 3236944L, 2678768L, 80864L, 77712L, 0L); case 1: return CreateOffsets(3193200L, 0L, 2670816L, 3241920L, 2683376L, 81456L, 78288L, 0L); case 2: return CreateOffsets(3205712L, 0L, 2683728L, 3254592L, 2696288L, 81280L, 78112L, 0L); case 3: return CreateOffsets(3203472L, 0L, 2684544L, 3252048L, 2695808L, 81088L, 77920L, 0L); case 4: return CreateOffsets(3204368L, 0L, 2682752L, 3254256L, 2695376L, 81344L, 78176L, 0L); case 5: return CreateOffsets(3205552L, 0L, 2679536L, 3255328L, 2691840L, 80896L, 77728L, 0L); case 6: return CreateOffsets(3212144L, 0L, 2689424L, 3261824L, 2701120L, 81168L, 78000L, 0L); } break; case 6: switch (unityVersion.Build) { case 0: return CreateOffsets(8607808L, 0L, 7398368L, 6477584L, 7397984L, 8475808L, 8475984L, 0L); case 1: return CreateOffsets(8613168L, 0L, 7402064L, 6478288L, 7401680L, 8481280L, 8481456L, 0L); case 2: return CreateOffsets(8634192L, 0L, 7413264L, 6491008L, 7412880L, 8502496L, 8502672L, 0L); case 3: return CreateOffsets(8641584L, 0L, 7421536L, 6501520L, 7421152L, 8508976L, 8509152L, 0L); case 4: return CreateOffsets(8645968L, 0L, 7425024L, 6502240L, 7424640L, 8515008L, 8515184L, 0L); case 5: return CreateOffsets(8650080L, 0L, 7426080L, 6502768L, 7425696L, 8517088L, 8517264L, 0L); case 6: return CreateOffsets(8644208L, 0L, 7420704L, 6497312L, 7420320L, 8511584L, 8511760L, 0L); case 7: return CreateOffsets(8644208L, 0L, 7420704L, 6497312L, 7420320L, 8511584L, 8511760L, 0L); } break; } break; case 2017: switch (unityVersion.Minor) { case 1: switch (unityVersion.Build) { case 0: return CreateOffsets(5689904L, 0L, 8344128L, 7269760L, 8357424L, 9310656L, 9306960L, 0L); case 1: return CreateOffsets(5693664L, 0L, 8350688L, 7274656L, 8364608L, 9318256L, 9314560L, 0L); case 2: return CreateOffsets(5698352L, 0L, 8350896L, 7277376L, 8364816L, 9322400L, 9318704L, 0L); case 3: return CreateOffsets(5703968L, 0L, 8363488L, 7285696L, 8377360L, 9338048L, 9334352L, 0L); case 4: return CreateOffsets(5713616L, 0L, 8372080L, 7296256L, 8385872L, 9345600L, 9341904L, 0L); case 5: return CreateOffsets(5710224L, 0L, 8372640L, 7292560L, 8386560L, 9345104L, 9341408L, 0L); } break; case 2: switch (unityVersion.Build) { case 0: return CreateOffsets(4525712L, 0L, 3978000L, 4598144L, 3993984L, 1163072L, 1159376L, 0L); case 1: return CreateOffsets(4527072L, 0L, 3981312L, 4599904L, 3997552L, 1159344L, 1155648L, 0L); case 2: return CreateOffsets(4527520L, 0L, 3979856L, 4600704L, 3995840L, 1161024L, 1157328L, 0L); case 3: return CreateOffsets(4535296L, 0L, 3987264L, 4608480L, 4003456L, 1160272L, 1156576L, 0L); case 4: return CreateOffsets(4531840L, 0L, 3980800L, 4605552L, 3997264L, 1161952L, 1158256L, 0L); case 5: return CreateOffsets(4531568L, 0L, 3989296L, 4604384L, 4005408L, 1159136L, 1155440L, 0L); } break; case 3: switch (unityVersion.Build) { case 0: return CreateOffsets(6098128L, 6114480L, 0L, 6201264L, 5566256L, 2970112L, 2969968L, 0L); case 1: return CreateOffsets(6092560L, 6108592L, 0L, 6195360L, 5561584L, 2968608L, 2968464L, 0L); } break; case 4: switch (unityVersion.Build) { case 0: return CreateOffsets(6099152L, 6115168L, 0L, 6200912L, 5570992L, 2962832L, 2962688L, 0L); case 1: return CreateOffsets(6090224L, 6106352L, 0L, 6192160L, 5563088L, 2966992L, 2966848L, 0L); case 2: return CreateOffsets(6089152L, 6105184L, 0L, 6191344L, 5558704L, 2966256L, 2966112L, 0L); case 3: return CreateOffsets(6098288L, 6114416L, 0L, 6200832L, 5569856L, 2976272L, 2976128L, 0L); case 4: return CreateOffsets(6093440L, 6109568L, 0L, 6195728L, 5562016L, 2968944L, 2968800L, 0L); case 5: return CreateOffsets(6105040L, 6121072L, 0L, 6207424L, 5575792L, 2969376L, 2969232L, 0L); case 6: return CreateOffsets(6088256L, 6104304L, 0L, 6190176L, 5555632L, 2970272L, 2970128L, 0L); case 7: return CreateOffsets(6102032L, 6118064L, 0L, 6203936L, 5573216L, 2967184L, 2967040L, 0L); case 8: return CreateOffsets(6105072L, 6121200L, 0L, 6207488L, 5576496L, 2979936L, 2979792L, 0L); case 9: return CreateOffsets(6099504L, 6115632L, 0L, 6202080L, 5567344L, 2969632L, 2969488L, 0L); case 10: return CreateOffsets(6109760L, 6125808L, 0L, 6212096L, 5574160L, 2970560L, 2970416L, 0L); case 11: return CreateOffsets(6109840L, 6125872L, 0L, 6211920L, 5575440L, 2968192L, 2968048L, 0L); case 12: return CreateOffsets(6119152L, 6135168L, 0L, 6221536L, 5589472L, 2973952L, 2973808L, 0L); case 13: return CreateOffsets(6114544L, 6130672L, 0L, 6217040L, 5579888L, 2980080L, 2979936L, 0L); case 14: return CreateOffsets(6117312L, 6133440L, 0L, 6220256L, 5580752L, 2985280L, 2985136L, 0L); case 15: return CreateOffsets(6117904L, 6133936L, 0L, 6221280L, 5581568L, 2981136L, 2980992L, 0L); case 16: return CreateOffsets(6118368L, 6134400L, 0L, 6221312L, 5587808L, 2969936L, 2969792L, 0L); case 17: return CreateOffsets(6121104L, 6137136L, 0L, 6224032L, 5590048L, 2973232L, 2973088L, 0L); case 18: return CreateOffsets(6123024L, 6139152L, 0L, 6226080L, 5591712L, 2970976L, 2970832L, 0L); case 19: return CreateOffsets(6121200L, 6137216L, 0L, 6223728L, 5585680L, 2974192L, 2974048L, 0L); case 20: return CreateOffsets(6116240L, 6132272L, 0L, 6219808L, 5580752L, 2969056L, 2968912L, 0L); case 21: return CreateOffsets(6122640L, 6138688L, 0L, 6225712L, 5589936L, 2980784L, 2980640L, 0L); case 22: return CreateOffsets(6122640L, 6138688L, 0L, 6225712L, 5589936L, 2980784L, 2980640L, 0L); case 23: return CreateOffsets(6123424L, 6139456L, 0L, 6226704L, 5591328L, 2969376L, 2969232L, 0L); case 24: return CreateOffsets(6116784L, 6132800L, 0L, 6219984L, 5585888L, 2982864L, 2982720L, 0L); case 25: return CreateOffsets(6116208L, 6132432L, 0L, 6219616L, 5582304L, 2982720L, 2982576L, 0L); case 26: return CreateOffsets(6120352L, 6136576L, 0L, 6223792L, 5586720L, 2970096L, 2969952L, 0L); case 27: return CreateOffsets(6124624L, 6140848L, 0L, 6228048L, 5592176L, 2980256L, 2980112L, 0L); case 28: return CreateOffsets(6107520L, 6123856L, 0L, 6211152L, 5571904L, 2974000L, 2973856L, 0L); case 29: return CreateOffsets(6107520L, 6123856L, 0L, 6211152L, 5571904L, 2974000L, 2973856L, 0L); case 30: return CreateOffsets(6125328L, 6141680L, 0L, 6228896L, 5586656L, 2982912L, 2982768L, 0L); case 31: return CreateOffsets(6120704L, 6136944L, 0L, 6223984L, 5587728L, 2976064L, 2975920L, 0L); case 32: return CreateOffsets(6108816L, 6125056L, 0L, 6212208L, 5573056L, 2968016L, 2967872L, 0L); case 33: return CreateOffsets(6122272L, 6138624L, 0L, 6225696L, 5585472L, 2984416L, 2984272L, 0L); case 34: return CreateOffsets(6122512L, 6138848L, 0L, 6226176L, 5586752L, 2983696L, 2983552L, 0L); case 35: return CreateOffsets(6122752L, 6138976L, 0L, 6225952L, 5590960L, 2972096L, 2971952L, 0L); case 36: return CreateOffsets(6126272L, 6142496L, 0L, 6229648L, 5592816L, 2986848L, 2986704L, 0L); case 37: return CreateOffsets(6121616L, 6137856L, 0L, 6225232L, 5585360L, 2971200L, 2971056L, 0L); case 38: return CreateOffsets(6121424L, 6137664L, 0L, 6225056L, 5587040L, 2978944L, 2978800L, 0L); case 39: return CreateOffsets(6122736L, 6138976L, 0L, 6226288L, 5591712L, 2985440L, 2985296L, 0L); case 40: return CreateOffsets(6117872L, 6134096L, 0L, 6221616L, 5582608L, 2982928L, 2982784L, 0L); } break; } break; case 2018: switch (unityVersion.Minor) { case 1: switch (unityVersion.Build) { case 0: return CreateOffsets(5841104L, 5860640L, 0L, 5923328L, 5335888L, 2849008L, 2848960L, 0L); case 1: return CreateOffsets(5834512L, 5854048L, 0L, 5916592L, 5330832L, 2848048L, 2837376L, 0L); case 2: return CreateOffsets(5839264L, 5858800L, 0L, 5921712L, 5335696L, 2850784L, 2840256L, 0L); case 3: return CreateOffsets(5835600L, 5855136L, 0L, 5918256L, 5331712L, 2847920L, 2847872L, 0L); case 4: return CreateOffsets(5841024L, 5860560L, 0L, 5923008L, 5335648L, 2846960L, 2846912L, 0L); case 5: return CreateOffsets(5839920L, 5859456L, 0L, 5922656L, 5333936L, 2848240L, 2837568L, 0L); case 6: return CreateOffsets(5839104L, 5858640L, 0L, 5921408L, 5334368L, 2848368L, 2837744L, 0L); case 7: return CreateOffsets(5839888L, 5859424L, 0L, 5922480L, 5336160L, 2853216L, 2842784L, 0L); case 8: return CreateOffsets(5840960L, 5860512L, 0L, 5923280L, 5334480L, 2845504L, 2845456L, 0L); case 9: return CreateOffsets(5838832L, 5858368L, 0L, 5921024L, 5336560L, 2851392L, 2840816L, 0L); } break; case 2: switch (unityVersion.Build) { case 0: return CreateOffsets(6134752L, 6152240L, 0L, 6214400L, 5567824L, 3004448L, 3004400L, 0L); case 1: return CreateOffsets(6136480L, 6154000L, 0L, 6216368L, 5573280L, 3004016L, 3003968L, 0L); case 2: return CreateOffsets(6136784L, 6154272L, 0L, 6216768L, 5572768L, 3003648L, 3003600L, 0L); case 3: return CreateOffsets(6134160L, 6151664L, 0L, 6214032L, 5569712L, 3005856L, 2995456L, 0L); case 4: return CreateOffsets(6137600L, 6155104L, 0L, 6217568L, 5573328L, 3000704L, 2990400L, 0L); case 5: return CreateOffsets(6135904L, 6153408L, 0L, 6217008L, 5572336L, 3002448L, 3002400L, 0L); case 6: return CreateOffsets(6140624L, 6158128L, 0L, 6220336L, 5576304L, 3005888L, 3005840L, 0L); case 7: return CreateOffsets(6141280L, 6158768L, 0L, 6221712L, 5574560L, 3007168L, 3007120L, 0L); case 8: return CreateOffsets(6141072L, 6158560L, 0L, 6220944L, 5574192L, 3006624L, 3006576L, 0L); case 9: return CreateOffsets(6142976L, 6160496L, 0L, 6223184L, 5577760L, 3006608L, 2996400L, 0L); case 10: return CreateOffsets(6144720L, 6162240L, 0L, 6224928L, 5580864L, 3006832L, 2996528L, 0L); case 11: return CreateOffsets(6140448L, 6157936L, 0L, 6220560L, 5574288L, 3005024L, 3004976L, 0L); case 12: return CreateOffsets(6144960L, 6162448L, 0L, 6224608L, 5578288L, 3007536L, 2997088L, 0L); case 13: return CreateOffsets(6144784L, 6162288L, 0L, 6224528L, 5579264L, 3007344L, 2997040L, 0L); case 14: return CreateOffsets(6148432L, 6165920L, 0L, 6228176L, 5582640L, 3008544L, 2998192L, 0L); case 15: return CreateOffsets(6146896L, 6164416L, 0L, 6226704L, 5582336L, 3008848L, 3008800L, 0L); case 16: return CreateOffsets(6147104L, 6164624L, 0L, 6226800L, 5585456L, 3009728L, 3009680L, 0L); case 17: return CreateOffsets(6147104L, 6164624L, 0L, 6226800L, 5585456L, 3009728L, 3009680L, 0L); case 18: return CreateOffsets(6141616L, 6159120L, 0L, 6221296L, 5578512L, 3007008L, 3006960L, 0L); case 19: return CreateOffsets(6145424L, 6162928L, 0L, 6225184L, 5580576L, 3008768L, 3008720L, 0L); case 20: return CreateOffsets(6147296L, 6164800L, 0L, 6227184L, 5583056L, 3007440L, 2997184L, 0L); case 21: return CreateOffsets(6147296L, 6164800L, 0L, 6227184L, 5583056L, 3007440L, 2997184L, 0L); } break; case 3: switch (unityVersion.Build) { case 0: return CreateOffsets(9297584L, 9308880L, 0L, 9330880L, 8839872L, 6427856L, 6427808L, 0L); case 1: return CreateOffsets(9298944L, 9310240L, 0L, 9332240L, 8841232L, 6428736L, 6428688L, 0L); case 2: return CreateOffsets(9298880L, 9310176L, 0L, 9332176L, 8841168L, 6428720L, 6428672L, 0L); case 3: return CreateOffsets(9300864L, 9312160L, 0L, 9334160L, 8843152L, 6430848L, 6430800L, 0L); case 4: return CreateOffsets(9301808L, 9313104L, 0L, 9335104L, 8844096L, 6431776L, 6431728L, 0L); case 5: return CreateOffsets(9303232L, 9314528L, 0L, 9336528L, 8845360L, 6432080L, 6432032L, 0L); case 6: return CreateOffsets(9310592L, 9321872L, 0L, 9343872L, 8852688L, 6439856L, 6439808L, 0L); case 7: return CreateOffsets(9313440L, 9324720L, 0L, 9346720L, 8855536L, 6441168L, 6441120L, 0L); case 8: return CreateOffsets(9316512L, 9327792L, 0L, 9349792L, 8842976L, 6443808L, 6443760L, 0L); case 9: return CreateOffsets(9316768L, 9328048L, 0L, 9350048L, 8843232L, 6444048L, 6444000L, 0L); case 10: return CreateOffsets(9318192L, 9329472L, 0L, 9351472L, 8844400L, 6444848L, 6444800L, 0L); case 11: return CreateOffsets(9318256L, 9329536L, 0L, 9351536L, 8844464L, 6444784L, 6444736L, 0L); case 12: return CreateOffsets(9318160L, 9329440L, 0L, 9351440L, 8844336L, 6446272L, 6446224L, 0L); case 13: return CreateOffsets(9319200L, 9330480L, 0L, 9352480L, 8845168L, 6447104L, 6447056L, 0L); case 14: return CreateOffsets(9317152L, 9328432L, 0L, 9350432L, 8843168L, 6447504L, 6447456L, 0L); } break; case 4: switch (unityVersion.Build) { case 1: return CreateOffsets(9318256L, 9329536L, 0L, 9351536L, 8844272L, 6448576L, 6448528L, 0L); case 2: return CreateOffsets(9320864L, 9332144L, 0L, 9354144L, 8846880L, 6450800L, 6450752L, 0L); case 3: return CreateOffsets(9320768L, 9332048L, 0L, 9354048L, 8846784L, 6450560L, 6450512L, 0L); case 4: return CreateOffsets(9320640L, 9331920L, 0L, 9353920L, 8846640L, 6450688L, 6450640L, 0L); case 5: return CreateOffsets(9321040L, 9332320L, 0L, 9354320L, 8847008L, 6451552L, 6451504L, 0L); case 6: return CreateOffsets(9321952L, 9333232L, 0L, 9355232L, 8847920L, 6451568L, 6451520L, 0L); case 7: return CreateOffsets(9321952L, 9333232L, 0L, 9355232L, 8847920L, 6451568L, 6451520L, 0L); case 8: return CreateOffsets(9320432L, 9331712L, 0L, 9353712L, 8846352L, 6449696L, 6449648L, 0L); case 9: return CreateOffsets(9326096L, 9337376L, 0L, 9359376L, 8851888L, 6453808L, 6453760L, 0L); case 10: return CreateOffsets(9336368L, 9347648L, 0L, 9369648L, 8862128L, 6460048L, 6460000L, 0L); case 11: return CreateOffsets(9336816L, 9348096L, 0L, 9370096L, 8862576L, 6460544L, 6460496L, 0L); case 12: return CreateOffsets(9337168L, 9348448L, 0L, 9370448L, 8862928L, 6460896L, 6460848L, 0L); case 13: return CreateOffsets(9339296L, 9350576L, 0L, 9372576L, 8864832L, 6460512L, 6460464L, 0L); case 14: return CreateOffsets(9343008L, 9354288L, 0L, 9376048L, 8868544L, 6462976L, 6462928L, 0L); case 15: return CreateOffsets(9346320L, 9357600L, 0L, 9379360L, 8871840L, 6465216L, 6465168L, 0L); case 16: return CreateOffsets(9348000L, 9359280L, 0L, 9381040L, 8873504L, 6466592L, 6466544L, 0L); case 17: return CreateOffsets(9349424L, 9360704L, 0L, 9382464L, 8874928L, 6467872L, 6467824L, 0L); case 18: return CreateOffsets(9351392L, 9362672L, 0L, 9384432L, 8875168L, 6468128L, 6468080L, 0L); case 19: return CreateOffsets(9353920L, 9365200L, 0L, 9386960L, 8877696L, 6468832L, 6468784L, 0L); case 20: return CreateOffsets(9354640L, 9365920L, 0L, 9387680L, 8878352L, 6469520L, 6469472L, 0L); case 21: return CreateOffsets(9354608L, 9365888L, 0L, 9387648L, 8878288L, 6469488L, 6469440L, 0L); case 22: return CreateOffsets(9355392L, 9366672L, 0L, 9388432L, 8879072L, 6469920L, 6469872L, 0L); case 23: return CreateOffsets(9349008L, 9360288L, 0L, 9382048L, 8872688L, 6469296L, 6469248L, 0L); case 24: return CreateOffsets(9354976L, 9366256L, 0L, 9388016L, 8878656L, 6474432L, 6474384L, 0L); case 25: return CreateOffsets(9358448L, 9369728L, 0L, 9391488L, 8882128L, 6477616L, 6477568L, 0L); case 26: return CreateOffsets(9360176L, 9371456L, 0L, 9393216L, 8883840L, 6478464L, 6478416L, 0L); case 27: return CreateOffsets(9362704L, 9373984L, 0L, 9395744L, 8885872L, 6478688L, 6478640L, 0L); case 28: return CreateOffsets(9361728L, 9373008L, 0L, 9394768L, 8884896L, 6477680L, 6477632L, 0L); case 29: return CreateOffsets(9363568L, 9374848L, 0L, 9396608L, 8886736L, 6478832L, 6478784L, 0L); case 30: return CreateOffsets(9365728L, 9377008L, 0L, 9398816L, 8888896L, 6479888L, 6479840L, 0L); case 31: return CreateOffsets(9365968L, 9377248L, 0L, 9399056L, 8889136L, 6479904L, 6479856L, 0L); case 32: return CreateOffsets(9366304L, 9377584L, 0L, 9399392L, 8889472L, 6480000L, 6479952L, 0L); case 33: return CreateOffsets(9366320L, 9377600L, 0L, 9399408L, 8889488L, 6480000L, 6479952L, 0L); case 34: return CreateOffsets(9369360L, 9380640L, 0L, 9402448L, 8892528L, 6480000L, 6479952L, 0L); case 35: return CreateOffsets(9369712L, 9380992L, 0L, 9402800L, 8892880L, 6480352L, 6480304L, 0L); case 36: return CreateOffsets(9370320L, 9381600L, 0L, 9403408L, 8893280L, 6480688L, 6480640L, 0L); } break; } break; case 2019: switch (unityVersion.Minor) { case 1: switch (unityVersion.Build) { case 0: return CreateOffsets(9142272L, 9166192L, 0L, 9200784L, 8543344L, 6065712L, 6065664L, 0L); case 1: return CreateOffsets(9143856L, 9167776L, 0L, 9202368L, 8544928L, 6067216L, 6067168L, 0L); case 2: return CreateOffsets(9145552L, 9169472L, 0L, 9204064L, 8546624L, 6067984L, 6067936L, 0L); case 3: return CreateOffsets(9146416L, 9170336L, 0L, 9204928L, 8529248L, 6068992L, 6068944L, 0L); case 4: return CreateOffsets(9138256L, 9162176L, 0L, 9196768L, 8521088L, 6060064L, 6060016L, 0L); case 5: return CreateOffsets(9138256L, 9162176L, 0L, 9196768L, 8521088L, 6060064L, 6060016L, 0L); case 6: return CreateOffsets(9137808L, 9161728L, 0L, 9196320L, 8520512L, 6058848L, 6058800L, 0L); case 7: return CreateOffsets(9138304L, 9162224L, 0L, 9196816L, 8521008L, 6059136L, 6059088L, 0L); case 8: return CreateOffsets(9138224L, 9162144L, 0L, 9196736L, 8520928L, 6058912L, 6058864L, 0L); case 9: return CreateOffsets(9139280L, 9163200L, 0L, 9197792L, 8521984L, 6059792L, 6059744L, 0L); case 10: return CreateOffsets(9138688L, 9162624L, 0L, 9197216L, 8521392L, 6059968L, 6059920L, 0L); case 11: return CreateOffsets(9138720L, 9162656L, 0L, 9197248L, 8521424L, 6059968L, 6059920L, 0L); case 12: return CreateOffsets(9138720L, 9162656L, 0L, 9197248L, 8521424L, 6059968L, 6059920L, 0L); case 13: return CreateOffsets(9139200L, 9163136L, 0L, 9197728L, 8521904L, 6059776L, 6059728L, 0L); case 14: return CreateOffsets(9140224L, 9164160L, 0L, 9198880L, 8522928L, 6060784L, 6060736L, 0L); } break; case 2: switch (unityVersion.Build) { case 0: return CreateOffsets(8830144L, 8854096L, 0L, 8888896L, 8195296L, 5738272L, 5738224L, 0L); case 1: return CreateOffsets(8830880L, 8854832L, 0L, 8889632L, 8196048L, 5738352L, 5738304L, 0L); case 2: return CreateOffsets(8832304L, 8856256L, 0L, 8891056L, 8197472L, 5738448L, 5738400L, 0L); case 3: return CreateOffsets(8833472L, 8857424L, 0L, 8892224L, 8198640L, 5739584L, 5739536L, 0L); case 4: return CreateOffsets(8836032L, 8859984L, 0L, 8894784L, 8201200L, 5741568L, 5741520L, 0L); case 5: return CreateOffsets(8836160L, 8860112L, 0L, 8894912L, 8201264L, 5740976L, 5740928L, 0L); case 6: return CreateOffsets(8835888L, 8859840L, 0L, 8894640L, 8200992L, 5740496L, 5740448L, 0L); case 7: return CreateOffsets(8837152L, 8861104L, 0L, 8895664L, 8202256L, 5740416L, 5740368L, 0L); case 8: return CreateOffsets(8837488L, 8861456L, 0L, 8896016L, 8202512L, 5740656L, 5740608L, 0L); case 9: return CreateOffsets(8838368L, 8862336L, 0L, 8896896L, 8203392L, 5741088L, 5741040L, 0L); case 10: return CreateOffsets(8839008L, 8862976L, 0L, 8897536L, 8203888L, 5741600L, 5741552L, 0L); case 11: return CreateOffsets(8839552L, 8863520L, 0L, 8898080L, 8204432L, 5742048L, 5742000L, 0L); case 12: return CreateOffsets(8839696L, 8863664L, 0L, 8898224L, 8204576L, 5742080L, 5742032L, 0L); case 13: return CreateOffsets(8840752L, 8864720L, 0L, 8899280L, 8205632L, 5742160L, 5742112L, 0L); case 14: return CreateOffsets(8842256L, 8866224L, 0L, 8900784L, 8207120L, 5742704L, 5742656L, 0L); case 15: return CreateOffsets(8842736L, 8866704L, 0L, 8901264L, 8207600L, 5743184L, 5743136L, 0L); case 16: return CreateOffsets(8843440L, 8867408L, 0L, 8901968L, 8208272L, 5743728L, 5743680L, 0L); case 17: return CreateOffsets(8845744L, 8869712L, 0L, 8904272L, 8210576L, 5745920L, 5745872L, 0L); case 18: return CreateOffsets(8845136L, 8869104L, 0L, 8903664L, 8209968L, 5744992L, 5744944L, 0L); case 19: return CreateOffsets(8840176L, 8864144L, 0L, 8898704L, 8205008L, 5740032L, 5739984L, 0L); case 20: return CreateOffsets(8840400L, 8864368L, 0L, 8898928L, 8205200L, 5740224L, 5740176L, 0L); case 21: return CreateOffsets(8840400L, 8864368L, 0L, 8898928L, 8205200L, 5740224L, 5740176L, 0L); } break; case 3: switch (unityVersion.Build) { case 0: return CreateOffsets(9002592L, 9014576L, 0L, 9035568L, 8329232L, 5734800L, 5734704L, 0L); case 1: return CreateOffsets(9004928L, 9016912L, 0L, 9037904L, 8331648L, 5735296L, 5735200L, 0L); case 2: return CreateOffsets(9006448L, 9018432L, 0L, 9039424L, 8333168L, 5738096L, 5738000L, 0L); case 3: return CreateOffsets(9006592L, 9018576L, 0L, 9039568L, 8333312L, 5738112L, 5738016L, 0L); case 4: return CreateOffsets(9012320L, 9024304L, 0L, 9045296L, 8339040L, 5740016L, 5739920L, 0L); case 5: return CreateOffsets(9014880L, 9026864L, 0L, 9047856L, 8341600L, 5741152L, 5741056L, 0L); case 6: return CreateOffsets(9021328L, 9033312L, 0L, 9054368L, 8347568L, 5745680L, 5745584L, 0L); case 7: return CreateOffsets(9024528L, 9036512L, 0L, 9057568L, 8350736L, 5747968L, 5747872L, 0L); case 8: return CreateOffsets(9033456L, 9045440L, 0L, 9066496L, 8359664L, 5748608L, 5748512L, 0L); case 9: return CreateOffsets(9034000L, 9045984L, 0L, 9067040L, 8360208L, 5747904L, 5747808L, 0L); case 10: return CreateOffsets(9034928L, 9046912L, 0L, 9067968L, 8360784L, 5748128L, 5748032L, 0L); case 11: return CreateOffsets(9041712L, 9053696L, 0L, 9074752L, 8367376L, 5753664L, 5753568L, 0L); case 12: return CreateOffsets(9042576L, 9054560L, 0L, 9075616L, 8367808L, 5754080L, 5753984L, 0L); case 13: return CreateOffsets(9043520L, 9055504L, 0L, 9076560L, 8368720L, 5754912L, 5754816L, 0L); case 14: return CreateOffsets(9045920L, 9057904L, 0L, 9078960L, 8371104L, 5757152L, 5757056L, 0L); case 15: return CreateOffsets(9057024L, 9069008L, 0L, 9090064L, 8382144L, 5765296L, 5765200L, 0L); } break; case 4: switch (unityVersion.Build) { case 0: return CreateOffsets(9058752L, 9070736L, 0L, 9091792L, 8383872L, 5765664L, 5765568L, 0L); case 1: return CreateOffsets(9058816L, 9070768L, 0L, 9091856L, 8383936L, 5765664L, 5765568L, 0L); case 2: return CreateOffsets(9060704L, 9072656L, 0L, 9093744L, 8385824L, 5766816L, 5766720L, 0L); case 3: return CreateOffsets(9067440L, 9079392L, 0L, 9100480L, 8392560L, 5771232L, 5771136L, 0L); case 4: return CreateOffsets(9067552L, 9079504L, 0L, 9100592L, 8392672L, 5771232L, 5771136L, 0L); case 5: return CreateOffsets(9068288L, 9080240L, 0L, 9101328L, 8393392L, 5771584L, 5771488L, 0L); case 6: return CreateOffsets(9069664L, 9081616L, 0L, 9102704L, 8394752L, 5772672L, 5772576L, 0L); case 7: return CreateOffsets(9073056L, 9085008L, 0L, 9106096L, 8398112L, 5775648L, 5775552L, 0L); case 8: return CreateOffsets(9073008L, 9084960L, 0L, 9106048L, 8398064L, 5775184L, 5775088L, 0L); case 9: return CreateOffsets(9081712L, 9093664L, 0L, 9114752L, 8406224L, 5776832L, 5776736L, 0L); case 10: return CreateOffsets(9087568L, 9099520L, 0L, 9120608L, 8412080L, 5782096L, 5782000L, 0L); case 11: return CreateOffsets(9089136L, 9101088L, 0L, 9122176L, 8413760L, 5782416L, 5782320L, 0L); case 12: return CreateOffsets(9091056L, 9103008L, 0L, 9124096L, 8415344L, 5785168L, 5785072L, 0L); case 13: return CreateOffsets(9091792L, 9103744L, 0L, 9124832L, 8416080L, 5785440L, 5785344L, 0L); case 14: return CreateOffsets(9092352L, 9104304L, 0L, 9125392L, 8416640L, 5785776L, 5785680L, 0L); case 15: return CreateOffsets(9092848L, 9104800L, 0L, 9125888L, 8416976L, 5786064L, 5785968L, 0L); case 16: return CreateOffsets(9098160L, 9110112L, 0L, 9131232L, 8422144L, 5789232L, 5789136L, 0L); case 17: return CreateOffsets(9101728L, 9113680L, 0L, 9134800L, 8425008L, 5791824L, 5791728L, 0L); case 18: return CreateOffsets(9107216L, 9119168L, 0L, 9140288L, 8430512L, 5795952L, 5795856L, 0L); case 19: return CreateOffsets(9110464L, 9122416L, 0L, 9143536L, 8433616L, 5796864L, 5796768L, 0L); case 20: return CreateOffsets(9115296L, 9127248L, 0L, 9148368L, 8437840L, 5800832L, 5800736L, 0L); case 21: return CreateOffsets(9110672L, 9122688L, 0L, 9143808L, 8433184L, 5795968L, 5795872L, 0L); case 22: return CreateOffsets(9115872L, 9127888L, 0L, 9149008L, 8438336L, 5798352L, 5798256L, 0L); case 23: return CreateOffsets(9138784L, 9150800L, 0L, 9170672L, 8459856L, 5818064L, 5817968L, 0L); case 24: return CreateOffsets(9144336L, 9156320L, 0L, 9176112L, 8465104L, 5825632L, 5825536L, 0L); case 25: return CreateOffsets(9144416L, 9156400L, 0L, 9176192L, 8465248L, 5825712L, 5825616L, 0L); case 26: return CreateOffsets(9146160L, 9158144L, 0L, 9177936L, 8466288L, 5825760L, 5825664L, 0L); case 27: return CreateOffsets(9148608L, 9160592L, 0L, 9180272L, 8468752L, 5827792L, 5827696L, 0L); case 28: return CreateOffsets(9149168L, 9161152L, 0L, 9180832L, 8469280L, 5827984L, 5827888L, 0L); case 29: return CreateOffsets(9154368L, 9166368L, 0L, 9186048L, 8474480L, 5829488L, 5829392L, 0L); case 30: return CreateOffsets(9158224L, 9170224L, 0L, 9189904L, 8478336L, 5832976L, 5832880L, 0L); case 31: return CreateOffsets(9169952L, 9181936L, 0L, 9201616L, 8490064L, 5841152L, 5841056L, 0L); case 32: return CreateOffsets(9171328L, 9183312L, 0L, 9202992L, 8490320L, 5841600L, 5841504L, 0L); case 33: return CreateOffsets(9174592L, 9186576L, 0L, 9206256L, 8493584L, 5842464L, 5842368L, 0L); case 34: return CreateOffsets(9174576L, 9186560L, 0L, 9206240L, 8493568L, 5842416L, 5842320L, 0L); case 35: return CreateOffsets(9177728L, 9189712L, 0L, 9209392L, 8496720L, 5845248L, 5845152L, 0L); case 36: return CreateOffsets(9178992L, 9190976L, 0L, 9210656L, 8497968L, 5846416L, 5846320L, 0L); case 37: return CreateOffsets(9185360L, 9197344L, 0L, 9217008L, 8499712L, 5846544L, 5846448L, 0L); case 38: return CreateOffsets(9186160L, 9198144L, 0L, 9217808L, 8500480L, 5847360L, 5847264L, 0L); case 39: return CreateOffsets(9190464L, 9202448L, 0L, 9222112L, 8504784L, 5851648L, 5851552L, 0L); case 40: return CreateOffsets(9191424L, 9203408L, 0L, 9223072L, 8505728L, 5852480L, 5852384L, 0L); } break; } break; case 2020: switch (unityVersion.Minor) { case 1: switch (unityVersion.Build) { case 0: return CreateOffsets(8542848L, 8555104L, 0L, 8573920L, 7836576L, 5291184L, 5291088L, 0L); case 1: return CreateOffsets(8554816L, 8567072L, 0L, 8585888L, 7839760L, 5293008L, 5292912L, 0L); case 2: return CreateOffsets(8555040L, 8567296L, 0L, 8586112L, 7839984L, 5293232L, 5293136L, 0L); case 3: return CreateOffsets(8555136L, 8567392L, 0L, 8586208L, 7839888L, 5292896L, 5292800L, 0L); case 4: return CreateOffsets(8558144L, 8570400L, 0L, 8589216L, 7842480L, 5294512L, 5294416L, 0L); case 5: return CreateOffsets(8559504L, 8571728L, 0L, 8590576L, 7843552L, 5294336L, 5294240L, 0L); case 6: return CreateOffsets(8560112L, 8572336L, 0L, 8591184L, 7844160L, 5294912L, 5294816L, 0L); case 7: return CreateOffsets(8564240L, 8576464L, 0L, 8595312L, 7847888L, 5297120L, 5297024L, 0L); case 8: return CreateOffsets(8564064L, 8576288L, 0L, 8595136L, 7847712L, 5296976L, 5296880L, 0L); case 9: return CreateOffsets(8564496L, 8576720L, 0L, 8595568L, 7848144L, 5296720L, 5296624L, 0L); case 10: return CreateOffsets(8564688L, 8576912L, 0L, 8595760L, 7848336L, 5296992L, 5296896L, 0L); case 11: return CreateOffsets(8566320L, 8578544L, 0L, 8597392L, 7849968L, 5298736L, 5298640L, 0L); case 12: return CreateOffsets(8566672L, 8578896L, 0L, 8597744L, 7850320L, 5298864L, 5298768L, 0L); case 13: return CreateOffsets(8572176L, 8584400L, 0L, 8603248L, 7855856L, 5304352L, 5304256L, 0L); case 14: return CreateOffsets(8577376L, 8589616L, 0L, 8608368L, 7861024L, 5307440L, 5307344L, 0L); case 15: return CreateOffsets(8580352L, 8592592L, 0L, 8611376L, 7863840L, 5309536L, 5309440L, 0L); case 16: return CreateOffsets(8585936L, 8598176L, 0L, 8616960L, 7869040L, 5312880L, 5312784L, 0L); case 17: return CreateOffsets(8586304L, 8598544L, 0L, 8617328L, 7869408L, 5313072L, 5312976L, 0L); } break; case 2: switch (unityVersion.Build) { case 0: return CreateOffsets(9087040L, 9101408L, 0L, 9122512L, 8355392L, 5680336L, 5680240L, 26666624L); case 1: return CreateOffsets(9087040L, 9101408L, 0L, 9122512L, 8355392L, 5680336L, 5680240L, 26666624L); case 2: return CreateOffsets(9090976L, 9105344L, 0L, 9126448L, 8358752L, 5682848L, 5682752L, 26670784L); case 3: return CreateOffsets(9100640L, 9115008L, 0L, 9136112L, 8368192L, 5685776L, 5685680L, 26687232L); case 4: return CreateOffsets(9101840L, 9116208L, 0L, 9137344L, 8369392L, 5686848L, 5686752L, 26695488L); case 5: return CreateOffsets(9103824L, 9118192L, 0L, 9139328L, 8371376L, 5688016L, 5687920L, 26699712L); case 6: return CreateOffsets(9099936L, 9114304L, 0L, 9135440L, 8367488L, 5683312L, 5683216L, 26703744L); case 7: return CreateOffsets(9101744L, 9116112L, 0L, 9137248L, 8369296L, 5684752L, 5684656L, 26708096L); } break; case 3: switch (unityVersion.Build) { case 0: return CreateOffsets(9102800L, 9117168L, 0L, 9138304L, 8370352L, 5684832L, 5684736L, 26708096L); case 1: return CreateOffsets(9135888L, 9150256L, 0L, 9171392L, 8402912L, 5718320L, 5718224L, 26753152L); case 2: return CreateOffsets(9137280L, 9151648L, 0L, 9172784L, 8404144L, 5718288L, 5718192L, 26757248L); case 3: return CreateOffsets(9139248L, 9153616L, 0L, 9174752L, 8406048L, 5719504L, 5719408L, 26757248L); case 4: return CreateOffsets(9139568L, 9153936L, 0L, 9175072L, 8406368L, 5719520L, 5719424L, 26757248L); case 5: return CreateOffsets(9147488L, 9161856L, 0L, 9182992L, 8413136L, 5724112L, 5724016L, 26773696L); case 6: return CreateOffsets(9146384L, 9160752L, 0L, 9181888L, 8412032L, 5724160L, 5724064L, 26769600L); case 7: return CreateOffsets(9147248L, 9161616L, 0L, 9182752L, 8412528L, 5724576L, 5724480L, 26777792L); case 8: return CreateOffsets(9147952L, 9162320L, 0L, 9183456L, 8412240L, 5724080L, 5723984L, 26474688L); case 9: return CreateOffsets(9148192L, 9162560L, 0L, 9183696L, 8412400L, 5724272L, 5724176L, 26538752L); case 10: return CreateOffsets(9156768L, 9171136L, 0L, 9192272L, 8420640L, 5724928L, 5724832L, 26547008L); case 11: return CreateOffsets(9160864L, 9175232L, 0L, 9196368L, 8424768L, 5728624L, 5728528L, 26551232L); case 12: return CreateOffsets(9161808L, 9176176L, 0L, 9197312L, 8425696L, 5729328L, 5729232L, 26543040L); case 13: return CreateOffsets(9163456L, 9177824L, 0L, 9198960L, 8427216L, 5730144L, 5730048L, 26547136L); case 14: return CreateOffsets(9165152L, 9179600L, 0L, 9200736L, 8428912L, 5731824L, 5731728L, 26563520L); case 15: return CreateOffsets(9165120L, 9179568L, 0L, 9200704L, 8428896L, 5731824L, 5731728L, 26563520L); case 16: return CreateOffsets(9168512L, 9182944L, 0L, 9203904L, 8432208L, 5734288L, 5734192L, 26571712L); case 17: return CreateOffsets(9173248L, 9187680L, 0L, 9208640L, 8436928L, 5738592L, 5738496L, 26584256L); case 18: return CreateOffsets(9191056L, 9205488L, 0L, 9226448L, 8454496L, 5755536L, 5755440L, 26600640L); case 19: return CreateOffsets(9191200L, 9205632L, 0L, 9226592L, 8454928L, 5755040L, 5754944L, 26600576L); case 20: return CreateOffsets(9191680L, 9206112L, 0L, 9227072L, 8455296L, 5755216L, 5755120L, 26600576L); case 21: return CreateOffsets(9192784L, 9207216L, 0L, 9228176L, 8455472L, 5755168L, 5755072L, 26625152L); case 22: return CreateOffsets(9196320L, 9210752L, 0L, 9231712L, 8458960L, 5756528L, 5756432L, 26629248L); case 23: return CreateOffsets(9193808L, 9208240L, 0L, 9229200L, 8458000L, 5757024L, 5756928L, 26625344L); case 24: return CreateOffsets(9195328L, 9209760L, 0L, 9230720L, 8459424L, 5758448L, 5758352L, 26695168L); case 25: return CreateOffsets(9202192L, 9216624L, 0L, 9237584L, 8466400L, 5765376L, 5765280L, 26703360L); case 26: return CreateOffsets(9202848L, 9217280L, 0L, 9238240L, 8467040L, 5766048L, 5765952L, 26703360L); case 27: return CreateOffsets(9207264L, 9221696L, 0L, 9242656L, 8470784L, 5769712L, 5769616L, 26707520L); case 28: return CreateOffsets(9209568L, 9224000L, 0L, 9244960L, 8473024L, 5771328L, 5771232L, 26711616L); case 29: return CreateOffsets(9211408L, 9225840L, 0L, 9246800L, 8474864L, 5771968L, 5771872L, 26703552L); case 30: return CreateOffsets(9212528L, 9226960L, 0L, 9247920L, 8475984L, 5772784L, 5772688L, 26703552L); case 31: return CreateOffsets(9244416L, 9259040L, 0L, 9280736L, 8497744L, 5787920L, 5787824L, 26744576L); case 32: return CreateOffsets(9245184L, 9259808L, 0L, 9281504L, 8498496L, 5788320L, 5788224L, 26748672L); case 33: return CreateOffsets(9244608L, 9259232L, 0L, 9280928L, 8497856L, 5787920L, 5787824L, 26748672L); case 34: return CreateOffsets(9244960L, 9259584L, 0L, 9281280L, 8497920L, 5787904L, 5787808L, 26752768L); case 35: return CreateOffsets(9247424L, 9262048L, 0L, 9283744L, 8500256L, 5788576L, 5788480L, 26752768L); case 36: return CreateOffsets(9247872L, 9262496L, 0L, 9284192L, 8500704L, 5788832L, 5788736L, 26760960L); case 37: return CreateOffsets(9251104L, 9265728L, 0L, 9287424L, 8503936L, 5789952L, 5789856L, 26777344L); case 38: return CreateOffsets(9260896L, 9275552L, 0L, 9297248L, 8513648L, 5791632L, 5791536L, 26777472L); case 39: return CreateOffsets(9261504L, 9276160L, 0L, 9297856L, 8512864L, 5791952L, 5791856L, 26818368L); case 40: return CreateOffsets(9262560L, 9277216L, 0L, 9298912L, 8513920L, 5791984L, 5791888L, 26953536L); case 41: return CreateOffsets(9266896L, 9281552L, 0L, 9303248L, 8517680L, 5794032L, 5793936L, 26961920L); case 42: return CreateOffsets(9277136L, 9291792L, 0L, 9313488L, 8527648L, 5803488L, 5803392L, 26974208L); case 43: return CreateOffsets(9280848L, 9295504L, 0L, 9317200L, 8531360L, 5804160L, 5804064L, 26978304L); case 44: return CreateOffsets(9274672L, 9289280L, 0L, 9309952L, 8525120L, 5800848L, 5800752L, 26961856L); case 45: return CreateOffsets(8980480L, 8995088L, 0L, 9015760L, 8230560L, 5502768L, 5502672L, 26986432L); case 46: return CreateOffsets(8981712L, 8996320L, 0L, 9016992L, 8231792L, 5503600L, 5503504L, 26986496L); case 47: return CreateOffsets(8982128L, 8996736L, 0L, 9017408L, 8232208L, 5504064L, 5503968L, 26990592L); case 48: return CreateOffsets(8985392L, 9000000L, 0L, 9020672L, 8235664L, 5506688L, 5506592L, 26990592L); } break; } break; case 2021: switch (unityVersion.Minor) { case 1: switch (unityVersion.Build) { case 0: return CreateOffsets(9107152L, 9120176L, 0L, 9140112L, 8377760L, 5711216L, 5711120L, 26714752L); case 1: return CreateOffsets(9110304L, 9123328L, 0L, 9143264L, 8380848L, 5712688L, 5712592L, 26722944L); case 2: return CreateOffsets(9113344L, 9126368L, 0L, 9146304L, 8383744L, 5715584L, 5715488L, 26727040L); case 3: return CreateOffsets(9114656L, 9127680L, 0L, 9147616L, 8384640L, 5715888L, 5715792L, 26788480L); case 4: return CreateOffsets(9115632L, 9128656L, 0L, 9148592L, 8384608L, 5715568L, 5715472L, 26792576L); case 5: return CreateOffsets(9114752L, 9127776L, 0L, 9147696L, 8383792L, 5715440L, 5715344L, 26489472L); case 6: return CreateOffsets(9116704L, 9129728L, 0L, 9149648L, 8385456L, 5717264L, 5717168L, 26493568L); case 7: return CreateOffsets(9116688L, 9129712L, 0L, 9149632L, 8385440L, 5717168L, 5717072L, 26493568L); case 9: return CreateOffsets(9119360L, 9132464L, 0L, 9152384L, 8387840L, 5718240L, 5718144L, 26485440L); case 10: return CreateOffsets(9122064L, 9135168L, 0L, 9155088L, 8390288L, 5720304L, 5720208L, 26489536L); case 11: return CreateOffsets(9122064L, 9135168L, 0L, 9155088L, 8390288L, 5720304L, 5720208L, 26489536L); case 12: return CreateOffsets(9122128L, 9135232L, 0L, 9155152L, 8390336L, 5720352L, 5720256L, 26489536L); case 13: return CreateOffsets(9122272L, 9135376L, 0L, 9155296L, 8390480L, 5720496L, 5720400L, 26489536L); case 14: return CreateOffsets(9123696L, 9136800L, 0L, 9156720L, 8391904L, 5721936L, 5721840L, 26493632L); case 15: return CreateOffsets(9124368L, 9137488L, 0L, 9157328L, 8392640L, 5722672L, 5722576L, 26505920L); case 16: return CreateOffsets(9001600L, 9014720L, 0L, 9034560L, 8269728L, 5600688L, 5600592L, 26516224L); case 17: return CreateOffsets(9004032L, 9017152L, 0L, 9036992L, 8272096L, 5602304L, 5602208L, 26520320L); case 18: return CreateOffsets(9020048L, 9033168L, 0L, 9053008L, 8288016L, 5618256L, 5618160L, 26537024L); case 19: return CreateOffsets(9021216L, 9034336L, 0L, 9054176L, 8289184L, 5619216L, 5619120L, 26537024L); case 20: return CreateOffsets(9022272L, 9035392L, 0L, 9055232L, 8290240L, 5620112L, 5620016L, 26541120L); case 21: return CreateOffsets(9022752L, 9035872L, 0L, 9055712L, 8290672L, 5620336L, 5620240L, 26541120L); case 22: return CreateOffsets(9023920L, 9037040L, 0L, 9056880L, 8292032L, 5620320L, 5620224L, 26541120L); case 23: return CreateOffsets(9023392L, 9036512L, 0L, 9056352L, 8291504L, 5620032L, 5619936L, 26541120L); case 24: return CreateOffsets(9022208L, 9035328L, 0L, 9055168L, 8290352L, 5618944L, 5618848L, 26561600L); case 25: return CreateOffsets(9026880L, 9040000L, 0L, 9059840L, 8294112L, 5620704L, 5620608L, 26569792L); case 26: return CreateOffsets(9027472L, 9040592L, 0L, 9060432L, 8294688L, 5621152L, 5621056L, 26569792L); case 27: return CreateOffsets(9026768L, 9039888L, 0L, 9059728L, 8293984L, 5620224L, 5620128L, 26569792L); case 28: return CreateOffsets(9026528L, 9039648L, 0L, 9059488L, 8293680L, 5619808L, 5619712L, 26569792L); } break; case 2: switch (unityVersion.Build) { case 0: return CreateOffsets(6652704L, 6667376L, 0L, 6692368L, 5807344L, 2872928L, 2872848L, 27258624L); case 1: return CreateOffsets(6652976L, 6667648L, 0L, 6692640L, 5807568L, 2872928L, 2872848L, 27258624L); case 2: return CreateOffsets(6655264L, 6669936L, 0L, 6694928L, 5809856L, 2874560L, 2874480L, 27266880L); case 3: return CreateOffsets(6656032L, 6670704L, 0L, 6695696L, 5810656L, 2874464L, 2874384L, 27271040L); case 4: return CreateOffsets(6655456L, 6670128L, 0L, 6695120L, 5810080L, 2874688L, 2874608L, 27271232L); case 5: return CreateOffsets(6656720L, 6671392L, 0L, 6696384L, 5811344L, 2875344L, 2875264L, 27275200L); case 6: return CreateOffsets(6657024L, 6671696L, 0L, 6696688L, 5811648L, 2875344L, 2875264L, 27275264L); case 7: return CreateOffsets(6657344L, 6672016L, 0L, 6697008L, 5811968L, 2875664L, 2875584L, 27279360L); case 8: return CreateOffsets(6658624L, 6673296L, 0L, 6698288L, 5813216L, 2876048L, 2875968L, 27287616L); case 9: return CreateOffsets(6659744L, 6674416L, 0L, 6699408L, 5814192L, 2876384L, 2876304L, 27291776L); case 10: return CreateOffsets(6660320L, 6674992L, 0L, 6699984L, 5814064L, 2876384L, 2876304L, 27295872L); case 11: return CreateOffsets(6660240L, 6674912L, 0L, 6699904L, 5813984L, 2876272L, 2876192L, 27295872L); case 12: return CreateOffsets(6661344L, 6676016L, 0L, 6701008L, 5815104L, 2876528L, 2876448L, 27300096L); case 13: return CreateOffsets(6661360L, 6676032L, 0L, 6701024L, 5815104L, 2876528L, 2876448L, 27300096L); case 14: return CreateOffsets(6661744L, 6676416L, 0L, 6701408L, 5815488L, 2876528L, 2876448L, 27300096L); case 15: return CreateOffsets(6661744L, 6676416L, 0L, 6701408L, 5815488L, 2876528L, 2876448L, 27304192L); case 16: return CreateOffsets(6661744L, 6676416L, 0L, 6701408L, 5815488L, 2876528L, 2876448L, 27312384L); case 17: return CreateOffsets(6663264L, 6677952L, 0L, 6702672L, 5815616L, 2876528L, 2876448L, 27320576L); case 18: return CreateOffsets(6666800L, 6681488L, 0L, 6706208L, 5819664L, 2877440L, 2877360L, 27324672L); case 19: return CreateOffsets(6666928L, 6681616L, 0L, 6706336L, 5819792L, 2877744L, 2877664L, 27324672L); } break; case 3: switch (unityVersion.Build) { case 0: return CreateOffsets(6666928L, 6681616L, 0L, 6706336L, 5819792L, 2877744L, 2877664L, 27324672L); case 1: return CreateOffsets(6668880L, 6683568L, 0L, 6708288L, 5821696L, 2877744L, 2877664L, 27328768L); case 2: return CreateOffsets(6669776L, 6684464L, 0L, 6709184L, 5822160L, 2877744L, 2877664L, 27332864L); case 3: return CreateOffsets(6669856L, 6684544L, 0L, 6709264L, 5822240L, 2877840L, 2877760L, 27337024L); case 4: return CreateOffsets(6672928L, 6687616L, 0L, 6712336L, 5825312L, 2878608L, 2878528L, 27345152L); case 5: return CreateOffsets(6674656L, 6689344L, 0L, 6714064L, 5826928L, 2878640L, 2878560L, 27345216L); case 6: return CreateOffsets(6376752L, 6391440L, 0L, 6416160L, 5529024L, 2580704L, 2580624L, 27369792L); case 7: return CreateOffsets(6380896L, 6395584L, 0L, 6420304L, 5533168L, 2583872L, 2583792L, 27373888L); case 8: return CreateOffsets(6381040L, 6395728L, 0L, 6452416L, 5533312L, 2583936L, 2583856L, 27374208L); case 9: return CreateOffsets(6386512L, 6401152L, 0L, 6457664L, 5538928L, 2583632L, 2583552L, 27370112L); case 10: return CreateOffsets(6393664L, 6408304L, 0L, 6464816L, 5546064L, 2584256L, 2584176L, 27386560L); case 11: return CreateOffsets(6395648L, 6410288L, 0L, 6466800L, 5547456L, 2584576L, 2584496L, 27517632L); case 12: return CreateOffsets(6410224L, 6424864L, 0L, 6481392L, 5559296L, 2586112L, 2586032L, 27543424L); case 13: return CreateOffsets(6411888L, 6426528L, 0L, 6483056L, 5560272L, 2586288L, 2586208L, 27551616L); case 14: return CreateOffsets(6413456L, 6428096L, 0L, 6484624L, 5561808L, 2586528L, 2586448L, 27563968L); case 15: return CreateOffsets(6416896L, 6431536L, 0L, 6488064L, 5565216L, 2586608L, 2586528L, 27564032L); case 16: return CreateOffsets(6443840L, 6458480L, 0L, 6515008L, 5591552L, 2611616L, 2611536L, 27736704L); case 17: return CreateOffsets(6445008L, 6459648L, 0L, 6516176L, 5592960L, 2614560L, 2614480L, 27749120L); case 18: return CreateOffsets(6447856L, 6462496L, 0L, 6519040L, 5595792L, 2614864L, 2614784L, 27753344L); case 19: return CreateOffsets(6448480L, 6463120L, 0L, 6519664L, 5596128L, 2615088L, 2615008L, 27769728L); case 20: return CreateOffsets(6449712L, 6464352L, 0L, 6520896L, 5597360L, 2615744L, 2615664L, 27769792L); case 21: return CreateOffsets(6451840L, 6466480L, 0L, 6523024L, 5599184L, 2616480L, 2616400L, 27839424L); case 22: return CreateOffsets(6452016L, 6466656L, 0L, 6523200L, 5599360L, 2616480L, 2616400L, 27839424L); case 23: return CreateOffsets(6452656L, 6467296L, 0L, 6523840L, 5600192L, 2617376L, 2617296L, 27847680L); case 24: return CreateOffsets(6452688L, 6467328L, 0L, 6523872L, 5600176L, 2617376L, 2617296L, 27847680L); case 25: return CreateOffsets(6453056L, 6467696L, 0L, 6524240L, 5601376L, 2617424L, 2617344L, 27843584L); case 26: return CreateOffsets(6454560L, 6469200L, 0L, 6525744L, 5602864L, 2617472L, 2617392L, 27847680L); case 27: return CreateOffsets(6454800L, 6469440L, 0L, 6525984L, 5602880L, 2617472L, 2617392L, 27847680L); case 28: return CreateOffsets(6457680L, 6472320L, 0L, 6528864L, 5605600L, 2617744L, 2617664L, 27855872L); case 29: return CreateOffsets(6441072L, 6455712L, 0L, 6512256L, 5589024L, 2593760L, 2593680L, 27855936L); case 30: return CreateOffsets(6444464L, 6459104L, 0L, 6515648L, 5593776L, 2594128L, 2594048L, 27864128L); case 31: return CreateOffsets(6446528L, 6461168L, 0L, 6517712L, 5594896L, 2595088L, 2595008L, 27921472L); case 32: return CreateOffsets(6448704L, 6463344L, 0L, 6519888L, 5597008L, 2596272L, 2596192L, 27925568L); case 33: return CreateOffsets(6446528L, 6461168L, 0L, 6517712L, 5594304L, 2593680L, 2593600L, 27913152L); case 34: return CreateOffsets(6452272L, 6466912L, 0L, 6524096L, 5599184L, 2594336L, 2594256L, 27925504L); } break; } break; case 2022: switch (unityVersion.Minor) { case 1: switch (unityVersion.Build) { case 0: return CreateOffsets(6777184L, 6791680L, 0L, 6816768L, 5906960L, 2901088L, 2901008L, 27528640L); case 1: return CreateOffsets(6778016L, 6792528L, 0L, 6817616L, 5907392L, 2901232L, 2901152L, 27528640L); case 2: return CreateOffsets(6780976L, 6795488L, 0L, 6820576L, 5910352L, 2901600L, 2901520L, 27532672L); case 3: return CreateOffsets(6780976L, 6795488L, 0L, 6820576L, 5910352L, 2901600L, 2901520L, 27532672L); case 4: return CreateOffsets(6780608L, 6795120L, 0L, 6820208L, 5909984L, 2901600L, 2901520L, 27532672L); case 5: return CreateOffsets(6780608L, 6795120L, 0L, 6820208L, 5909984L, 2901600L, 2901520L, 27532672L); case 6: return CreateOffsets(6780528L, 6795040L, 0L, 6820128L, 5909600L, 2901600L, 2901520L, 27532672L); case 7: return CreateOffsets(6780528L, 6795040L, 0L, 6820128L, 5909600L, 2901600L, 2901520L, 27536768L); case 8: return CreateOffsets(6780848L, 6795360L, 0L, 6820448L, 5909920L, 2901600L, 2901520L, 27536768L); case 9: return CreateOffsets(6784272L, 6798784L, 0L, 6823872L, 5913344L, 2901888L, 2901808L, 27684224L); case 10: return CreateOffsets(6784272L, 6798784L, 0L, 6856288L, 5913344L, 2901888L, 2901808L, 27684480L); case 11: return CreateOffsets(6784272L, 6798784L, 0L, 6856288L, 5913344L, 2901888L, 2901808L, 27684480L); case 12: return CreateOffsets(6785312L, 6799824L, 0L, 6857344L, 5914368L, 2902112L, 2902032L, 27684544L); case 13: return CreateOffsets(6797280L, 6811792L, 0L, 6869312L, 5926352L, 2902112L, 2902032L, 27696832L); case 14: return CreateOffsets(6797104L, 6811616L, 0L, 6869136L, 5926176L, 2901952L, 2901872L, 27729600L); case 15: return CreateOffsets(6797104L, 6811616L, 0L, 6869136L, 5926176L, 2901952L, 2901872L, 27737792L); case 16: return CreateOffsets(6797360L, 6811872L, 0L, 6869392L, 5926176L, 2901952L, 2901872L, 27737792L); case 17: return CreateOffsets(6798208L, 6812720L, 0L, 6870240L, 5927024L, 2901936L, 2901856L, 27733696L); case 18: return CreateOffsets(6800912L, 6815424L, 0L, 6872944L, 5929184L, 2902288L, 2902208L, 27737920L); case 19: return CreateOffsets(6801392L, 6815904L, 0L, 6873424L, 5929664L, 2902608L, 2902528L, 27737920L); case 20: return CreateOffsets(6801376L, 6815888L, 0L, 6873408L, 5929648L, 2902592L, 2902512L, 27737920L); case 21: return CreateOffsets(6807376L, 6821888L, 0L, 6879408L, 5935264L, 2902992L, 2902912L, 27746176L); case 22: return CreateOffsets(6807568L, 6822080L, 0L, 6879600L, 5935456L, 2902992L, 2902912L, 27746176L); case 23: return CreateOffsets(6807968L, 6822480L, 0L, 6880000L, 5935744L, 2903152L, 2903072L, 27754368L); case 24: return CreateOffsets(6809360L, 6823872L, 0L, 6881392L, 5937024L, 2903152L, 2903072L, 27746176L); } break; case 2: switch (unityVersion.Build) { case 0: return CreateOffsets(7635360L, 7634128L, 0L, 7719360L, 6690192L, 3458912L, 6453920L, 28917696L); case 1: return CreateOffsets(7637952L, 7636720L, 0L, 7721952L, 6692784L, 3457664L, 6456512L, 28917760L); case 2: return CreateOffsets(7643824L, 7642592L, 0L, 7727824L, 6698096L, 3457296L, 6461824L, 28934144L); case 3: return CreateOffsets(7647840L, 7646608L, 0L, 7731840L, 6702048L, 3460656L, 6461728L, 28933120L); case 4: return CreateOffsets(7666592L, 7665360L, 0L, 7750896L, 6717104L, 3472224L, 6476864L, 28963136L); case 5: return CreateOffsets(7668512L, 7667280L, 0L, 7752832L, 6719024L, 3473280L, 6478784L, 28967168L); case 6: return CreateOffsets(7669008L, 7667776L, 0L, 7753328L, 6719184L, 3473216L, 6478944L, 28967232L); case 7: return CreateOffsets(7681936L, 7680704L, 0L, 7766256L, 6732192L, 3478656L, 6492608L, 28979520L); case 8: return CreateOffsets(7683840L, 7682608L, 0L, 7768160L, 6733888L, 3480368L, 6494320L, 28983616L); case 9: return CreateOffsets(7683616L, 7682384L, 0L, 7767936L, 6735184L, 3481280L, 6495616L, 28991808L); case 10: return CreateOffsets(7685120L, 7683888L, 0L, 7769440L, 6737008L, 3482176L, 6497424L, 28983616L); case 11: return CreateOffsets(7687392L, 7686160L, 0L, 7771712L, 6739120L, 3481888L, 6498848L, 28987776L); case 12: return CreateOffsets(7688928L, 7687696L, 0L, 7773248L, 6740656L, 3480112L, 6500384L, 28995968L); case 13: return CreateOffsets(7686160L, 7684928L, 0L, 7770480L, 6738016L, 3478880L, 6497744L, 28991872L); case 14: return CreateOffsets(7690688L, 7689456L, 0L, 7775008L, 6742544L, 3481072L, 6502272L, 29004224L); case 15: return CreateOffsets(7696432L, 7695200L, 0L, 7780784L, 6748528L, 3482784L, 6508256L, 29012416L); case 16: return CreateOffsets(7698016L, 7696784L, 0L, 7782368L, 6750352L, 3482544L, 6510080L, 29012288L); case 17: return CreateOffsets(7698752L, 7697520L, 0L, 7783104L, 6750816L, 3482528L, 6510528L, 29008128L); case 18: return CreateOffsets(7712128L, 7710896L, 0L, 7796480L, 6764032L, 3482960L, 6523504L, 29032896L); case 19: return CreateOffsets(7713040L, 7711808L, 0L, 7797392L, 6764944L, 3482992L, 6524416L, 29118976L); case 20: return CreateOffsets(7843536L, 7842304L, 0L, 7928272L, 6889552L, 3570320L, 6649504L, 29295232L); case 21: return CreateOffsets(7846064L, 7844832L, 0L, 7930800L, 6892224L, 3570592L, 6652176L, 29295296L); } break; case 3: switch (unityVersion.Build) { case 0: return CreateOffsets(7847584L, 7846352L, 0L, 7932528L, 6892992L, 3570704L, 6652400L, 29299392L); case 1: return CreateOffsets(7845168L, 7843936L, 0L, 7930080L, 6891360L, 3570512L, 6650848L, 29299456L); case 2: return CreateOffsets(7845584L, 7844352L, 0L, 7930496L, 6891600L, 3570656L, 6651088L, 29299456L); case 3: return CreateOffsets(7844976L, 7843744L, 0L, 7929888L, 6891504L, 3570768L, 6651024L, 29303552L); case 4: return CreateOffsets(7845360L, 7844128L, 0L, 7930272L, 6891872L, 3571136L, 6651392L, 29303552L); case 5: return CreateOffsets(7770736L, 7769504L, 0L, 7855648L, 6816912L, 3496112L, 6575392L, 29305024L); case 6: return CreateOffsets(7770304L, 7769072L, 0L, 7855216L, 6816176L, 3494512L, 6574496L, 29313280L); case 7: return CreateOffsets(7777520L, 7776288L, 0L, 7863936L, 6823312L, 3494432L, 6581392L, 29329856L); case 8: return CreateOffsets(7781552L, 7780320L, 0L, 7868240L, 6827904L, 3495520L, 6585968L, 29338048L); case 9: return CreateOffsets(7782592L, 7781360L, 0L, 7869280L, 6828848L, 3495632L, 6586912L, 29342272L); case 10: return CreateOffsets(7781968L, 7780736L, 0L, 7868656L, 6827888L, 3496800L, 6586336L, 29342208L); case 11: return CreateOffsets(7790496L, 7789264L, 0L, 7877248L, 6833280L, 3499872L, 6593040L, 29341760L); case 12: return CreateOffsets(7791136L, 7789904L, 0L, 7877920L, 6833904L, 3501472L, 6583520L, 29345984L); case 13: return CreateOffsets(7791744L, 7790512L, 0L, 7878528L, 6834000L, 3501568L, 6583616L, 29362368L); case 14: return CreateOffsets(7814944L, 7814464L, 0L, 7904272L, 6854512L, 3502448L, 6601600L, 29481152L); case 15: return CreateOffsets(7815904L, 7815424L, 0L, 7905408L, 6855280L, 3502128L, 6602368L, 29489344L); case 16: return CreateOffsets(7826928L, 7826448L, 0L, 7916400L, 6865920L, 3503072L, 6612752L, 29513984L); case 17: return CreateOffsets(7824736L, 7824256L, 0L, 7914208L, 6864000L, 3503088L, 6610832L, 29509824L); } break; } break; case 2023: switch (unityVersion.Minor) { case 1: switch (unityVersion.Build) { case 0: return CreateOffsets(6824560L, 6824016L, 0L, 6914080L, 5866960L, 2476800L, 5489344L, 28587648L); case 1: return CreateOffsets(6826352L, 6825808L, 0L, 6915872L, 5868752L, 2476976L, 5491168L, 28595840L); case 2: return CreateOffsets(6827456L, 6826912L, 0L, 6916976L, 5870496L, 2477888L, 5492912L, 28595840L); case 3: return CreateOffsets(6816704L, 6816160L, 0L, 6906224L, 5859744L, 2467136L, 5482208L, 28587648L); case 4: return CreateOffsets(6816736L, 6816192L, 0L, 6906256L, 5859776L, 2466688L, 5482192L, 28609600L); case 5: return CreateOffsets(6815968L, 6815424L, 0L, 6905488L, 5858960L, 2467248L, 5481376L, 28609600L); case 6: return CreateOffsets(6816400L, 6815856L, 0L, 6905920L, 5859392L, 2467328L, 5481648L, 28609600L); case 7: return CreateOffsets(6815216L, 6814672L, 0L, 6904736L, 5857920L, 2465872L, 5480176L, 28613696L); case 8: return CreateOffsets(6820336L, 6819792L, 0L, 6909856L, 5863088L, 2465664L, 5485104L, 28617728L); case 9: return CreateOffsets(6822976L, 6822432L, 0L, 6912768L, 5866416L, 2465712L, 5488416L, 28630080L); case 10: return CreateOffsets(6823552L, 6823008L, 0L, 6913344L, 5866944L, 2466208L, 5488944L, 28638272L); case 11: return CreateOffsets(6826448L, 6825904L, 0L, 6916240L, 5867984L, 2466320L, 5489984L, 28638272L); case 12: return CreateOffsets(6828720L, 6828176L, 0L, 6918512L, 5869888L, 2467312L, 5492480L, 28642496L); case 13: return CreateOffsets(6828992L, 6828448L, 0L, 6918784L, 5869984L, 2467872L, 5492560L, 28646592L); case 14: return CreateOffsets(6829424L, 6828880L, 0L, 6919216L, 5870368L, 2467888L, 5492944L, 28646656L); case 15: return CreateOffsets(6828320L, 6827776L, 0L, 6918112L, 5869312L, 2467792L, 5491776L, 28646656L); case 16: return CreateOffsets(6829280L, 6828736L, 0L, 6919072L, 5870272L, 2468448L, 5492352L, 28654848L); case 17: return CreateOffsets(6831440L, 6830896L, 0L, 6921152L, 5872336L, 2470672L, 5495888L, 28679488L); case 18: return CreateOffsets(6831792L, 6831248L, 0L, 6921552L, 5872672L, 2470912L, 5496224L, 28683584L); case 19: return CreateOffsets(6829024L, 6828480L, 0L, 6918784L, 5869904L, 2470928L, 5495696L, 28679488L); case 20: return CreateOffsets(6827824L, 6827280L, 0L, 6917296L, 5871216L, 2475888L, 5497056L, 28695872L); } break; case 2: switch (unityVersion.Build) { case 0: return CreateOffsets(7015696L, 7015120L, 0L, 7091776L, 6050128L, 2586768L, 2586960L, 29192896L); case 1: return CreateOffsets(7016576L, 7016000L, 0L, 7092672L, 6050928L, 2586416L, 2586608L, 29192896L); case 2: return CreateOffsets(7018288L, 7017712L, 0L, 7094384L, 6052832L, 2587200L, 2587392L, 29192896L); case 3: return CreateOffsets(7018224L, 7017648L, 0L, 7094320L, 6052768L, 2587216L, 2587408L, 29209280L); case 4: return CreateOffsets(7025840L, 7025264L, 0L, 7101952L, 6059616L, 2588864L, 2589056L, 29225664L); case 5: return CreateOffsets(7026144L, 7025568L, 0L, 7102256L, 6059888L, 2588880L, 2589072L, 29229760L); } break; } break; } return null; } private static Dictionary<string, long> CreateOffsets(long monoManagerAwakeFromLoadOffset, long monoManagerIsAssemblyCreatedOffset, long isFileCreatedOffset, long scriptingManagerDeconstructorOffset, long convertSeparatorsToPlatformOffset, long mallocInternalOffset, long freeAllocInternalOffset, long scriptingAssembliesOffset) { return new Dictionary<string, long> { ["MonoManagerAwakeFromLoadOffset"] = monoManagerAwakeFromLoadOffset, ["MonoManagerIsAssemblyCreatedOffset"] = monoManagerIsAssemblyCreatedOffset, ["IsFileCreatedOffset"] = isFileCreatedOffset, ["ScriptingManagerDeconstructorOffset"] = scriptingManagerDeconstructorOffset, ["ConvertSeparatorsToPlatformOffset"] = convertSeparatorsToPlatformOffset, ["MallocInternalOffset"] = mallocInternalOffset, ["FreeAllocInternalOffset"] = freeAllocInternalOffset, ["ScriptingAssembliesOffset"] = scriptingAssembliesOffset }; } } internal class MiniPdbReader { private static readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromMinutes(5.0) }; private readonly PeReader _peReader; private byte[] _pdbFile; internal bool IsPdbAvailable; internal bool UseCache; private static byte[] DownloadFromWeb(string url) { Log.Info("Downloading : " + url + "\nThis pdb file is needed for the plugin to work properly. This may take a while, relax, modding is coming."); try { HttpResponseMessage result = _httpClient.GetAsync(url).GetAwaiter().GetResult(); Log.Info("Status Code : " + result.StatusCode); if (result.StatusCode != HttpStatusCode.OK) { return null; } return result.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); } catch (TaskCanceledException) { Log.Info("Could not download pdb. Plugin may not work correctly."); return null; } } internal MiniPdbReader(string targetFilePath) { _peReader = new PeReader(targetFilePath); if (_peReader.RsdsPdbFileName == null) { Log.Info("No pdb path found in the pe file. Falling back to supported versions"); return; } UseCache = Config.LastDownloadedGUID.Value == _peReader.PdbGuid; Log.Message((UseCache ? "U" : "Not u") + "sing the config cache"); if (!UseCache) { if (DownloadUnityPdb(_peReader)) { Config.LastDownloadedGUID.Value = _peReader.PdbGuid; IsPdbAvailable = true; } else { Log.Info("Failed to find the linked pdb in the unity symbol server. Falling back to supported versions"); } } else { IsPdbAvailable = true; } } private bool DownloadUnityPdb(PeReader peReader) { //IL_0098: Unknown result type (might be due to invalid IL or missing references) string text = peReader.RsdsPdbFileName.TrimEnd(new char[1] { 'b' }) + "_"; byte[] array = DownloadFromWeb("http://symbolserver.unity3d.com/" + peReader.RsdsPdbFileName + "/" + peReader.PdbGuid + "/" + text); if (array != null) { string tempPath = Path.GetTempPath(); string text2 = Path.Combine(tempPath, "pdb.cab"); try { File.Delete(text2); } catch (Exception) { } Log.Info("Writing the compressed pdb to " + text2); File.WriteAllBytes(text2, array); CabInfo val = new CabInfo(text2); Log.Info("Unpacking the compressed pdb"); ((ArchiveInfo)val).Unpack(tempPath); string path = Path.Combine(tempPath, peReader.RsdsPdbFileName); _pdbFile = File.ReadAllBytes(path); File.Delete(text2); File.Delete(path); } return _pdbFile != null; } internal unsafe IntPtr FindFunctionOffset(BytePattern[] bytePatterns) { fixed (byte* ptr = &_pdbFile[0]) { IntPtr pdbStartAddress = (IntPtr)ptr; long sizeOfPdb = _pdbFile.Length; var anon = bytePatterns.Select((BytePattern p) => new { p = p, res = p.Match(pdbStartAddress, sizeOfPdb) }).FirstOrDefault(m => m.res > 0); if (anon == null) { return IntPtr.Zero; } Log.Info($"Found at {anon.res:X} ({pdbStartAddress.ToInt64() + anon.res:X})"); uint* ptr2 = (uint*)(pdbStartAddress.ToInt64() + anon.res - 7); uint num = *ptr2; ushort* ptr3 = (ushort*)(pdbStartAddress.ToInt64() + anon.res - 3); int num2 = *ptr3 - 1; num += _peReader.ImageSectionHeaders[num2].VirtualAddress; Log.Info("Function offset : " + num.ToString("X") + " | PE section : " + num2); return new IntPtr(num); } } } internal static class MonoManagerCommon { public unsafe static void CopyNativeAssemblyListToManagedV0(List<StringStorageDefaultV0> managedAssemblyList, Vector<StringStorageDefaultV0> assemblyNames) { managedAssemblyList.Clear(); for (StringStorageDefaultV0* ptr = assemblyNames.first; ptr != assemblyNames.last; ptr++) { managedAssemblyList.Add(*ptr); } } public unsafe static void AddAssembliesToManagedListV0(List<StringStorageDefaultV0> managedAssemblyList, List<string> pluginAssemblyPaths) { foreach (string pluginAssemblyPath in pluginAssemblyPaths) { string? fileName = Path.GetFileName(pluginAssemblyPath); ulong num = (ulong)fileName.Length; IntPtr intPtr = Marshal.StringToHGlobalAnsi(fileName); byte* ptr = (byte*)(void*)intPtr + num; while (*ptr != 0) { ptr++; num++; } StringStorageDefaultV0 stringStorageDefaultV = default(StringStorageDefaultV0); stringStorageDefaultV.data = intPtr; stringStorageDefaultV.extra1 = num; stringStorageDefaultV.size = num; stringStorageDefaultV.flags = 31uL; stringStorageDefaultV.extra2 = 0uL; StringStorageDefaultV0 item = stringStorageDefaultV; managedAssemblyList.Add(item); } } public unsafe static void AllocNativeAssemblyListFromManagedV0(List<StringStorageDefaultV0> managedAssemblyList, Vector<StringStorageDefaultV0>* assemblyNames) { StringStorageDefaultV0* ptr = (StringStorageDefaultV0*)(void*)Marshal.AllocHGlobal(Marshal.SizeOf(typeof(StringStorageDefaultV0)) * managedAssemblyList.Count); int i = 0; StringStorageDefaultV0* ptr2 = ptr; for (; i < managedAssemblyList.Count; i++) { *ptr2 = managedAssemblyList[i]; ptr2++; } assemblyNames->first = ptr; assemblyNames->last = ptr + managedAssemblyList.Count; assemblyNames->end = assemblyNames->last; } public unsafe static void PrintAssembliesV0(Vector<StringStorageDefaultV0> assemblyNames) { for (StringStorageDefaultV0* ptr = assemblyNames.first; ptr != assemblyNames.last; ptr++) { if (ptr->flags < 16) { Log.Warning("Ass: " + Marshal.PtrToStringAnsi((IntPtr)ptr)); } else { Log.Warning("Ass: " + Marshal.PtrToStringAnsi(ptr->data, (int)ptr->size)); } } } public unsafe static void CopyNativeAssemblyListToManagedV1(List<StringStorageDefaultV1> managedAssemblyList, Vector<StringStorageDefaultV1> assemblyNames) { managedAssemblyList.Clear(); for (StringStorageDefaultV1* ptr = assemblyNames.first; ptr != assemblyNames.last; ptr++) { managedAssemblyList.Add(*ptr); } } public unsafe static void AddAssembliesToManagedListV1(List<StringStorageDefaultV1> managedAssemblyList, List<string> pluginAssemblyPaths) { foreach (string pluginAssemblyPath in pluginAssemblyPaths) { string? fileName = Path.GetFileName(pluginAssemblyPath); ulong num = (ulong)fileName.Length; IntPtr intPtr = Marshal.StringToHGlobalAnsi(fileName); byte* ptr = (byte*)(void*)intPtr + num; while (*ptr != 0) { ptr++; num++; } StringStorageDefaultV1 stringStorageDefaultV = default(StringStorageDefaultV1); stringStorageDefaultV.label = UseRightStructs.LabelMemStringId; stringStorageDefaultV.data = intPtr; stringStorageDefaultV.capacity = num; stringStorageDefaultV.size = num; StringStorageDefaultV1 item = stringStorageDefaultV; managedAssemblyList.Add(item); } } public unsafe static void AllocNativeAssemblyListFromManagedV1(List<StringStorageDefaultV1> managedAssemblyList, Vector<StringStorageDefaultV1>* assemblyNames) { StringStorageDefaultV1* ptr = (StringStorageDefaultV1*)(void*)Marshal.AllocHGlobal(Marshal.SizeOf(typeof(StringStorageDefaultV1)) * managedAssemblyList.Count); int i = 0; StringStorageDefaultV1* ptr2 = ptr; for (; i < managedAssemblyList.Count; i++) { *ptr2 = managedAssemblyList[i]; ptr2++; } assemblyNames->first = ptr; assemblyNames->last = ptr + managedAssemblyList.Count; assemblyNames->end = assemblyNames->last; } public unsafe static void PrintAssembliesV1(Vector<StringStorageDefaultV1> assemblyNames) { for (StringStorageDefaultV1* ptr = assemblyNames.first; ptr != assemblyNames.last; ptr++) { nint ptr2 = ptr->data; if (ptr->data == 0) { ptr2 = (nint)((byte*)ptr + 8); } Log.Warning($"Ass: {Marshal.PtrToStringAnsi(ptr2, (int)ptr->size)} | label : {ptr->label:X}"); } } public unsafe static void CopyNativeAssemblyListToManagedV2(List<StringStorageDefaultV1> managedAssemblyList, DynamicArrayData assemblyNames) { managedAssemblyList.Clear(); ulong num = 0uL; StringStorageDefaultV1* ptr = (StringStorageDefaultV1*)assemblyNames.ptr; for (; num < assemblyNames.size; num++) { managedAssemblyList.Add(*ptr); ptr++; } } public unsafe static void AllocNativeAssemblyListFromManagedV2(List<StringStorageDefaultV1> managedAssemblyList, DynamicArrayData* assemblyNames) { StringStorageDefaultV1* ptr = (StringStorageDefaultV1*)(void*)Marshal.AllocHGlobal(Marshal.SizeOf(typeof(StringStorageDefaultV1)) * managedAssemblyList.Count); int i = 0; StringStorageDefaultV1* ptr2 = ptr; for (; i < managedAssemblyList.Count; i++) { *ptr2 = managedAssemblyList[i]; ptr2++; } assemblyNames->ptr = (nint)ptr; assemblyNames->size = (ulong)managedAssemblyList.Count; assemblyNames->capacity = assemblyNames->size; } public unsafe static void PrintAssembliesV2(DynamicArrayData assemblyNames) { ulong num = 0uL; StringStorageDefaultV1* ptr = (StringStorageDefaultV1*)assemblyNames.ptr; for (; num < assemblyNames.size; num++) { nint ptr2 = ptr->data; if (ptr->data == 0) { ptr2 = (nint)((byte*)ptr + 8); } Log.Warning($"Ass: {Marshal.PtrToStringAnsi(ptr2, (int)ptr->size)} | label : {ptr->label:X}"); ptr++; } } public unsafe static void CopyNativeAssemblyListToManagedV3(List<StringStorageDefaultV2> managedAssemblyList, DynamicArrayData assemblyNames) { managedAssemblyList.Clear(); ulong num = 0uL; StringStorageDefaultV2* ptr = (StringStorageDefaultV2*)assemblyNames.ptr; for (; num < assemblyNames.size; num++) { managedAssemblyList.Add(*ptr); ptr++; } } public unsafe static void AddAssembliesToManagedListV3(List<StringStorageDefaultV2> managedAssemblyList, List<string> pluginAssemblyPaths) { foreach (string pluginAssemblyPath in pluginAssemblyPaths) { string? fileName = Path.GetFileName(pluginAssemblyPath); ulong num = (ulong)fileName.Length; IntPtr intPtr = Marshal.StringToHGlobalAnsi(fileName); byte* ptr = (byte*)(void*)intPtr + num; while (*ptr != 0) { ptr++; num++; } StringStorageDefaultV2 stringStorageDefaultV = default(StringStorageDefaultV2); stringStorageDefaultV.union = new StringStorageDefaultV2Union { heap = new HeapAllocatedRepresentationV2 { data = intPtr, capacity = num, size = num } }; stringStorageDefaultV.data_repr = StringRepresentation.Heap; stringStorageDefaultV.label = UseRightStructs.LabelMemStringId; StringStorageDefaultV2 item = stringStorageDefaultV; managedAssemblyList.Add(item); } } public unsafe static void AllocNativeAssemblyListFromManagedV3(List<StringStorageDefaultV2> managedAssemblyList, DynamicArrayData* assemblyNames) { StringStorageDefaultV2* ptr = (StringStorageDefaultV2*)(void*)Marshal.AllocHGlobal(Marshal.SizeOf(typeof(StringStorageDefaultV2)) * managedAssemblyList.Count); int i = 0; StringStorageDefaultV2* ptr2 = ptr; for (; i < managedAssemblyList.Count; i++) { *ptr2 = managedAssemblyList[i]; ptr2++; } assemblyNames->ptr = (nint)ptr; assemblyNames->size = (ulong)managedAssemblyList.Count; assemblyNames->capacity = assemblyNames->size; } public unsafe static void PrintAssembliesV3(DynamicArrayData assemblyNames) { ulong num = 0uL; StringStorageDefaultV2* ptr = (StringStorageDefaultV2*)assemblyNames.ptr; for (; num < assemblyNames.size; num++) { if (ptr->data_repr == StringRepresentation.Embedded) { Log.Warning($"Ass: {Marshal.PtrToStringAnsi((IntPtr)ptr->union.embedded.data)} | label : {ptr->label:X}"); } else { Log.Warning($"Ass: {Marshal.PtrToStringAnsi(ptr->union.heap.data, (int)ptr->union.heap.size)} | label : {ptr->label:X}"); } ptr++; } } public unsafe static void CopyNativeAssemblyListToManagedV4(List<StringStorageDefaultV3> managedAssemblyList, DynamicArrayData assemblyNames) { managedAssemblyList.Clear(); ulong num = 0uL; StringStorageDefaultV3* ptr = (StringStorageDefaultV3*)assemblyNames.ptr; for (; num < assemblyNames.size; num++) { managedAssemblyList.Add(*ptr); ptr++; } } public unsafe static void AddAssembliesToManagedListV4(List<StringStorageDefaultV3> managedAssemblyList, List<string> pluginAssemblyPaths) { foreach (string pluginAssemblyPath in pluginAssemblyPaths) { string? fileName = Path.GetFileName(pluginAssemblyPath); ulong num = (ulong)fileName.Length; IntPtr intPtr = Marshal.StringToHGlobalAnsi(fileName); byte* ptr = (byte*)(void*)intPtr + num; while (*ptr != 0) { ptr++; num++; } StringStorageDefaultV3 stringStorageDefaultV = default(StringStorageDefaultV3); stringStorageDefaultV.union = new StringStorageDefaultV3Union { heap = new HeapAllocatedRepresentationV3 { data = intPtr, capacity = num, size = num, flags = new StringStorageDefaultV3Flags { IsHeap = true } } }; stringStorageDefaultV.label = UseRightStructs.LabelMemStringId; StringStorageDefaultV3 item = stringStorageDefaultV; managedAssemblyList.Add(item); } } public unsafe static void AllocNativeAssemblyListFromManagedV4(List<StringStorageDefaultV3> managedAssemblyList, DynamicArrayData* assemblyNames) { StringStorageDefaultV3* ptr = (StringStorageDefaultV3*)(void*)Marshal.AllocHGlobal(Marshal.SizeOf(typeof(StringStorageDefaultV3)) * managedAssemblyList.Count); int i = 0; StringStorageDefaultV3* ptr2 = ptr; for (; i < managedAssemblyList.Count; i++) { *ptr2 = managedAssemblyList[i]; ptr2++; } assemblyNames->ptr = (nint)ptr; assemblyNames->size = (ulong)managedAssemblyList.Count; assemblyNames->capacity = assemblyNames->size; } public unsafe static void PrintAssembliesV4(DynamicArrayData assemblyNames) { ulong num = 0uL; StringStorageDefaultV3* ptr = (StringStorageDefaultV3*)assemblyNames.ptr; for (; num < assemblyNames.size; num++) { if (ptr->union.embedded.flags.IsEmbedded) { Log.Warning($"Ass: {Marshal.PtrToStringAnsi((IntPtr)ptr->union.embedded.data)} | label : {ptr->label:X}"); } else { Log.Warning($"Ass: {Marshal.PtrToStringAnsi(ptr->union.heap.data, (int)ptr->union.heap.size)} | label : {ptr->label:X}"); } ptr++; } } } internal class PatternDiscoverer { private readonly IntPtr unityModule; private readonly MiniPdbReader pdbReader; private readonly bool usePdb; private readonly Dictionary<string, long> functionOffsets; public PatternDiscoverer(IntPtr unityModule, string unityPlayerPath) { this.unityModule = unityModule; switch (Config.FunctionOffsetLookupType.Value) { case FunctionOffsetLookup.Manual: break; case FunctionOffsetLookup.PreferPdb: pdbReader = new MiniPdbReader(unityPlayerPath); usePdb = pdbReader.IsPdbAvailable; if (!usePdb) { if (!FunctionOffsets.TryGet(UseRightStructs.UnityVersion, out functionOffsets)) { throw new NotSupportedException($"Pdb not found and {UseRightStructs.UnityVersion} is not a supported version"); } Log.Info("Found offsets for current version, using them."); } break; case FunctionOffsetLookup.PreferSupportedVersions: if (!FunctionOffsets.TryGet(UseRightStructs.UnityVersion, out functionOffsets)) { pdbReader = new MiniPdbReader(unityPlayerPath); usePdb = pdbReader.IsPdbAvailable; if (!usePdb) { throw new NotSupportedException($"{UseRightStructs.UnityVersion} is not a supported version and pdb not found"); } } else { Log.Info("Found offsets for current version, using them."); } break; default: throw new ArgumentException("FunctionOffsetLookupType"); } } public IntPtr Discover(ConfigEntry<string> functionOffsetCache, BytePattern[] pdbPatterns) { if (usePdb) { return DiscoverWithPdb(functionOffsetCache, pdbPatterns); } long num; if (functionOffsets != null) { num = functionOffsets[((ConfigEntryBase)functionOffsetCache).Definition.Key]; functionOffsetCache.Value = num.ToString("X2"); if (num == 0L) { return IntPtr.Zero; } IntPtr intPtr = unityModule; return (IntPtr)(intPtr.ToInt64() + num); } if (long.TryParse(functionOffsetCache.Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out num)) { IntPtr intPtr = unityModule; return (IntPtr)(intPtr.ToInt64() + num); } return IntPtr.Zero; } private IntPtr DiscoverWithPdb(ConfigEntry<string> functionOffsetCache, BytePattern[] pdbPatterns) { IntPtr intPtr; if (pdbReader.UseCache) { intPtr = new IntPtr(Convert.ToInt64(functionOffsetCache.Value, 16)); if (intPtr == IntPtr.Zero) { return intPtr; } } else { intPtr = pdbReader.FindFunctionOffset(pdbPatterns); if (intPtr == IntPtr.Zero) { functionOffsetCache.Value = "00"; return intPtr; } functionOffsetCache.Value = intPtr.ToString("X2"); } IntPtr intPtr2 = unityModule; return (IntPtr)(intPtr2.ToInt64() + intPtr.ToInt64()); } } internal class PeReader { public struct IMAGE_DOS_HEADER { public ushort e_magic; public ushort e_cblp; public ushort e_cp; public ushort e_crlc; public ushort e_cparhdr; public ushort e_minalloc; public ushort e_maxalloc; public ushort e_ss; public ushort e_sp; public ushort e_csum; public ushort e_ip; public ushort e_cs; public ushort e_lfarlc; public ushort e_ovno; public ushort e_res_0; public ushort e_res_1; public ushort e_res_2; public ushort e_res_3; public ushort e_oemid; public ushort e_oeminfo; public ushort e_res2_0; public ushort e_res2_1; public ushort e_res2_2; public ushort e_res2_3; public ushort e_res2_4; public ushort e_res2_5; public ushort e_res2_6; public ushort e_res2_7; public ushort e_res2_8; public ushort e_res2_9; public uint e_lfanew; } public struct IMAGE_DATA_DIRECTORY { public uint VirtualAddress; public uint Size; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct IMAGE_OPTIONAL_HEADER32 { public ushort Magic; public byte MajorLinkerVersion; public byte MinorLinkerVersion; public uint SizeOfCode; public uint SizeOfInitializedData; public uint SizeOfUninitializedData; public uint AddressOfEntryPoint; public uint BaseOfCode; public uint BaseOfData; public uint ImageBase; public uint SectionAlignment; public uint FileAlignment; public ushort MajorOperatingSystemVersion; public ushort MinorOperatingSystemVersion; public ushort MajorImageVersion; public ushort MinorImageVersion; public ushort MajorSubsystemVersion; public ushort MinorSubsystemVersion; public uint Win32VersionValue; public uint SizeOfImage; public uint SizeOfHeaders; public uint CheckSum; public ushort Subsystem; public ushort DllCharacteristics; public uint SizeOfStackReserve; public uint SizeOfStackCommit; public uint SizeOfHeapReserve; public uint SizeOfHeapCommit; public uint LoaderFlags; public uint NumberOfRvaAndSizes; public IMAGE_DATA_DIRECTORY ExportTable; public IMAGE_DATA_DIRECTORY ImportTable; public IMAGE_DATA_DIRECTORY ResourceTable; public IMAGE_DATA_DIRECTORY ExceptionTable; public IMAGE_DATA_DIRECTORY CertificateTable; public IMAGE_DATA_DIRECTORY BaseRelocationTable; public IMAGE_DATA_DIRECTORY Debug; public IMAGE_DATA_DIRECTORY Architecture; public IMAGE_DATA_DIRECTORY GlobalPtr; public IMAGE_DATA_DIRECTORY TLSTable; public IMAGE_DATA_DIRECTORY LoadConfigTable; public IMAGE_DATA_DIRECTORY BoundImport; public IMAGE_DATA_DIRECTORY IAT; public IMAGE_DATA_DIRECTORY DelayImportDescriptor; public IMAGE_DATA_DIRECTORY CLRRuntimeHeader; public IMAGE_DATA_DIRECTORY Reserved; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct IMAGE_OPTIONAL_HEADER64 { public ushort Magic; public byte MajorLinkerVersion; public byte MinorLinkerVersion; public uint SizeOfCode; public uint SizeOfInitializedData; public uint SizeOfUninitializedData; public uint AddressOfEntryPoint; public uint BaseOfCode; public ulong ImageBase; public uint SectionAlignment; public uint FileAlignment; public ushort MajorOperatingSystemVersion; public ushort MinorOperatingSystemVersion; public ushort MajorImageVersion; public ushort MinorImageVersion; public ushort MajorSubsystemVersion; public ushort MinorSubsystemVersion; public uint Win32VersionValue; public uint SizeOfImage; public uint SizeOfHeaders; public uint CheckSum; public ushort Subsystem; public ushort DllCharacteristics; public ulong SizeOfStackReserve; public ulong SizeOfStackCommit; public ulong SizeOfHeapReserve; public ulong SizeOfHeapCommit; public uint LoaderFlags; public uint NumberOfRvaAndSizes; public IMAGE_DATA_DIRECTORY ExportTable; public IMAGE_DATA_DIRECTORY ImportTable; public IMAGE_DATA_DIRECTORY ResourceTable; public IMAGE_DATA_DIRECTORY ExceptionTable; public IMAGE_DATA_DIRECTORY CertificateTable; public IMAGE_DATA_DIRECTORY BaseRelocationTable; public IMAGE_DATA_DIRECTORY Debug; public IMAGE_DATA_DIRECTORY Architecture; public IMAGE_DATA_DIRECTORY GlobalPtr; public IMAGE_DATA_DIRECTORY TLSTable; public IMAGE_DATA_DIRECTORY LoadConfigTable; public IMAGE_DATA_DIRECTORY BoundImport; public IMAGE_DATA_DIRECTORY IAT; public IMAGE_DATA_DIRECTORY DelayImportDescriptor; public IMAGE_DATA_DIRECTORY CLRRuntimeHeader; public IMAGE_DATA_DIRECTORY Reserved; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct IMAGE_FILE_HEADER { public ushort Machine; public ushort NumberOfSections; public uint TimeDateStamp; public uint PointerToSymbolTable; public uint NumberOfSymbols; public ushort SizeOfOptionalHeader; public ushort Characteristics; } [StructLayout(LayoutKind.Explicit)] public struct IMAGE_SECTION_HEADER { [FieldOffset(0)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] public string Name; [FieldOffset(8)] public uint VirtualSize; [FieldOffset(12)] public uint VirtualAddress; [FieldOffset(16)] public uint SizeOfRawData; [FieldOffset(20)] public uint PointerToRawData; [FieldOffset(24)] public uint PointerToRelocations; [FieldOffset(28)] public uint PointerToLinenumbers; [FieldOffset(32)] public ushort NumberOfRelocations; [FieldOffset(34)] public ushort NumberOfLinenumbers; [FieldOffset(36)] public DataSectionFlags Characteristics; } [Flags] public enum DataSectionFlags : uint { TypeReg = 0u, TypeDsect = 1u, TypeNoLoad = 2u, TypeGroup = 4u, TypeNoPadded = 8u, TypeCopy = 0x10u, ContentCode = 0x20u, ContentInitializedData = 0x40u, ContentUninitializedData = 0x80u, LinkOther = 0x100u, LinkInfo = 0x200u, TypeOver = 0x400u, LinkRemove = 0x800u, LinkComDat = 0x1000u, NoDeferSpecExceptions = 0x4000u, RelativeGP = 0x8000u, MemPurgeable = 0x20000u, Memory16Bit = 0x20000u, MemoryLocked = 0x40000u, MemoryPreload = 0x80000u, Align1Bytes = 0x100000u, Align2Bytes = 0x200000u, Align4Bytes = 0x300000u, Align8Bytes = 0x400000u, Align16Bytes = 0x500000u, Align32Bytes = 0x600000u, Align64Bytes = 0x700000u, Align128Bytes = 0x800000u, Align256Bytes = 0x900000u, Align512Bytes = 0xA00000u, Align1024Bytes = 0xB00000u, Align2048Bytes = 0xC00000u, Align4096Bytes = 0xD00000u, Align8192Bytes = 0xE00000u, LinkExtendedRelocationOverflow = 0x1000000u, MemoryDiscardable = 0x2000000u, MemoryNotCached = 0x4000000u, MemoryNotPaged = 0x8000000u, MemoryShared = 0x10000000u, MemoryExecute = 0x20000000u, MemoryRead = 0x40000000u, MemoryWrite = 0x80000000u } public struct IMAGE_DEBUG_DIRECTORY { public enum _Type : uint { IMAGE_DEBUG_TYPE_UNKNOWN, IMAGE_DEBUG_TYPE_COFF, IMAGE_DEBUG_TYPE_CODEVIEW, IMAGE_DEBUG_TYPE_FPO, IMAGE_DEBUG_TYPE_MISC, IMAGE_DEBUG_TYPE_EXCEPTION, IMAGE_DEBUG_TYPE_FIXUP, IMAGE_DEBUG_T
patchers/FixPluginTypesSerialization/Microsoft.Deployment.Compression.Cab.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyDescription("Managed libraries for cabinet archive packing and unpacking")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyFileVersion("3.10.1.2213")] [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyCopyright("Copyright (c) Outercurve Foundation. All rights reserved.")] [assembly: AssemblyProduct("Windows Installer XML Toolset")] [assembly: AssemblyConfiguration("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Assertion = true, UnmanagedCode = true)] [assembly: AssemblyVersion("3.0.0.0")] namespace Microsoft.Tools.WindowsInstallerXml { internal static class WixDistribution { public static string NewsUrl = "http://wixtoolset.org/news/"; public static string ShortProduct = "WiX Toolset"; public static string SupportUrl = "http://wixtoolset.org/"; public static string TelemetryUrlFormat = "http://wixtoolset.org/telemetry/v{0}/?r={1}"; public static string ReplacePlaceholders(string original, Assembly assembly) { if ((object)assembly != null) { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); original = original.Replace("[FileComments]", versionInfo.Comments); original = original.Replace("[FileCopyright]", versionInfo.LegalCopyright); original = original.Replace("[FileProductName]", versionInfo.ProductName); original = original.Replace("[FileVersion]", versionInfo.FileVersion); if (original.Contains("[FileVersionMajorMinor]")) { Version version = new Version(versionInfo.FileVersion); original = original.Replace("[FileVersionMajorMinor]", version.Major + "." + version.Minor); } if (TryGetAttribute<AssemblyCompanyAttribute>(assembly, out var attribute)) { original = original.Replace("[AssemblyCompany]", attribute.Company); } if (TryGetAttribute<AssemblyCopyrightAttribute>(assembly, out var attribute2)) { original = original.Replace("[AssemblyCopyright]", attribute2.Copyright); } if (TryGetAttribute<AssemblyDescriptionAttribute>(assembly, out var attribute3)) { original = original.Replace("[AssemblyDescription]", attribute3.Description); } if (TryGetAttribute<AssemblyProductAttribute>(assembly, out var attribute4)) { original = original.Replace("[AssemblyProduct]", attribute4.Product); } if (TryGetAttribute<AssemblyTitleAttribute>(assembly, out var attribute5)) { original = original.Replace("[AssemblyTitle]", attribute5.Title); } } original = original.Replace("[NewsUrl]", NewsUrl); original = original.Replace("[ShortProduct]", ShortProduct); original = original.Replace("[SupportUrl]", SupportUrl); return original; } private static bool TryGetAttribute<T>(Assembly assembly, out T attribute) where T : Attribute { attribute = null; object[] customAttributes = assembly.GetCustomAttributes(typeof(T), inherit: false); if (customAttributes != null && customAttributes.Length != 0) { attribute = customAttributes[0] as T; } return attribute != null; } } } namespace Microsoft.Deployment.Compression.Cab { internal class CabPacker : CabWorker { private const string TempStreamName = "%%TEMP%%"; private NativeMethods.FCI.Handle fciHandle; private NativeMethods.FCI.PFNALLOC fciAllocMemHandler; private NativeMethods.FCI.PFNFREE fciFreeMemHandler; private NativeMethods.FCI.PFNOPEN fciOpenStreamHandler; private NativeMethods.FCI.PFNREAD fciReadStreamHandler; private NativeMethods.FCI.PFNWRITE fciWriteStreamHandler; private NativeMethods.FCI.PFNCLOSE fciCloseStreamHandler; private NativeMethods.FCI.PFNSEEK fciSeekStreamHandler; private NativeMethods.FCI.PFNFILEPLACED fciFilePlacedHandler; private NativeMethods.FCI.PFNDELETE fciDeleteFileHandler; private NativeMethods.FCI.PFNGETTEMPFILE fciGetTempFileHandler; private NativeMethods.FCI.PFNGETNEXTCABINET fciGetNextCabinet; private NativeMethods.FCI.PFNSTATUS fciCreateStatus; private NativeMethods.FCI.PFNGETOPENINFO fciGetOpenInfo; private IPackStreamContext context; private FileAttributes fileAttributes; private DateTime fileLastWriteTime; private int maxCabBytes; private long totalFolderBytesProcessedInCurrentCab; private CompressionLevel compressionLevel; private bool dontUseTempFiles; private IList<Stream> tempStreams; public bool UseTempFiles { get { return !dontUseTempFiles; } set { dontUseTempFiles = !value; } } public CompressionLevel CompressionLevel { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return compressionLevel; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) compressionLevel = value; } } public CabPacker(CabEngine cabEngine) : base(cabEngine) { //IL_0103: Unknown result type (might be due to invalid IL or missing references) fciAllocMemHandler = base.CabAllocMem; fciFreeMemHandler = base.CabFreeMem; fciOpenStreamHandler = CabOpenStreamEx; fciReadStreamHandler = CabReadStreamEx; fciWriteStreamHandler = CabWriteStreamEx; fciCloseStreamHandler = CabCloseStreamEx; fciSeekStreamHandler = CabSeekStreamEx; fciFilePlacedHandler = CabFilePlaced; fciDeleteFileHandler = CabDeleteFile; fciGetTempFileHandler = CabGetTempFile; fciGetNextCabinet = CabGetNextCabinet; fciCreateStatus = CabCreateStatus; fciGetOpenInfo = CabGetOpenInfo; tempStreams = new List<Stream>(); compressionLevel = (CompressionLevel)6; } private void CreateFci(long maxArchiveSize) { NativeMethods.FCI.CCAB cCAB = new NativeMethods.FCI.CCAB(); checked { if (maxArchiveSize > 0 && maxArchiveSize < cCAB.cb) { cCAB.cb = Math.Max(32768, (int)maxArchiveSize); } object option = context.GetOption("maxFolderSize", (object[])null); if (option != null) { long num = Convert.ToInt64(option, CultureInfo.InvariantCulture); if (num > 0 && num < cCAB.cbFolderThresh) { cCAB.cbFolderThresh = (int)num; } } maxCabBytes = cCAB.cb; cCAB.szCab = context.GetArchiveName(0); if (cCAB.szCab == null) { throw new FileNotFoundException("Cabinet name not provided by stream context."); } cCAB.setID = (short)new Random().Next(-32768, 32768); base.CabNumbers[cCAB.szCab] = 0; currentArchiveName = cCAB.szCab; totalArchives = 1; base.CabStream = null; base.Erf.Clear(); fciHandle = NativeMethods.FCI.Create(base.ErfHandle.AddrOfPinnedObject(), fciFilePlacedHandler, fciAllocMemHandler, fciFreeMemHandler, fciOpenStreamHandler, fciReadStreamHandler, fciWriteStreamHandler, fciCloseStreamHandler, fciSeekStreamHandler, fciDeleteFileHandler, fciGetTempFileHandler, cCAB, IntPtr.Zero); CheckError(extracting: false); } } [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] public void Pack(IPackStreamContext streamContext, IEnumerable<string> files, long maxArchiveSize) { //IL_01d0: Unknown result type (might be due to invalid IL or missing references) if (streamContext == null) { throw new ArgumentNullException("streamContext"); } if (files == null) { throw new ArgumentNullException("files"); } lock (this) { try { context = streamContext; ResetProgressData(); CreateFci(maxArchiveSize); checked { FileAttributes fileAttributes = default(FileAttributes); DateTime dateTime = default(DateTime); foreach (string file in files) { Stream stream = context.OpenFileReadStream(file, ref fileAttributes, ref dateTime); if (stream != null) { totalFileBytes += stream.Length; totalFiles++; context.CloseFileReadStream(file, stream); } } long num = 0L; currentFileNumber = -1; FileAttributes attributes = default(FileAttributes); DateTime lastWriteTime = default(DateTime); foreach (string file2 in files) { Stream stream2 = context.OpenFileReadStream(file2, ref attributes, ref lastWriteTime); if (stream2 == null) { continue; } if (stream2.Length >= 2147450880) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "File {0} exceeds maximum file size for cabinet format.", new object[1] { file2 })); } if (num > 0) { bool flag = num + stream2.Length >= 2147450880; if (!flag) { flag = Convert.ToBoolean(streamContext.GetOption("nextFolder", new object[2] { file2, currentFolderNumber }), CultureInfo.InvariantCulture); } if (flag) { FlushFolder(); num = 0L; } } if (currentFolderTotalBytes > 0) { currentFolderTotalBytes = 0L; currentFolderNumber++; num = 0L; } currentFileName = file2; currentFileNumber++; currentFileTotalBytes = stream2.Length; currentFileBytesProcessed = 0L; OnProgress((ArchiveProgressType)0); num += stream2.Length; AddFile(file2, stream2, attributes, lastWriteTime, execute: false, CompressionLevel); } FlushFolder(); FlushCabinet(); } } finally { if (base.CabStream != null) { context.CloseArchiveWriteStream((int)currentArchiveNumber, currentArchiveName, base.CabStream); base.CabStream = null; } if (base.FileStream != null) { context.CloseFileReadStream(currentFileName, base.FileStream); base.FileStream = null; } context = null; if (fciHandle != null) { fciHandle.Dispose(); fciHandle = null; } } } } internal override int CabOpenStreamEx(string path, int openFlags, int shareMode, out int err, IntPtr pv) { //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown if (base.CabNumbers.ContainsKey(path)) { Stream stream = base.CabStream; if (stream == null) { short num = base.CabNumbers[path]; currentFolderTotalBytes = 0L; stream = context.OpenArchiveWriteStream((int)num, path, true, (CompressionEngine)(object)base.CabEngine); if (stream == null) { throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Cabinet {0} not provided.", new object[1] { num })); } currentArchiveName = path; currentArchiveTotalBytes = Math.Min(totalFolderBytesProcessedInCurrentCab, maxCabBytes); currentArchiveBytesProcessed = 0L; OnProgress((ArchiveProgressType)3); base.CabStream = stream; } path = "%%CAB%%"; } else { if (path == "%%TEMP%%") { Stream stream2 = new MemoryStream(); tempStreams.Add(stream2); int result = base.StreamHandles.AllocHandle(stream2); err = 0; return result; } if (path != "%%CAB%%") { path = Path.Combine(Path.GetTempPath(), path); Stream stream3 = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); tempStreams.Add(stream3); stream3 = (Stream)new DuplicateStream(stream3); int result2 = base.StreamHandles.AllocHandle(stream3); err = 0; return result2; } } return base.CabOpenStreamEx(path, openFlags, shareMode, out err, pv); } internal override int CabWriteStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv) { int num = base.CabWriteStreamEx(streamHandle, memory, cb, out err, pv); checked { if (num > 0 && err == 0 && DuplicateStream.OriginalStream(base.StreamHandles[streamHandle]) == DuplicateStream.OriginalStream(base.CabStream)) { currentArchiveBytesProcessed += cb; if (currentArchiveBytesProcessed > currentArchiveTotalBytes) { currentArchiveBytesProcessed = currentArchiveTotalBytes; } } return num; } } internal override int CabCloseStreamEx(int streamHandle, out int err, IntPtr pv) { Stream stream = DuplicateStream.OriginalStream(base.StreamHandles[streamHandle]); checked { if (stream == DuplicateStream.OriginalStream(base.FileStream)) { context.CloseFileReadStream(currentFileName, stream); base.FileStream = null; long num = currentFileTotalBytes - currentFileBytesProcessed; currentFileBytesProcessed += num; fileBytesProcessed += num; OnProgress((ArchiveProgressType)2); currentFileTotalBytes = 0L; currentFileBytesProcessed = 0L; currentFileName = null; } else if (stream == DuplicateStream.OriginalStream(base.CabStream)) { if (stream.CanWrite) { stream.Flush(); } currentArchiveBytesProcessed = currentArchiveTotalBytes; OnProgress((ArchiveProgressType)5); currentArchiveNumber++; totalArchives++; context.CloseArchiveWriteStream(unchecked((int)currentArchiveNumber), currentArchiveName, stream); currentArchiveName = base.NextCabinetName; currentArchiveBytesProcessed = (currentArchiveTotalBytes = 0L); totalFolderBytesProcessedInCurrentCab = 0L; base.CabStream = null; } else { stream.Close(); tempStreams.Remove(stream); } return base.CabCloseStreamEx(streamHandle, out err, pv); } } protected override void Dispose(bool disposing) { try { if (disposing && fciHandle != null) { fciHandle.Dispose(); fciHandle = null; } } finally { base.Dispose(disposing); } } private static NativeMethods.FCI.TCOMP GetCompressionType(CompressionLevel compLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected I4, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) if ((int)compLevel < 1) { return NativeMethods.FCI.TCOMP.TYPE_NONE; } if ((int)compLevel > 10) { compLevel = (CompressionLevel)10; } int num = checked(6 * (compLevel - 1)) / 9; return (NativeMethods.FCI.TCOMP)checked((ushort)(3 | (3840 + (num << 8)))); } private void AddFile(string name, Stream stream, FileAttributes attributes, DateTime lastWriteTime, bool execute, CompressionLevel compLevel) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) base.FileStream = stream; fileAttributes = attributes & (FileAttributes.ReadOnly | FileAttributes.Hidden | FileAttributes.System | FileAttributes.Archive); fileLastWriteTime = lastWriteTime; currentFileName = name; NativeMethods.FCI.TCOMP compressionType = GetCompressionType(compLevel); IntPtr intPtr = IntPtr.Zero; try { Encoding encoding = Encoding.ASCII; if (Encoding.UTF8.GetByteCount(name) > name.Length) { encoding = Encoding.UTF8; fileAttributes |= FileAttributes.Normal; } byte[] bytes = encoding.GetBytes(name); intPtr = Marshal.AllocHGlobal(checked(bytes.Length + 1)); Marshal.Copy(bytes, 0, intPtr, bytes.Length); Marshal.WriteByte(intPtr, bytes.Length, 0); base.Erf.Clear(); NativeMethods.FCI.AddFile(fciHandle, string.Empty, intPtr, execute, fciGetNextCabinet, fciCreateStatus, fciGetOpenInfo, compressionType); } finally { if (intPtr != IntPtr.Zero) { Marshal.FreeHGlobal(intPtr); } } CheckError(extracting: false); base.FileStream = null; currentFileName = null; } private void FlushFolder() { base.Erf.Clear(); NativeMethods.FCI.FlushFolder(fciHandle, fciGetNextCabinet, fciCreateStatus); CheckError(extracting: false); } private void FlushCabinet() { base.Erf.Clear(); NativeMethods.FCI.FlushCabinet(fciHandle, fGetNextCab: false, fciGetNextCabinet, fciCreateStatus); CheckError(extracting: false); } private int CabGetOpenInfo(string path, out short date, out short time, out short attribs, out int err, IntPtr pv) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown CompressionEngine.DateTimeToDosDateAndTime(fileLastWriteTime, ref date, ref time); attribs = checked((short)fileAttributes); Stream stream = base.FileStream; base.FileStream = (Stream)new DuplicateStream(stream); int result = base.StreamHandles.AllocHandle(stream); err = 0; return result; } private int CabFilePlaced(IntPtr pccab, string filePath, long fileSize, int continuation, IntPtr pv) { return 0; } private int CabGetNextCabinet(IntPtr pccab, uint prevCabSize, IntPtr pv) { NativeMethods.FCI.CCAB cCAB = new NativeMethods.FCI.CCAB(); Marshal.PtrToStructure(pccab, (object)cCAB); cCAB.szDisk = string.Empty; cCAB.szCab = context.GetArchiveName(cCAB.iCab); base.CabNumbers[cCAB.szCab] = checked((short)cCAB.iCab); base.NextCabinetName = cCAB.szCab; Marshal.StructureToPtr((object)cCAB, pccab, fDeleteOld: false); return 1; } private int CabCreateStatus(NativeMethods.FCI.STATUS typeStatus, uint cb1, uint cb2, IntPtr pv) { checked { switch (typeStatus) { case NativeMethods.FCI.STATUS.FILE: if (cb2 != 0 && currentFileBytesProcessed < currentFileTotalBytes) { if (currentFileBytesProcessed + cb2 > currentFileTotalBytes) { cb2 = (uint)currentFileTotalBytes - (uint)currentFileBytesProcessed; } currentFileBytesProcessed += cb2; fileBytesProcessed += cb2; OnProgress((ArchiveProgressType)1); } break; case NativeMethods.FCI.STATUS.FOLDER: if (cb1 == 0) { currentFolderTotalBytes = cb2 - totalFolderBytesProcessedInCurrentCab; totalFolderBytesProcessedInCurrentCab = cb2; } else if (currentFolderTotalBytes == 0L) { OnProgress((ArchiveProgressType)4); } break; } return 0; } } private int CabGetTempFile(IntPtr tempNamePtr, int tempNameSize, IntPtr pv) { string s = ((!UseTempFiles) ? "%%TEMP%%" : Path.GetFileName(Path.GetTempFileName())); byte[] bytes = Encoding.ASCII.GetBytes(s); if (bytes.Length >= tempNameSize) { return -1; } Marshal.Copy(bytes, 0, tempNamePtr, bytes.Length); Marshal.WriteByte(tempNamePtr, bytes.Length, 0); return 1; } private int CabDeleteFile(string path, out int err, IntPtr pv) { try { if (path != "%%TEMP%%") { path = Path.Combine(Path.GetTempPath(), path); File.Delete(path); } } catch (IOException) { } err = 0; return 1; } } public class CabEngine : CompressionEngine { private CabPacker packer; private CabUnpacker unpacker; private CabPacker Packer { get { if (packer == null) { packer = new CabPacker(this); } return packer; } } private CabUnpacker Unpacker { get { if (unpacker == null) { unpacker = new CabUnpacker(this); } return unpacker; } } protected override void Dispose(bool disposing) { if (disposing) { if (packer != null) { packer.Dispose(); packer = null; } if (unpacker != null) { unpacker.Dispose(); unpacker = null; } } ((CompressionEngine)this).Dispose(disposing); } public override void Pack(IPackStreamContext streamContext, IEnumerable<string> files, long maxArchiveSize) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Packer.CompressionLevel = ((CompressionEngine)this).CompressionLevel; Packer.UseTempFiles = ((CompressionEngine)this).UseTempFiles; Packer.Pack(streamContext, files, maxArchiveSize); } public override bool IsArchive(Stream stream) { return Unpacker.IsArchive(stream); } public override IList<ArchiveFileInfo> GetFileInfo(IUnpackStreamContext streamContext, Predicate<string> fileFilter) { return Unpacker.GetFileInfo(streamContext, fileFilter); } public override void Unpack(IUnpackStreamContext streamContext, Predicate<string> fileFilter) { Unpacker.Unpack(streamContext, fileFilter); } internal void ReportProgress(ArchiveProgressEventArgs e) { ((CompressionEngine)this).OnProgress(e); } } internal abstract class CabWorker : IDisposable { internal const string CabStreamName = "%%CAB%%"; private CabEngine cabEngine; private HandleManager<Stream> streamHandles; private Stream cabStream; private Stream fileStream; private NativeMethods.ERF erf; private GCHandle erfHandle; private IDictionary<string, short> cabNumbers; private string nextCabinetName; private bool suppressProgressEvents; private byte[] buf; protected string currentFileName; protected int currentFileNumber; protected int totalFiles; protected long currentFileBytesProcessed; protected long currentFileTotalBytes; protected short currentFolderNumber; protected long currentFolderTotalBytes; protected string currentArchiveName; protected short currentArchiveNumber; protected short totalArchives; protected long currentArchiveBytesProcessed; protected long currentArchiveTotalBytes; protected long fileBytesProcessed; protected long totalFileBytes; public CabEngine CabEngine => cabEngine; internal NativeMethods.ERF Erf => erf; internal GCHandle ErfHandle => erfHandle; internal HandleManager<Stream> StreamHandles => streamHandles; internal bool SuppressProgressEvents { get { return suppressProgressEvents; } set { suppressProgressEvents = value; } } internal IDictionary<string, short> CabNumbers => cabNumbers; internal string NextCabinetName { get { return nextCabinetName; } set { nextCabinetName = value; } } internal Stream CabStream { get { return cabStream; } set { cabStream = value; } } internal Stream FileStream { get { return fileStream; } set { fileStream = value; } } protected CabWorker(CabEngine cabEngine) { this.cabEngine = cabEngine; streamHandles = new HandleManager<Stream>(); erf = new NativeMethods.ERF(); erfHandle = GCHandle.Alloc(erf, GCHandleType.Pinned); cabNumbers = new Dictionary<string, short>(1); buf = new byte[32768]; } ~CabWorker() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected void ResetProgressData() { currentFileName = null; currentFileNumber = 0; totalFiles = 0; currentFileBytesProcessed = 0L; currentFileTotalBytes = 0L; currentFolderNumber = 0; currentFolderTotalBytes = 0L; currentArchiveName = null; currentArchiveNumber = 0; totalArchives = 0; currentArchiveBytesProcessed = 0L; currentArchiveTotalBytes = 0L; fileBytesProcessed = 0L; totalFileBytes = 0L; } protected void OnProgress(ArchiveProgressType progressType) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown if (!suppressProgressEvents) { ArchiveProgressEventArgs e = new ArchiveProgressEventArgs(progressType, currentFileName, (currentFileNumber >= 0) ? currentFileNumber : 0, totalFiles, currentFileBytesProcessed, currentFileTotalBytes, currentArchiveName, (int)currentArchiveNumber, (int)totalArchives, currentArchiveBytesProcessed, currentArchiveTotalBytes, fileBytesProcessed, totalFileBytes); CabEngine.ReportProgress(e); } } internal IntPtr CabAllocMem(int byteCount) { return Marshal.AllocHGlobal((IntPtr)byteCount); } internal void CabFreeMem(IntPtr memPointer) { Marshal.FreeHGlobal(memPointer); } internal int CabOpenStream(string path, int openFlags, int shareMode) { int err; return CabOpenStreamEx(path, openFlags, shareMode, out err, IntPtr.Zero); } internal virtual int CabOpenStreamEx(string path, int openFlags, int shareMode, out int err, IntPtr pv) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown path = path.Trim(); Stream stream = cabStream; cabStream = (Stream)new DuplicateStream(stream); int result = streamHandles.AllocHandle(stream); err = 0; return result; } internal int CabReadStream(int streamHandle, IntPtr memory, int cb) { int err; return CabReadStreamEx(streamHandle, memory, cb, out err, IntPtr.Zero); } internal virtual int CabReadStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv) { Stream stream = streamHandles[streamHandle]; int num = cb; if (num > buf.Length) { buf = new byte[num]; } num = stream.Read(buf, 0, num); Marshal.Copy(buf, 0, memory, num); err = 0; return num; } internal int CabWriteStream(int streamHandle, IntPtr memory, int cb) { int err; return CabWriteStreamEx(streamHandle, memory, cb, out err, IntPtr.Zero); } internal virtual int CabWriteStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv) { Stream stream = streamHandles[streamHandle]; if (cb > buf.Length) { buf = new byte[cb]; } Marshal.Copy(memory, buf, 0, cb); stream.Write(buf, 0, cb); err = 0; return cb; } internal int CabCloseStream(int streamHandle) { int err; return CabCloseStreamEx(streamHandle, out err, IntPtr.Zero); } internal virtual int CabCloseStreamEx(int streamHandle, out int err, IntPtr pv) { streamHandles.FreeHandle(streamHandle); err = 0; return 0; } internal int CabSeekStream(int streamHandle, int offset, int seekOrigin) { int err; return CabSeekStreamEx(streamHandle, offset, seekOrigin, out err, IntPtr.Zero); } internal virtual int CabSeekStreamEx(int streamHandle, int offset, int seekOrigin, out int err, IntPtr pv) { checked { offset = (int)streamHandles[streamHandle].Seek(offset, unchecked((SeekOrigin)seekOrigin)); err = 0; return offset; } } protected virtual void Dispose(bool disposing) { if (disposing) { if (cabStream != null) { cabStream.Close(); cabStream = null; } if (fileStream != null) { fileStream.Close(); fileStream = null; } } if (erfHandle.IsAllocated) { erfHandle.Free(); } } protected void CheckError(bool extracting) { if (Erf.Error) { throw new CabException(Erf.Oper, Erf.Type, CabException.GetErrorMessage(Erf.Oper, Erf.Type, extracting)); } } } [Serializable] public class CabException : ArchiveException { private static ResourceManager errorResources; private int error; private int errorCode; public int Error => error; public int ErrorCode => errorCode; internal static ResourceManager ErrorResources { get { if (errorResources == null) { errorResources = new ResourceManager(typeof(CabException).Namespace + ".Errors", typeof(CabException).Assembly); } return errorResources; } } public CabException(string message, Exception innerException) : this(0, 0, message, innerException) { } public CabException(string message) : this(0, 0, message, null) { } public CabException() : this(0, 0, null, null) { } internal CabException(int error, int errorCode, string message, Exception innerException) : base(message, innerException) { this.error = error; this.errorCode = errorCode; } internal CabException(int error, int errorCode, string message) : this(error, errorCode, message, null) { } protected CabException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new ArgumentNullException("info"); } error = info.GetInt32("cabError"); errorCode = info.GetInt32("cabErrorCode"); } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("cabError", error); info.AddValue("cabErrorCode", errorCode); ((Exception)this).GetObjectData(info, context); } internal static string GetErrorMessage(int error, int errorCode, bool extracting) { int num = (extracting ? 2000 : 1000); string text = ErrorResources.GetString(checked(num + error).ToString(CultureInfo.InvariantCulture.NumberFormat), CultureInfo.CurrentCulture); if (text == null) { text = ErrorResources.GetString(num.ToString(CultureInfo.InvariantCulture.NumberFormat), CultureInfo.CurrentCulture); } if (errorCode != 0) { string @string = ErrorResources.GetString("1", CultureInfo.CurrentCulture); text = string.Format(CultureInfo.InvariantCulture, "{0} " + @string, new object[2] { text, errorCode }); } return text; } } internal class CabUnpacker : CabWorker { private NativeMethods.FDI.Handle fdiHandle; private NativeMethods.FDI.PFNALLOC fdiAllocMemHandler; private NativeMethods.FDI.PFNFREE fdiFreeMemHandler; private NativeMethods.FDI.PFNOPEN fdiOpenStreamHandler; private NativeMethods.FDI.PFNREAD fdiReadStreamHandler; private NativeMethods.FDI.PFNWRITE fdiWriteStreamHandler; private NativeMethods.FDI.PFNCLOSE fdiCloseStreamHandler; private NativeMethods.FDI.PFNSEEK fdiSeekStreamHandler; private IUnpackStreamContext context; private List<ArchiveFileInfo> fileList; private int folderId; private Predicate<string> filter; [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] public CabUnpacker(CabEngine cabEngine) : base(cabEngine) { fdiAllocMemHandler = base.CabAllocMem; fdiFreeMemHandler = base.CabFreeMem; fdiOpenStreamHandler = base.CabOpenStream; fdiReadStreamHandler = base.CabReadStream; fdiWriteStreamHandler = base.CabWriteStream; fdiCloseStreamHandler = base.CabCloseStream; fdiSeekStreamHandler = base.CabSeekStream; fdiHandle = NativeMethods.FDI.Create(fdiAllocMemHandler, fdiFreeMemHandler, fdiOpenStreamHandler, fdiReadStreamHandler, fdiWriteStreamHandler, fdiCloseStreamHandler, fdiSeekStreamHandler, 1, base.ErfHandle.AddrOfPinnedObject()); if (base.Erf.Error) { int oper = base.Erf.Oper; int type = base.Erf.Type; base.ErfHandle.Free(); throw new CabException(oper, type, CabException.GetErrorMessage(oper, type, extracting: true)); } } [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] public bool IsArchive(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } lock (this) { short id; int cabFolderCount; int fileCount; return IsCabinet(stream, out id, out cabFolderCount, out fileCount); } } [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] public IList<ArchiveFileInfo> GetFileInfo(IUnpackStreamContext streamContext, Predicate<string> fileFilter) { if (streamContext == null) { throw new ArgumentNullException("streamContext"); } lock (this) { context = streamContext; filter = fileFilter; base.NextCabinetName = string.Empty; fileList = new List<ArchiveFileInfo>(); bool flag = base.SuppressProgressEvents; base.SuppressProgressEvents = true; try { short num = 0; while (base.NextCabinetName != null) { base.Erf.Clear(); base.CabNumbers[base.NextCabinetName] = num; NativeMethods.FDI.Copy(fdiHandle, base.NextCabinetName, string.Empty, 0, CabListNotify, IntPtr.Zero, IntPtr.Zero); CheckError(extracting: true); num = checked((short)(num + 1)); } List<ArchiveFileInfo> list = fileList; fileList = null; return list.AsReadOnly(); } finally { base.SuppressProgressEvents = flag; if (base.CabStream != null) { context.CloseArchiveReadStream((int)currentArchiveNumber, currentArchiveName, base.CabStream); base.CabStream = null; } context = null; } } } [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] public void Unpack(IUnpackStreamContext streamContext, Predicate<string> fileFilter) { checked { lock (this) { IList<ArchiveFileInfo> fileInfo = GetFileInfo(streamContext, fileFilter); ResetProgressData(); if (fileInfo != null) { totalFiles = fileInfo.Count; for (int i = 0; i < fileInfo.Count; i++) { totalFileBytes += fileInfo[i].Length; if (fileInfo[i].ArchiveNumber >= totalArchives) { int num = fileInfo[i].ArchiveNumber + 1; totalArchives = (short)num; } } } context = streamContext; fileList = null; base.NextCabinetName = string.Empty; folderId = -1; currentFileNumber = -1; try { short num2 = 0; while (base.NextCabinetName != null) { base.Erf.Clear(); base.CabNumbers[base.NextCabinetName] = num2; NativeMethods.FDI.Copy(fdiHandle, base.NextCabinetName, string.Empty, 0, CabExtractNotify, IntPtr.Zero, IntPtr.Zero); CheckError(extracting: true); num2++; } } finally { if (base.CabStream != null) { context.CloseArchiveReadStream(unchecked((int)currentArchiveNumber), currentArchiveName, base.CabStream); base.CabStream = null; } if (base.FileStream != null) { context.CloseFileWriteStream(currentFileName, base.FileStream, FileAttributes.Normal, DateTime.Now); base.FileStream = null; } context = null; } } } } internal override int CabOpenStreamEx(string path, int openFlags, int shareMode, out int err, IntPtr pv) { if (base.CabNumbers.ContainsKey(path)) { Stream stream = base.CabStream; if (stream == null) { short num = base.CabNumbers[path]; stream = context.OpenArchiveReadStream((int)num, path, (CompressionEngine)(object)base.CabEngine); if (stream == null) { throw new FileNotFoundException(string.Format(CultureInfo.InvariantCulture, "Cabinet {0} not provided.", new object[1] { num })); } currentArchiveName = path; currentArchiveNumber = num; checked { if (totalArchives <= currentArchiveNumber) { int num2 = currentArchiveNumber + 1; totalArchives = (short)num2; } currentArchiveTotalBytes = stream.Length; currentArchiveBytesProcessed = 0L; if (folderId != -3) { OnProgress((ArchiveProgressType)3); } base.CabStream = stream; } } path = "%%CAB%%"; } return base.CabOpenStreamEx(path, openFlags, shareMode, out err, pv); } internal override int CabReadStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv) { int result = base.CabReadStreamEx(streamHandle, memory, cb, out err, pv); checked { if (err == 0 && base.CabStream != null && fileList == null && DuplicateStream.OriginalStream(base.StreamHandles[streamHandle]) == DuplicateStream.OriginalStream(base.CabStream)) { currentArchiveBytesProcessed += cb; if (currentArchiveBytesProcessed > currentArchiveTotalBytes) { currentArchiveBytesProcessed = currentArchiveTotalBytes; } } return result; } } internal override int CabWriteStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv) { int num = base.CabWriteStreamEx(streamHandle, memory, cb, out err, pv); checked { if (num > 0 && err == 0) { currentFileBytesProcessed += cb; fileBytesProcessed += cb; OnProgress((ArchiveProgressType)1); } return num; } } internal override int CabCloseStreamEx(int streamHandle, out int err, IntPtr pv) { Stream stream = DuplicateStream.OriginalStream(base.StreamHandles[streamHandle]); if (stream == DuplicateStream.OriginalStream(base.CabStream)) { if (folderId != -3) { OnProgress((ArchiveProgressType)5); } context.CloseArchiveReadStream((int)currentArchiveNumber, currentArchiveName, stream); currentArchiveName = base.NextCabinetName; currentArchiveBytesProcessed = (currentArchiveTotalBytes = 0L); base.CabStream = null; } return base.CabCloseStreamEx(streamHandle, out err, pv); } protected override void Dispose(bool disposing) { try { if (disposing && fdiHandle != null) { fdiHandle.Dispose(); fdiHandle = null; } } finally { base.Dispose(disposing); } } private static string GetFileName(NativeMethods.FDI.NOTIFICATION notification) { Encoding encoding = ((((uint)notification.attribs & 0x80u) != 0) ? Encoding.UTF8 : Encoding.Default); int i; for (i = 0; Marshal.ReadByte(notification.psz1, i) != 0; i = checked(i + 1)) { } byte[] array = new byte[i]; Marshal.Copy(notification.psz1, array, 0, i); string text = encoding.GetString(array); if (Path.IsPathRooted(text)) { text = text.Replace(Path.VolumeSeparatorChar.ToString() ?? "", ""); } return text; } private bool IsCabinet(Stream cabStream, out short id, out int cabFolderCount, out int fileCount) { int num = base.StreamHandles.AllocHandle(cabStream); try { base.Erf.Clear(); NativeMethods.FDI.CABINFO pfdici; bool result = NativeMethods.FDI.IsCabinet(fdiHandle, num, out pfdici) != 0; if (base.Erf.Error) { if (base.Erf.Oper != 3) { throw new CabException(base.Erf.Oper, base.Erf.Type, CabException.GetErrorMessage(base.Erf.Oper, base.Erf.Type, extracting: true)); } result = false; } id = pfdici.setID; cabFolderCount = pfdici.cFolders; fileCount = pfdici.cFiles; return result; } finally { base.StreamHandles.FreeHandle(num); } } private int CabListNotify(NativeMethods.FDI.NOTIFICATIONTYPE notificationType, NativeMethods.FDI.NOTIFICATION notification) { checked { switch (notificationType) { case NativeMethods.FDI.NOTIFICATIONTYPE.CABINET_INFO: { string text = Marshal.PtrToStringAnsi(notification.psz1); base.NextCabinetName = ((text.Length != 0) ? text : null); return 0; } case NativeMethods.FDI.NOTIFICATIONTYPE.PARTIAL_FILE: return 0; case NativeMethods.FDI.NOTIFICATIONTYPE.COPY_FILE: { string fileName = GetFileName(notification); if ((filter == null || filter(fileName)) && fileList != null) { FileAttributes fileAttributes = unchecked((FileAttributes)(notification.attribs & 0x27)); if (fileAttributes == (FileAttributes)0) { fileAttributes = FileAttributes.Normal; } DateTime lastWriteTime = default(DateTime); CompressionEngine.DosDateAndTimeToDateTime(notification.date, notification.time, ref lastWriteTime); long length = notification.cb; CabFileInfo item = new CabFileInfo(fileName, notification.iFolder, notification.iCabinet, fileAttributes, lastWriteTime, length); fileList.Add((ArchiveFileInfo)(object)item); currentFileNumber = fileList.Count - 1; fileBytesProcessed += notification.cb; } totalFiles++; totalFileBytes += notification.cb; return 0; } default: return 0; } } } private int CabExtractNotify(NativeMethods.FDI.NOTIFICATIONTYPE notificationType, NativeMethods.FDI.NOTIFICATION notification) { switch (notificationType) { case NativeMethods.FDI.NOTIFICATIONTYPE.CABINET_INFO: if (base.NextCabinetName != null && base.NextCabinetName.StartsWith("?", StringComparison.Ordinal)) { base.NextCabinetName = base.NextCabinetName.Substring(1); } else { string text = Marshal.PtrToStringAnsi(notification.psz1); base.NextCabinetName = ((text.Length != 0) ? text : null); } return 0; case NativeMethods.FDI.NOTIFICATIONTYPE.NEXT_CABINET: { string key = Marshal.PtrToStringAnsi(notification.psz1); base.CabNumbers[key] = notification.iCabinet; base.NextCabinetName = "?" + base.NextCabinetName; return 0; } case NativeMethods.FDI.NOTIFICATIONTYPE.COPY_FILE: return CabExtractCopyFile(notification); case NativeMethods.FDI.NOTIFICATIONTYPE.CLOSE_FILE_INFO: return CabExtractCloseFile(notification); default: return 0; } } private int CabExtractCopyFile(NativeMethods.FDI.NOTIFICATION notification) { checked { if (notification.iFolder != folderId) { if (notification.iFolder != -3 && folderId != -1) { currentFolderNumber++; } folderId = notification.iFolder; } string fileName = GetFileName(notification); if (filter == null || filter(fileName)) { currentFileNumber++; currentFileName = fileName; currentFileBytesProcessed = 0L; currentFileTotalBytes = notification.cb; OnProgress((ArchiveProgressType)0); DateTime dateTime = default(DateTime); CompressionEngine.DosDateAndTimeToDateTime(notification.date, notification.time, ref dateTime); Stream stream = context.OpenFileWriteStream(fileName, unchecked((long)notification.cb), dateTime); if (stream != null) { base.FileStream = stream; return base.StreamHandles.AllocHandle(stream); } fileBytesProcessed += notification.cb; OnProgress((ArchiveProgressType)2); currentFileName = null; } return 0; } } private int CabExtractCloseFile(NativeMethods.FDI.NOTIFICATION notification) { Stream stream = base.StreamHandles[notification.hf]; base.StreamHandles.FreeHandle(notification.hf); string fileName = GetFileName(notification); FileAttributes fileAttributes = (FileAttributes)(notification.attribs & 0x27); if (fileAttributes == (FileAttributes)0) { fileAttributes = FileAttributes.Normal; } DateTime dateTime = default(DateTime); CompressionEngine.DosDateAndTimeToDateTime(notification.date, notification.time, ref dateTime); stream.Flush(); context.CloseFileWriteStream(fileName, stream, fileAttributes, dateTime); base.FileStream = null; checked { long num = currentFileTotalBytes - currentFileBytesProcessed; currentFileBytesProcessed += num; fileBytesProcessed += num; OnProgress((ArchiveProgressType)2); currentFileName = null; return 1; } } } [Serializable] public class CabFileInfo : ArchiveFileInfo { private int cabFolder; public CabInfo Cabinet => (CabInfo)(object)((ArchiveFileInfo)this).Archive; public string CabinetName => ((ArchiveFileInfo)this).ArchiveName; public int CabinetFolderNumber { get { if (cabFolder < 0) { ((ArchiveFileInfo)this).Refresh(); } return cabFolder; } } public CabFileInfo(CabInfo cabinetInfo, string filePath) : base((ArchiveInfo)(object)cabinetInfo, filePath) { if (cabinetInfo == null) { throw new ArgumentNullException("cabinetInfo"); } cabFolder = -1; } internal CabFileInfo(string filePath, int cabFolder, int cabNumber, FileAttributes attributes, DateTime lastWriteTime, long length) : base(filePath, cabNumber, attributes, lastWriteTime, length) { this.cabFolder = cabFolder; } protected CabFileInfo(SerializationInfo info, StreamingContext context) : base(info, context) { cabFolder = info.GetInt32("cabFolder"); } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { ((ArchiveFileInfo)this).GetObjectData(info, context); info.AddValue("cabFolder", cabFolder); } protected override void Refresh(ArchiveFileInfo newFileInfo) { ((ArchiveFileInfo)this).Refresh(newFileInfo); cabFolder = ((CabFileInfo)(object)newFileInfo).cabFolder; } } [Serializable] public class CabInfo : ArchiveInfo { public CabInfo(string path) : base(path) { } protected CabInfo(SerializationInfo info, StreamingContext context) : base(info, context) { } protected override CompressionEngine CreateCompressionEngine() { return (CompressionEngine)(object)new CabEngine(); } public IList<CabFileInfo> GetFiles() { IList<ArchiveFileInfo> files = ((ArchiveInfo)this).GetFiles(); List<CabFileInfo> list = new List<CabFileInfo>(files.Count); foreach (CabFileInfo item in files) { list.Add(item); } return list.AsReadOnly(); } public IList<CabFileInfo> GetFiles(string searchPattern) { IList<ArchiveFileInfo> files = ((ArchiveInfo)this).GetFiles(searchPattern); List<CabFileInfo> list = new List<CabFileInfo>(files.Count); foreach (CabFileInfo item in files) { list.Add(item); } return list.AsReadOnly(); } } internal sealed class HandleManager<T> where T : class { private List<T> handles; public T this[int handle] { get { if (handle > 0 && handle <= handles.Count) { return handles[checked(handle - 1)]; } return null; } } public HandleManager() { handles = new List<T>(); } public int AllocHandle(T obj) { handles.Add(obj); return handles.Count; } public void FreeHandle(int handle) { if (handle > 0 && handle <= handles.Count) { handles[checked(handle - 1)] = null; } } } internal static class NativeMethods { internal static class FCI { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr PFNALLOC(int cb); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void PFNFREE(IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNOPEN(string path, int oflag, int pmode, out int err, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNREAD(int fileHandle, IntPtr memory, int cb, out int err, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNWRITE(int fileHandle, IntPtr memory, int cb, out int err, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNCLOSE(int fileHandle, out int err, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNSEEK(int fileHandle, int dist, int seekType, out int err, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNDELETE(string path, out int err, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNGETNEXTCABINET(IntPtr pccab, uint cbPrevCab, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNFILEPLACED(IntPtr pccab, string path, long fileSize, int continuation, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNGETOPENINFO(string path, out short date, out short time, out short pattribs, out int err, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNSTATUS(STATUS typeStatus, uint cb1, uint cb2, IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNGETTEMPFILE(IntPtr tempNamePtr, int tempNameSize, IntPtr pv); internal enum ERROR { NONE, OPEN_SRC, READ_SRC, ALLOC_FAIL, TEMP_FILE, BAD_COMPR_TYPE, CAB_FILE, USER_ABORT, MCI_FAIL } internal enum TCOMP : ushort { MASK_TYPE = 15, TYPE_NONE = 0, TYPE_MSZIP = 1, TYPE_QUANTUM = 2, TYPE_LZX = 3, BAD = 15, MASK_LZX_WINDOW = 7936, LZX_WINDOW_LO = 3840, LZX_WINDOW_HI = 5376, SHIFT_LZX_WINDOW = 8, MASK_QUANTUM_LEVEL = 240, QUANTUM_LEVEL_LO = 16, QUANTUM_LEVEL_HI = 112, SHIFT_QUANTUM_LEVEL = 4, MASK_QUANTUM_MEM = 7936, QUANTUM_MEM_LO = 2560, QUANTUM_MEM_HI = 5376, SHIFT_QUANTUM_MEM = 8, MASK_RESERVED = 57344 } internal enum STATUS : uint { FILE, FOLDER, CABINET } [StructLayout(LayoutKind.Sequential)] internal class CCAB { internal int cb = int.MaxValue; internal int cbFolderThresh = 2147450880; internal int cbReserveCFHeader; internal int cbReserveCFFolder; internal int cbReserveCFData; internal int iCab; internal int iDisk; internal int fFailOnIncompressible; internal short setID; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] internal string szDisk = string.Empty; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] internal string szCab = string.Empty; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] internal string szCabPath = string.Empty; } internal class Handle : SafeHandle { public override bool IsInvalid => handle == IntPtr.Zero; internal Handle() : base(IntPtr.Zero, ownsHandle: true) { } [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)] protected override bool ReleaseHandle() { return Destroy(handle); } } internal const int MIN_DISK = 32768; internal const int MAX_DISK = int.MaxValue; internal const int MAX_FOLDER = 2147450880; internal const int MAX_FILENAME = 256; internal const int MAX_CABINET_NAME = 256; internal const int MAX_CAB_PATH = 256; internal const int MAX_DISK_NAME = 256; internal const int CPU_80386 = 1; [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FCICreate", ThrowOnUnmappableChar = true)] internal static extern Handle Create(IntPtr perf, PFNFILEPLACED pfnfcifp, PFNALLOC pfna, PFNFREE pfnf, PFNOPEN pfnopen, PFNREAD pfnread, PFNWRITE pfnwrite, PFNCLOSE pfnclose, PFNSEEK pfnseek, PFNDELETE pfndelete, PFNGETTEMPFILE pfnfcigtf, [MarshalAs(UnmanagedType.LPStruct)] CCAB pccab, IntPtr pv); [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FCIAddFile", ThrowOnUnmappableChar = true)] internal static extern int AddFile(Handle hfci, string pszSourceFile, IntPtr pszFileName, [MarshalAs(UnmanagedType.Bool)] bool fExecute, PFNGETNEXTCABINET pfnfcignc, PFNSTATUS pfnfcis, PFNGETOPENINFO pfnfcigoi, TCOMP typeCompress); [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FCIFlushCabinet", ThrowOnUnmappableChar = true)] internal static extern int FlushCabinet(Handle hfci, [MarshalAs(UnmanagedType.Bool)] bool fGetNextCab, PFNGETNEXTCABINET pfnfcignc, PFNSTATUS pfnfcis); [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FCIFlushFolder", ThrowOnUnmappableChar = true)] internal static extern int FlushFolder(Handle hfci, PFNGETNEXTCABINET pfnfcignc, PFNSTATUS pfnfcis); [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FCIDestroy", ThrowOnUnmappableChar = true)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool Destroy(IntPtr hfci); } internal static class FDI { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr PFNALLOC(int cb); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void PFNFREE(IntPtr pv); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNOPEN(string path, int oflag, int pmode); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNREAD(int hf, IntPtr pv, int cb); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNWRITE(int hf, IntPtr pv, int cb); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNCLOSE(int hf); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNSEEK(int hf, int dist, int seektype); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int PFNNOTIFY(NOTIFICATIONTYPE fdint, NOTIFICATION fdin); internal enum ERROR { NONE, CABINET_NOT_FOUND, NOT_A_CABINET, UNKNOWN_CABINET_VERSION, CORRUPT_CABINET, ALLOC_FAIL, BAD_COMPR_TYPE, MDI_FAIL, TARGET_FILE, RESERVE_MISMATCH, WRONG_CABINET, USER_ABORT } internal enum NOTIFICATIONTYPE { CABINET_INFO, PARTIAL_FILE, COPY_FILE, CLOSE_FILE_INFO, NEXT_CABINET, ENUMERATE } internal struct CABINFO { internal int cbCabinet; internal short cFolders; internal short cFiles; internal short setID; internal short iCabinet; internal int fReserve; internal int hasprev; internal int hasnext; } [StructLayout(LayoutKind.Sequential)] internal class NOTIFICATION { internal int cb; internal IntPtr psz1; internal IntPtr psz2; internal IntPtr psz3; internal IntPtr pv; internal IntPtr hf_ptr; internal short date; internal short time; internal short attribs; internal short setID; internal short iCabinet; internal short iFolder; internal int fdie; internal int hf => (int)hf_ptr; } internal class Handle : SafeHandle { public override bool IsInvalid => handle == IntPtr.Zero; internal Handle() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { return Destroy(handle); } } internal const int MAX_DISK = int.MaxValue; internal const int MAX_FILENAME = 256; internal const int MAX_CABINET_NAME = 256; internal const int MAX_CAB_PATH = 256; internal const int MAX_DISK_NAME = 256; internal const int CPU_80386 = 1; [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FDICreate", ThrowOnUnmappableChar = true)] internal static extern Handle Create([MarshalAs(UnmanagedType.FunctionPtr)] PFNALLOC pfnalloc, [MarshalAs(UnmanagedType.FunctionPtr)] PFNFREE pfnfree, PFNOPEN pfnopen, PFNREAD pfnread, PFNWRITE pfnwrite, PFNCLOSE pfnclose, PFNSEEK pfnseek, int cpuType, IntPtr perf); [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FDICopy", ThrowOnUnmappableChar = true)] internal static extern int Copy(Handle hfdi, string pszCabinet, string pszCabPath, int flags, PFNNOTIFY pfnfdin, IntPtr pfnfdid, IntPtr pvUser); [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FDIDestroy", ThrowOnUnmappableChar = true)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool Destroy(IntPtr hfdi); [DllImport("cabinet.dll", BestFitMapping = false, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "FDIIsCabinet", ThrowOnUnmappableChar = true)] internal static extern int IsCabinet(Handle hfdi, int hf, out CABINFO pfdici); } [StructLayout(LayoutKind.Sequential)] internal class ERF { private int erfOper; private int erfType; private int fError; internal int Oper { get { return erfOper; } set { erfOper = value; } } internal int Type { get { return erfType; } set { erfType = value; } } internal bool Error { get { return fError != 0; } set { fError = (value ? 1 : 0); } } internal void Clear() { Oper = 0; Type = 0; Error = false; } } } }
patchers/FixPluginTypesSerialization/Microsoft.Deployment.Compression.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyDescription("Abstract base libraries for archive packing and unpacking")] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyFileVersion("3.10.1.2213")] [assembly: AssemblyCompany("Outercurve Foundation")] [assembly: AssemblyCopyright("Copyright (c) Outercurve Foundation. All rights reserved.")] [assembly: AssemblyProduct("Windows Installer XML Toolset")] [assembly: AssemblyConfiguration("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, Unrestricted = true)] [assembly: AssemblyVersion("3.0.0.0")] namespace Microsoft.Tools.WindowsInstallerXml { internal static class WixDistribution { public static string NewsUrl = "http://wixtoolset.org/news/"; public static string ShortProduct = "WiX Toolset"; public static string SupportUrl = "http://wixtoolset.org/"; public static string TelemetryUrlFormat = "http://wixtoolset.org/telemetry/v{0}/?r={1}"; public static string ReplacePlaceholders(string original, Assembly assembly) { if ((object)assembly != null) { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); original = original.Replace("[FileComments]", versionInfo.Comments); original = original.Replace("[FileCopyright]", versionInfo.LegalCopyright); original = original.Replace("[FileProductName]", versionInfo.ProductName); original = original.Replace("[FileVersion]", versionInfo.FileVersion); if (original.Contains("[FileVersionMajorMinor]")) { Version version = new Version(versionInfo.FileVersion); original = original.Replace("[FileVersionMajorMinor]", version.Major + "." + version.Minor); } if (TryGetAttribute<AssemblyCompanyAttribute>(assembly, out var attribute)) { original = original.Replace("[AssemblyCompany]", attribute.Company); } if (TryGetAttribute<AssemblyCopyrightAttribute>(assembly, out var attribute2)) { original = original.Replace("[AssemblyCopyright]", attribute2.Copyright); } if (TryGetAttribute<AssemblyDescriptionAttribute>(assembly, out var attribute3)) { original = original.Replace("[AssemblyDescription]", attribute3.Description); } if (TryGetAttribute<AssemblyProductAttribute>(assembly, out var attribute4)) { original = original.Replace("[AssemblyProduct]", attribute4.Product); } if (TryGetAttribute<AssemblyTitleAttribute>(assembly, out var attribute5)) { original = original.Replace("[AssemblyTitle]", attribute5.Title); } } original = original.Replace("[NewsUrl]", NewsUrl); original = original.Replace("[ShortProduct]", ShortProduct); original = original.Replace("[SupportUrl]", SupportUrl); return original; } private static bool TryGetAttribute<T>(Assembly assembly, out T attribute) where T : Attribute { attribute = null; object[] customAttributes = assembly.GetCustomAttributes(typeof(T), inherit: false); if (customAttributes != null && customAttributes.Length != 0) { attribute = customAttributes[0] as T; } return attribute != null; } } } namespace Microsoft.Deployment.Compression { [Serializable] public class ArchiveException : IOException { public ArchiveException(string message, Exception innerException) : base(message, innerException) { } public ArchiveException(string message) : this(message, null) { } public ArchiveException() : this(null, null) { } protected ArchiveException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public abstract class ArchiveFileInfo : FileSystemInfo { private ArchiveInfo archiveInfo; private string name; private string path; private bool initialized; private bool exists; private int archiveNumber; private FileAttributes attributes; private DateTime lastWriteTime; private long length; public override string Name => name; public string Path => path; public override string FullName { get { string text = System.IO.Path.Combine(Path, Name); if (Archive != null) { text = System.IO.Path.Combine(ArchiveName, text); } return text; } } public ArchiveInfo Archive { get { return archiveInfo; } internal set { archiveInfo = value; OriginalPath = value?.FullName; FullPath = OriginalPath; } } public string ArchiveName { get { if (Archive == null) { return null; } return Archive.FullName; } } public int ArchiveNumber => archiveNumber; public override bool Exists { get { if (!initialized) { Refresh(); } return exists; } } public long Length { get { if (!initialized) { Refresh(); } return length; } } public new FileAttributes Attributes { get { if (!initialized) { Refresh(); } return attributes; } } public new DateTime LastWriteTime { get { if (!initialized) { Refresh(); } return lastWriteTime; } } protected ArchiveFileInfo(ArchiveInfo archiveInfo, string filePath) { if (filePath == null) { throw new ArgumentNullException("filePath"); } Archive = archiveInfo; name = System.IO.Path.GetFileName(filePath); path = System.IO.Path.GetDirectoryName(filePath); attributes = FileAttributes.Normal; lastWriteTime = DateTime.MinValue; } protected ArchiveFileInfo(string filePath, int archiveNumber, FileAttributes attributes, DateTime lastWriteTime, long length) : this(null, filePath) { exists = true; this.archiveNumber = archiveNumber; this.attributes = attributes; this.lastWriteTime = lastWriteTime; this.length = length; initialized = true; } protected ArchiveFileInfo(SerializationInfo info, StreamingContext context) : base(info, context) { archiveInfo = (ArchiveInfo)info.GetValue("archiveInfo", typeof(ArchiveInfo)); name = info.GetString("name"); path = info.GetString("path"); initialized = info.GetBoolean("initialized"); exists = info.GetBoolean("exists"); archiveNumber = info.GetInt32("archiveNumber"); attributes = (FileAttributes)info.GetValue("attributes", typeof(FileAttributes)); lastWriteTime = info.GetDateTime("lastWriteTime"); length = info.GetInt64("length"); } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("archiveInfo", archiveInfo); info.AddValue("name", name); info.AddValue("path", path); info.AddValue("initialized", initialized); info.AddValue("exists", exists); info.AddValue("archiveNumber", archiveNumber); info.AddValue("attributes", attributes); info.AddValue("lastWriteTime", lastWriteTime); info.AddValue("length", length); } public override string ToString() { return FullName; } public override void Delete() { throw new NotSupportedException(); } public new void Refresh() { base.Refresh(); if (Archive != null) { string fileName = System.IO.Path.Combine(Path, Name); ArchiveFileInfo file = Archive.GetFile(fileName); if (file == null) { throw new FileNotFoundException("File not found in archive.", fileName); } Refresh(file); } } public void CopyTo(string destFileName) { CopyTo(destFileName, overwrite: false); } public void CopyTo(string destFileName, bool overwrite) { if (destFileName == null) { throw new ArgumentNullException("destFileName"); } if (!overwrite && File.Exists(destFileName)) { throw new IOException(); } if (Archive == null) { throw new InvalidOperationException(); } Archive.UnpackFile(System.IO.Path.Combine(Path, Name), destFileName); } public Stream OpenRead() { return Archive.OpenRead(System.IO.Path.Combine(Path, Name)); } public StreamReader OpenText() { return Archive.OpenText(System.IO.Path.Combine(Path, Name)); } protected virtual void Refresh(ArchiveFileInfo newFileInfo) { exists = newFileInfo.exists; length = newFileInfo.length; attributes = newFileInfo.attributes; lastWriteTime = newFileInfo.lastWriteTime; } } [Serializable] public abstract class ArchiveInfo : FileSystemInfo { public DirectoryInfo Directory => new DirectoryInfo(Path.GetDirectoryName(FullName)); public string DirectoryName => Path.GetDirectoryName(FullName); public long Length => new FileInfo(FullName).Length; public override string Name => Path.GetFileName(FullName); public override bool Exists => File.Exists(FullName); protected ArchiveInfo(string path) { if (path == null) { throw new ArgumentNullException("path"); } OriginalPath = path; FullPath = Path.GetFullPath(path); } protected ArchiveInfo(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string ToString() { return FullName; } public override void Delete() { File.Delete(FullName); } public void CopyTo(string destFileName) { File.Copy(FullName, destFileName); } public void CopyTo(string destFileName, bool overwrite) { File.Copy(FullName, destFileName, overwrite); } public void MoveTo(string destFileName) { File.Move(FullName, destFileName); FullPath = Path.GetFullPath(destFileName); } public bool IsValid() { using Stream stream = File.OpenRead(FullName); using CompressionEngine compressionEngine = CreateCompressionEngine(); return compressionEngine.FindArchiveOffset(stream) >= 0; } public IList<ArchiveFileInfo> GetFiles() { return InternalGetFiles(null); } public IList<ArchiveFileInfo> GetFiles(string searchPattern) { if (searchPattern == null) { throw new ArgumentNullException("searchPattern"); } string pattern = string.Format(CultureInfo.InvariantCulture, "^{0}$", new object[1] { Regex.Escape(searchPattern).Replace("\\*", ".*").Replace("\\?", ".") }); Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); return InternalGetFiles((string match) => regex.IsMatch(match)); } public void Unpack(string destDirectory) { Unpack(destDirectory, null); } public void Unpack(string destDirectory, EventHandler<ArchiveProgressEventArgs> progressHandler) { using CompressionEngine compressionEngine = CreateCompressionEngine(); compressionEngine.Progress += progressHandler; ArchiveFileStreamContext archiveFileStreamContext = new ArchiveFileStreamContext(FullName, destDirectory, null); archiveFileStreamContext.EnableOffsetOpen = true; compressionEngine.Unpack(archiveFileStreamContext, null); } public void UnpackFile(string fileName, string destFileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (destFileName == null) { throw new ArgumentNullException("destFileName"); } UnpackFiles(new string[1] { fileName }, null, new string[1] { destFileName }); } public void UnpackFiles(IList<string> fileNames, string destDirectory, IList<string> destFileNames) { UnpackFiles(fileNames, destDirectory, destFileNames, null); } public void UnpackFiles(IList<string> fileNames, string destDirectory, IList<string> destFileNames, EventHandler<ArchiveProgressEventArgs> progressHandler) { if (fileNames == null) { throw new ArgumentNullException("fileNames"); } if (destFileNames == null) { if (destDirectory == null) { throw new ArgumentNullException("destFileNames"); } destFileNames = fileNames; } if (destFileNames.Count != fileNames.Count) { throw new ArgumentOutOfRangeException("destFileNames"); } IDictionary<string, string> fileNames2 = CreateStringDictionary(fileNames, destFileNames); UnpackFileSet(fileNames2, destDirectory, progressHandler); } public void UnpackFileSet(IDictionary<string, string> fileNames, string destDirectory) { UnpackFileSet(fileNames, destDirectory, null); } public void UnpackFileSet(IDictionary<string, string> fileNames, string destDirectory, EventHandler<ArchiveProgressEventArgs> progressHandler) { if (fileNames == null) { throw new ArgumentNullException("fileNames"); } using CompressionEngine compressionEngine = CreateCompressionEngine(); compressionEngine.Progress += progressHandler; ArchiveFileStreamContext archiveFileStreamContext = new ArchiveFileStreamContext(FullName, destDirectory, fileNames); archiveFileStreamContext.EnableOffsetOpen = true; compressionEngine.Unpack(archiveFileStreamContext, (string match) => fileNames.ContainsKey(match)); } public Stream OpenRead(string fileName) { Stream stream = File.OpenRead(FullName); CompressionEngine compressionEngine = CreateCompressionEngine(); return new CargoStream(compressionEngine.Unpack(stream, fileName), stream, compressionEngine); } public StreamReader OpenText(string fileName) { return new StreamReader(OpenRead(fileName)); } public void Pack(string sourceDirectory) { Pack(sourceDirectory, includeSubdirectories: false, CompressionLevel.Max, null); } public void Pack(string sourceDirectory, bool includeSubdirectories, CompressionLevel compLevel, EventHandler<ArchiveProgressEventArgs> progressHandler) { IList<string> relativeFilePathsInDirectoryTree = GetRelativeFilePathsInDirectoryTree(sourceDirectory, includeSubdirectories); PackFiles(sourceDirectory, relativeFilePathsInDirectoryTree, relativeFilePathsInDirectoryTree, compLevel, progressHandler); } public void PackFiles(string sourceDirectory, IList<string> sourceFileNames, IList<string> fileNames) { PackFiles(sourceDirectory, sourceFileNames, fileNames, CompressionLevel.Max, null); } public void PackFiles(string sourceDirectory, IList<string> sourceFileNames, IList<string> fileNames, CompressionLevel compLevel, EventHandler<ArchiveProgressEventArgs> progressHandler) { if (sourceFileNames == null) { throw new ArgumentNullException("sourceFileNames"); } if (fileNames == null) { string[] array = new string[sourceFileNames.Count]; for (int i = 0; i < sourceFileNames.Count; i = checked(i + 1)) { array[i] = Path.GetFileName(sourceFileNames[i]); } fileNames = array; } else if (fileNames.Count != sourceFileNames.Count) { throw new ArgumentOutOfRangeException("fileNames"); } using CompressionEngine compressionEngine = CreateCompressionEngine(); compressionEngine.Progress += progressHandler; IDictionary<string, string> files = CreateStringDictionary(fileNames, sourceFileNames); ArchiveFileStreamContext archiveFileStreamContext = new ArchiveFileStreamContext(FullName, sourceDirectory, files); archiveFileStreamContext.EnableOffsetOpen = true; compressionEngine.CompressionLevel = compLevel; compressionEngine.Pack(archiveFileStreamContext, fileNames); } public void PackFileSet(string sourceDirectory, IDictionary<string, string> fileNames) { PackFileSet(sourceDirectory, fileNames, CompressionLevel.Max, null); } public void PackFileSet(string sourceDirectory, IDictionary<string, string> fileNames, CompressionLevel compLevel, EventHandler<ArchiveProgressEventArgs> progressHandler) { if (fileNames == null) { throw new ArgumentNullException("fileNames"); } string[] array = new string[fileNames.Count]; fileNames.Keys.CopyTo(array, 0); using CompressionEngine compressionEngine = CreateCompressionEngine(); compressionEngine.Progress += progressHandler; ArchiveFileStreamContext archiveFileStreamContext = new ArchiveFileStreamContext(FullName, sourceDirectory, fileNames); archiveFileStreamContext.EnableOffsetOpen = true; compressionEngine.CompressionLevel = compLevel; compressionEngine.Pack(archiveFileStreamContext, array); } internal IList<string> GetRelativeFilePathsInDirectoryTree(string dir, bool includeSubdirectories) { IList<string> list = new List<string>(); RecursiveGetRelativeFilePathsInDirectoryTree(dir, string.Empty, includeSubdirectories, list); return list; } internal ArchiveFileInfo GetFile(string path) { IList<ArchiveFileInfo> list = InternalGetFiles((string match) => string.Compare(match, path, ignoreCase: true, CultureInfo.InvariantCulture) == 0); if (list == null || list.Count <= 0) { return null; } return list[0]; } protected abstract CompressionEngine CreateCompressionEngine(); private static IDictionary<string, string> CreateStringDictionary(IList<string> keys, IList<string> values) { IDictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < keys.Count; i = checked(i + 1)) { dictionary.Add(keys[i], values[i]); } return dictionary; } private void RecursiveGetRelativeFilePathsInDirectoryTree(string dir, string relativeDir, bool includeSubdirectories, IList<string> fileList) { string[] files = System.IO.Directory.GetFiles(dir); for (int i = 0; i < files.Length; i++) { string fileName = Path.GetFileName(files[i]); fileList.Add(Path.Combine(relativeDir, fileName)); } if (includeSubdirectories) { files = System.IO.Directory.GetDirectories(dir); for (int i = 0; i < files.Length; i++) { string fileName2 = Path.GetFileName(files[i]); RecursiveGetRelativeFilePathsInDirectoryTree(Path.Combine(dir, fileName2), Path.Combine(relativeDir, fileName2), includeSubdirectories, fileList); } } } private IList<ArchiveFileInfo> InternalGetFiles(Predicate<string> fileFilter) { using CompressionEngine compressionEngine = CreateCompressionEngine(); ArchiveFileStreamContext archiveFileStreamContext = new ArchiveFileStreamContext(FullName, null, null); archiveFileStreamContext.EnableOffsetOpen = true; IList<ArchiveFileInfo> fileInfo = compressionEngine.GetFileInfo(archiveFileStreamContext, fileFilter); for (int i = 0; i < fileInfo.Count; i = checked(i + 1)) { fileInfo[i].Archive = this; } return fileInfo; } } public class ArchiveProgressEventArgs : EventArgs { private ArchiveProgressType progressType; private string currentFileName; private int currentFileNumber; private int totalFiles; private long currentFileBytesProcessed; private long currentFileTotalBytes; private string currentArchiveName; private short currentArchiveNumber; private short totalArchives; private long currentArchiveBytesProcessed; private long currentArchiveTotalBytes; private long fileBytesProcessed; private long totalFileBytes; public ArchiveProgressType ProgressType => progressType; public string CurrentFileName => currentFileName; public int CurrentFileNumber => currentFileNumber; public int TotalFiles => totalFiles; public long CurrentFileBytesProcessed => currentFileBytesProcessed; public long CurrentFileTotalBytes => currentFileTotalBytes; public string CurrentArchiveName => currentArchiveName; public int CurrentArchiveNumber => currentArchiveNumber; public int TotalArchives => totalArchives; public long CurrentArchiveBytesProcessed => currentArchiveBytesProcessed; public long CurrentArchiveTotalBytes => currentArchiveTotalBytes; public long FileBytesProcessed => fileBytesProcessed; public long TotalFileBytes => totalFileBytes; public ArchiveProgressEventArgs(ArchiveProgressType progressType, string currentFileName, int currentFileNumber, int totalFiles, long currentFileBytesProcessed, long currentFileTotalBytes, string currentArchiveName, int currentArchiveNumber, int totalArchives, long currentArchiveBytesProcessed, long currentArchiveTotalBytes, long fileBytesProcessed, long totalFileBytes) { this.progressType = progressType; this.currentFileName = currentFileName; this.currentFileNumber = currentFileNumber; this.totalFiles = totalFiles; this.currentFileBytesProcessed = currentFileBytesProcessed; this.currentFileTotalBytes = currentFileTotalBytes; this.currentArchiveName = currentArchiveName; checked { this.currentArchiveNumber = (short)currentArchiveNumber; this.totalArchives = (short)totalArchives; this.currentArchiveBytesProcessed = currentArchiveBytesProcessed; this.currentArchiveTotalBytes = currentArchiveTotalBytes; this.fileBytesProcessed = fileBytesProcessed; this.totalFileBytes = totalFileBytes; } } } public enum ArchiveProgressType { StartFile, PartialFile, FinishFile, StartArchive, PartialArchive, FinishArchive } public class ArchiveFileStreamContext : IPackStreamContext, IUnpackStreamContext { private IList<string> archiveFiles; private string directory; private IDictionary<string, string> files; private bool extractOnlyNewerFiles; private bool enableOffsetOpen; public IList<string> ArchiveFiles => archiveFiles; public string Directory => directory; public IDictionary<string, string> Files => files; public bool ExtractOnlyNewerFiles { get { return extractOnlyNewerFiles; } set { extractOnlyNewerFiles = value; } } public bool EnableOffsetOpen { get { return enableOffsetOpen; } set { enableOffsetOpen = value; } } public ArchiveFileStreamContext(string archiveFile) : this(archiveFile, null, null) { } public ArchiveFileStreamContext(string archiveFile, string directory, IDictionary<string, string> files) : this(new string[1] { archiveFile }, directory, files) { if (archiveFile == null) { throw new ArgumentNullException("archiveFile"); } } public ArchiveFileStreamContext(IList<string> archiveFiles, string directory, IDictionary<string, string> files) { if (archiveFiles == null || archiveFiles.Count == 0) { throw new ArgumentNullException("archiveFiles"); } this.archiveFiles = archiveFiles; this.directory = directory; this.files = files; } public virtual string GetArchiveName(int archiveNumber) { if (archiveNumber < archiveFiles.Count) { return Path.GetFileName(archiveFiles[archiveNumber]); } return string.Empty; } public virtual Stream OpenArchiveWriteStream(int archiveNumber, string archiveName, bool truncate, CompressionEngine compressionEngine) { if (archiveNumber >= archiveFiles.Count) { return null; } if (string.IsNullOrEmpty(archiveName)) { throw new ArgumentNullException("archiveName"); } Stream stream = File.Open(Path.Combine(Path.GetDirectoryName(archiveFiles[0]), archiveName), truncate ? FileMode.OpenOrCreate : FileMode.Open, FileAccess.ReadWrite); if (enableOffsetOpen) { long num = compressionEngine.FindArchiveOffset(new DuplicateStream(stream)); if (num < 0) { num = stream.Length; } if (num > 0) { stream = new OffsetStream(stream, num); } stream.Seek(0L, SeekOrigin.Begin); } if (truncate) { stream.SetLength(0L); } return stream; } public virtual void CloseArchiveWriteStream(int archiveNumber, string archiveName, Stream stream) { if (stream == null) { return; } stream.Close(); if (!(stream is FileStream fileStream)) { return; } string name = fileStream.Name; if (!string.IsNullOrEmpty(archiveName) && archiveName != Path.GetFileName(name)) { string text = Path.Combine(Path.GetDirectoryName(archiveFiles[0]), archiveName); if (File.Exists(text)) { File.Delete(text); } File.Move(name, text); } } public virtual Stream OpenFileReadStream(string path, out FileAttributes attributes, out DateTime lastWriteTime) { string text = TranslateFilePath(path); if (text == null) { attributes = FileAttributes.Normal; lastWriteTime = DateTime.Now; return null; } attributes = File.GetAttributes(text); lastWriteTime = File.GetLastWriteTime(text); return File.Open(text, FileMode.Open, FileAccess.Read, FileShare.Read); } public virtual void CloseFileReadStream(string path, Stream stream) { stream?.Close(); } public virtual object GetOption(string optionName, object[] parameters) { return null; } public virtual Stream OpenArchiveReadStream(int archiveNumber, string archiveName, CompressionEngine compressionEngine) { if (archiveNumber >= archiveFiles.Count) { return null; } Stream stream = File.Open(archiveFiles[archiveNumber], FileMode.Open, FileAccess.Read, FileShare.Read); if (enableOffsetOpen) { long num = compressionEngine.FindArchiveOffset(new DuplicateStream(stream)); if (num > 0) { stream = new OffsetStream(stream, num); } else { stream.Seek(0L, SeekOrigin.Begin); } } return stream; } public virtual void CloseArchiveReadStream(int archiveNumber, string archiveName, Stream stream) { stream?.Close(); } public virtual Stream OpenFileWriteStream(string path, long fileSize, DateTime lastWriteTime) { string text = TranslateFilePath(path); if (text == null) { return null; } FileInfo fileInfo = new FileInfo(text); if (fileInfo.Exists) { if (extractOnlyNewerFiles && lastWriteTime != DateTime.MinValue && fileInfo.LastWriteTime >= lastWriteTime) { return null; } FileAttributes fileAttributes = FileAttributes.ReadOnly | FileAttributes.Hidden | FileAttributes.System; if ((fileInfo.Attributes & fileAttributes) != 0) { fileInfo.Attributes &= ~fileAttributes; } } if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } return File.Open(text, FileMode.Create, FileAccess.Write, FileShare.None); } public virtual void CloseFileWriteStream(string path, Stream stream, FileAttributes attributes, DateTime lastWriteTime) { stream?.Close(); string text = TranslateFilePath(path); if (text == null) { return; } FileInfo fileInfo = new FileInfo(text); if (lastWriteTime != DateTime.MinValue) { try { fileInfo.LastWriteTime = lastWriteTime; } catch (ArgumentException) { } catch (IOException) { } } try { fileInfo.Attributes = attributes; } catch (IOException) { } } private string TranslateFilePath(string path) { string text = ((files == null) ? path : files[path]); if (text != null && directory != null) { text = Path.Combine(directory, text); } return text; } } public class BasicUnpackStreamContext : IUnpackStreamContext { private Stream archiveStream; private Stream fileStream; public Stream FileStream => fileStream; public BasicUnpackStreamContext(Stream archiveStream) { this.archiveStream = archiveStream; } public Stream OpenArchiveReadStream(int archiveNumber, string archiveName, CompressionEngine compressionEngine) { return new DuplicateStream(archiveStream); } public void CloseArchiveReadStream(int archiveNumber, string archiveName, Stream stream) { } public Stream OpenFileWriteStream(string path, long fileSize, DateTime lastWriteTime) { fileStream = new MemoryStream(new byte[fileSize], 0, checked((int)fileSize), writable: true, publiclyVisible: true); return fileStream; } public void CloseFileWriteStream(string path, Stream stream, FileAttributes attributes, DateTime lastWriteTime) { } } public abstract class CompressionEngine : IDisposable { private CompressionLevel compressionLevel; private bool dontUseTempFiles; public bool UseTempFiles { get { return !dontUseTempFiles; } set { dontUseTempFiles = !value; } } public CompressionLevel CompressionLevel { get { return compressionLevel; } set { compressionLevel = value; } } public event EventHandler<ArchiveProgressEventArgs> Progress; protected CompressionEngine() { compressionLevel = CompressionLevel.Normal; } ~CompressionEngine() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public void Pack(IPackStreamContext streamContext, IEnumerable<string> files) { if (files == null) { throw new ArgumentNullException("files"); } Pack(streamContext, files, 0L); } public abstract void Pack(IPackStreamContext streamContext, IEnumerable<string> files, long maxArchiveSize); public abstract bool IsArchive(Stream stream); public virtual long FindArchiveOffset(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } long num = 4L; long length = stream.Length; checked { for (long num2 = 0L; num2 <= length - num; num2 += num) { stream.Seek(num2, SeekOrigin.Begin); if (IsArchive(stream)) { return num2; } } return -1L; } } public IList<ArchiveFileInfo> GetFileInfo(Stream stream) { return GetFileInfo(new BasicUnpackStreamContext(stream), null); } public abstract IList<ArchiveFileInfo> GetFileInfo(IUnpackStreamContext streamContext, Predicate<string> fileFilter); public IList<string> GetFiles(Stream stream) { return GetFiles(new BasicUnpackStreamContext(stream), null); } public IList<string> GetFiles(IUnpackStreamContext streamContext, Predicate<string> fileFilter) { if (streamContext == null) { throw new ArgumentNullException("streamContext"); } IList<ArchiveFileInfo> fileInfo = GetFileInfo(streamContext, fileFilter); IList<string> list = new List<string>(fileInfo.Count); for (int i = 0; i < fileInfo.Count; i = checked(i + 1)) { list.Add(fileInfo[i].Name); } return list; } public Stream Unpack(Stream stream, string path) { if (stream == null) { throw new ArgumentNullException("stream"); } if (path == null) { throw new ArgumentNullException("path"); } BasicUnpackStreamContext basicUnpackStreamContext = new BasicUnpackStreamContext(stream); Unpack(basicUnpackStreamContext, (string match) => string.Compare(match, path, ignoreCase: true, CultureInfo.InvariantCulture) == 0); Stream fileStream = basicUnpackStreamContext.FileStream; if (fileStream != null) { fileStream.Position = 0L; } return fileStream; } public abstract void Unpack(IUnpackStreamContext streamContext, Predicate<string> fileFilter); protected void OnProgress(ArchiveProgressEventArgs e) { if (this.Progress != null) { this.Progress(this, e); } } protected virtual void Dispose(bool disposing) { } public static void DosDateAndTimeToDateTime(short dosDate, short dosTime, out DateTime dateTime) { if (dosDate == 0 && dosTime == 0) { dateTime = DateTime.MinValue; return; } SafeNativeMethods.DosDateTimeToFileTime(dosDate, dosTime, out var fileTime); dateTime = DateTime.FromFileTimeUtc(fileTime); dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Local); } public static void DateTimeToDosDateAndTime(DateTime dateTime, out short dosDate, out short dosTime) { dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Utc); long fileTime = dateTime.ToFileTimeUtc(); SafeNativeMethods.FileTimeToDosDateTime(ref fileTime, out dosDate, out dosTime); } } public enum CompressionLevel { None = 0, Min = 1, Normal = 6, Max = 10 } public class CargoStream : Stream { private Stream source; private List<IDisposable> cargo; public Stream Source => source; public IList<IDisposable> Cargo => cargo; public override bool CanRead => source.CanRead; public override bool CanWrite => source.CanWrite; public override bool CanSeek => source.CanSeek; public override long Length => source.Length; public override long Position { get { return source.Position; } set { source.Position = value; } } public CargoStream(Stream source, params IDisposable[] cargo) { if (source == null) { throw new ArgumentNullException("source"); } this.source = source; this.cargo = new List<IDisposable>(cargo); } public override void Flush() { source.Flush(); } public override void SetLength(long value) { source.SetLength(value); } public override void Close() { source.Close(); foreach (IDisposable item in cargo) { item.Dispose(); } } public override int Read(byte[] buffer, int offset, int count) { return source.Read(buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { source.Write(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return source.Seek(offset, origin); } } public class DuplicateStream : Stream { private Stream source; private long position; public Stream Source => source; public override bool CanRead => source.CanRead; public override bool CanWrite => source.CanWrite; public override bool CanSeek => source.CanSeek; public override long Length => source.Length; public override long Position { get { return position; } set { position = value; } } public DuplicateStream(Stream source) { if (source == null) { throw new ArgumentNullException("source"); } this.source = OriginalStream(source); } public static Stream OriginalStream(Stream stream) { if (!(stream is DuplicateStream duplicateStream)) { return stream; } return duplicateStream.Source; } public override void Flush() { source.Flush(); } public override void SetLength(long value) { source.SetLength(value); } public override void Close() { source.Close(); } public override int Read(byte[] buffer, int offset, int count) { long num = source.Position; source.Position = position; int result = source.Read(buffer, offset, count); position = source.Position; source.Position = num; return result; } public override void Write(byte[] buffer, int offset, int count) { long num = source.Position; source.Position = position; source.Write(buffer, offset, count); position = source.Position; source.Position = num; } public override long Seek(long offset, SeekOrigin origin) { long num = 0L; switch (origin) { case SeekOrigin.Current: num = position; break; case SeekOrigin.End: num = Length; break; } position = checked(num + offset); return position; } } public interface IPackStreamContext { string GetArchiveName(int archiveNumber); Stream OpenArchiveWriteStream(int archiveNumber, string archiveName, bool truncate, CompressionEngine compressionEngine); void CloseArchiveWriteStream(int archiveNumber, string archiveName, Stream stream); Stream OpenFileReadStream(string path, out FileAttributes attributes, out DateTime lastWriteTime); void CloseFileReadStream(string path, Stream stream); object GetOption(string optionName, object[] parameters); } public interface IUnpackStreamContext { Stream OpenArchiveReadStream(int archiveNumber, string archiveName, CompressionEngine compressionEngine); void CloseArchiveReadStream(int archiveNumber, string archiveName, Stream stream); Stream OpenFileWriteStream(string path, long fileSize, DateTime lastWriteTime); void CloseFileWriteStream(string path, Stream stream, FileAttributes attributes, DateTime lastWriteTime); } public class OffsetStream : Stream { private Stream source; private long sourceOffset; public Stream Source => source; public long Offset => sourceOffset; public override bool CanRead => source.CanRead; public override bool CanWrite => source.CanWrite; public override bool CanSeek => source.CanSeek; public override long Length => checked(source.Length - sourceOffset); public override long Position { get { return checked(source.Position - sourceOffset); } set { source.Position = checked(value + sourceOffset); } } public OffsetStream(Stream source, long offset) { if (source == null) { throw new ArgumentNullException("source"); } this.source = source; sourceOffset = offset; this.source.Seek(sourceOffset, SeekOrigin.Current); } public override int Read(byte[] buffer, int offset, int count) { return source.Read(buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { source.Write(buffer, offset, count); } public override int ReadByte() { return source.ReadByte(); } public override void WriteByte(byte value) { source.WriteByte(value); } public override void Flush() { source.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return checked(source.Seek(offset + ((origin == SeekOrigin.Begin) ? sourceOffset : 0), origin) - sourceOffset); } public override void SetLength(long value) { source.SetLength(checked(value + sourceOffset)); } public override void Close() { source.Close(); } } [SuppressUnmanagedCodeSecurity] internal static class SafeNativeMethods { [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DosDateTimeToFileTime(short wFatDate, short wFatTime, out long fileTime); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FileTimeToDosDateTime(ref long fileTime, out short wFatDate, out short wFatTime); } }