Decompiled source of Gamer ModPack v1.0.2
patchers/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll
Decompiled a year 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 a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.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 a year 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(); } } } }
plugins/backrooms/Backrooms.dll
Decompiled a year agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using BepInEx; using BepInEx.Configuration; using DunGen.Graph; using GameNetcodeStuff; using HarmonyLib; using Unity.AI.Navigation; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); } } [RequireComponent(typeof(SphereCollider))] public class KillBox : MonoBehaviour { private void OnTriggerEnter(Collider other) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>(); if ((Object)(object)component != (Object)null) { component.KillPlayer(Vector3.zero, true, (CauseOfDeath)0, 0); } } } public class LightFlickerEffect : MonoBehaviour { [Tooltip("External light to flicker; you can leave this null if you attach script to a light")] public Light light; [Tooltip("Minimum random light intensity")] public float minIntensity; [Tooltip("Maximum random light intensity")] public float maxIntensity = 1f; [Tooltip("How much to smooth out the randomness; lower values = sparks, higher = lantern")] [Range(1f, 50f)] public int smoothing = 5; private Queue<float> smoothQueue; private float lastSum; public void Reset() { smoothQueue.Clear(); lastSum = 0f; } private void Start() { smoothQueue = new Queue<float>(smoothing); if ((Object)(object)light == (Object)null) { light = ((Component)this).GetComponent<Light>(); } } private void Update() { if (!((Object)(object)light == (Object)null)) { while (smoothQueue.Count >= smoothing) { lastSum -= smoothQueue.Dequeue(); } float num = Random.Range(minIntensity, maxIntensity); smoothQueue.Enqueue(num); lastSum += num; light.intensity = lastSum / (float)smoothQueue.Count; } } } public class LookAtPlayer : MonoBehaviour { private void Update() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) ((Component)this).gameObject.transform.LookAt(((Component)GameNetworkManager.Instance.localPlayerController).transform.position + Vector3.up); } } public class SpawnPosition : MonoBehaviour { private void Start() { } private void Update() { } } [CompilerGenerated] [EditorBrowsable(EditorBrowsableState.Never)] [GeneratedCode("Unity.MonoScriptGenerator.MonoScriptInfoGenerator", null)] internal class UnitySourceGeneratedAssemblyMonoScriptTypes_v1 { private struct MonoScriptData { public byte[] FilePathsData; public byte[] TypesData; public int TotalTypes; public int TotalFiles; public bool IsEditorOnly; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static MonoScriptData Get() { MonoScriptData result = default(MonoScriptData); result.FilePathsData = new byte[506] { 0, 0, 0, 1, 0, 0, 0, 42, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 65, 114, 101, 89, 111, 117, 87, 97, 116, 99, 104, 101, 100, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 38, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 33, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 69, 120, 105, 116, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 33, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 72, 111, 111, 107, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 36, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 75, 105, 108, 108, 66, 111, 120, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 47, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 76, 105, 103, 104, 116, 70, 108, 105, 99, 107, 101, 114, 69, 102, 102, 101, 99, 116, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 35, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 76, 111, 97, 100, 101, 114, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 41, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 76, 111, 111, 107, 65, 116, 80, 108, 97, 121, 101, 114, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 36, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 83, 107, 105, 98, 105, 100, 105, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 35, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 83, 109, 105, 108, 101, 114, 46, 99, 115, 0, 0, 0, 1, 0, 0, 0, 42, 92, 65, 115, 115, 101, 116, 115, 92, 66, 97, 99, 107, 114, 111, 111, 109, 115, 92, 83, 99, 114, 105, 112, 116, 115, 92, 83, 112, 97, 119, 110, 80, 111, 115, 105, 116, 105, 111, 110, 46, 99, 115 }; result.TypesData = new byte[233] { 0, 0, 0, 0, 25, 66, 97, 99, 107, 114, 111, 111, 109, 115, 124, 66, 97, 99, 107, 114, 111, 111, 109, 115, 72, 101, 108, 112, 101, 114, 0, 0, 0, 0, 19, 66, 97, 99, 107, 114, 111, 111, 109, 115, 124, 66, 97, 99, 107, 114, 111, 111, 109, 115, 0, 0, 0, 0, 14, 66, 97, 99, 107, 114, 111, 111, 109, 115, 124, 69, 120, 105, 116, 0, 0, 0, 0, 14, 66, 97, 99, 107, 114, 111, 111, 109, 115, 124, 72, 111, 111, 107, 0, 0, 0, 0, 8, 124, 75, 105, 108, 108, 66, 111, 120, 0, 0, 0, 0, 19, 124, 76, 105, 103, 104, 116, 70, 108, 105, 99, 107, 101, 114, 69, 102, 102, 101, 99, 116, 0, 0, 0, 0, 16, 66, 97, 99, 107, 114, 111, 111, 109, 115, 124, 76, 111, 97, 100, 101, 114, 0, 0, 0, 0, 13, 124, 76, 111, 111, 107, 65, 116, 80, 108, 97, 121, 101, 114, 0, 0, 0, 0, 20, 66, 97, 99, 107, 114, 111, 111, 109, 115, 124, 83, 111, 117, 110, 100, 80, 97, 116, 99, 104, 0, 0, 0, 0, 16, 66, 97, 99, 107, 114, 111, 111, 109, 115, 124, 83, 109, 105, 108, 101, 114, 0, 0, 0, 0, 14, 124, 83, 112, 97, 119, 110, 80, 111, 115, 105, 116, 105, 111, 110 }; result.TotalFiles = 11; result.TotalTypes = 11; result.IsEditorOnly = false; return result; } } namespace Backrooms; public class BackroomsHelper : MonoBehaviour { public bool HasBeenInTheBackrooms; private void Start() { } private void Update() { } } public class Backrooms : NetworkBehaviour { public static Backrooms Instance; public GameObject Floor; public GameObject Wall; public GameObject Ceiling; public GameObject LightlessCeiling; public GameObject Pillar; public GameObject Room; public static float Offset = -500f; private int Width = 30; private int Height = 30; public List<Vector2> PossibleSpawnPoint; public List<PlayerControllerB> playerInBackrooms; public NetworkVariable<float> SharedOdds = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private float initialValue; public DungeonFlow Flow; public GameObject Child; public override void OnNetworkSpawn() { if (((NetworkBehaviour)this).IsServer) { initialValue = Loader.TeleportationOdds.Value; SharedOdds.Value = initialValue; ((NetworkBehaviour)this).NetworkManager.OnClientConnectedCallback += NetworkManager_OnClientConnectedCallback; return; } if (SharedOdds.Value != initialValue) { Debug.LogWarning((object)($"NetworkVariable was {SharedOdds.Value} upon being spawned" + $" when it should have been {initialValue}")); } else { Debug.Log((object)$"NetworkVariable is {SharedOdds.Value} when spawned."); } NetworkVariable<float> sharedOdds = SharedOdds; sharedOdds.OnValueChanged = (OnValueChangedDelegate<float>)(object)Delegate.Combine((Delegate?)(object)sharedOdds.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<float>(OnSomeValueChanged)); } private void NetworkManager_OnClientConnectedCallback(ulong obj) { StartChangingNetworkVariable(); } private void OnSomeValueChanged(float previous, float current) { Debug.Log((object)$"Detected NetworkVariable Change: Previous: {previous} | Current: {current}"); } private void StartChangingNetworkVariable() { ((NetworkBehaviour)this).NetworkManager.OnClientConnectedCallback -= NetworkManager_OnClientConnectedCallback; } private void Awake() { PossibleSpawnPoint = new List<Vector2>(); playerInBackrooms = new List<PlayerControllerB>(); } private void Start() { if ((Object)(object)Instance == (Object)null) { Instance = this; } } private IEnumerator Teleport() { yield return (object)new WaitForSeconds(10f); for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (StartOfRound.Instance.allPlayerScripts[i].isPlayerControlled) { TeleportToBackroomsClientRpc(i); } } } public void ServerGenerate() { int seed = Random.Range(0, 1000000); GenerateClientRpc(seed); } public void ServerClean() { Smiler[] array = Object.FindObjectsOfType<Smiler>(); for (int i = 0; i < array.Length; i++) { ((Component)array[i]).GetComponent<NetworkObject>().Despawn(true); } playerInBackrooms.Clear(); CleanBackroomsClientRpc(); } [ClientRpc] public void CleanBackroomsClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_00cf: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2180494496u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2180494496u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } foreach (Transform item in ((Component)this).transform) { Object.Destroy((Object)(object)((Component)item).gameObject); } PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; for (int i = 0; i < allPlayerScripts.Length; i++) { ((Component)allPlayerScripts[i]).GetComponent<BackroomsHelper>().HasBeenInTheBackrooms = false; } } [ServerRpc(RequireOwnership = false)] public void TeleportToBackroomsServerRpc(int client) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2541916904u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, client); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2541916904u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { TeleportToBackroomsClientRpc(client); } } } [ClientRpc] public void TeleportToBackroomsClientRpc(int client) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3078584200u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, client); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3078584200u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { PlayerControllerB val3 = StartOfRound.Instance.allPlayerScripts[client]; Random.InitState(client); Vector2 val4 = PossibleSpawnPoint[Random.Range(0, PossibleSpawnPoint.Count)]; val3.TeleportPlayer(new Vector3(val4.x, Offset, val4.y), false, 0f, false, true); val3.isInsideFactory = true; val3.ResetFallGravity(); ((Component)val3).GetComponent<BackroomsHelper>().HasBeenInTheBackrooms = true; if (((NetworkBehaviour)this).IsServer) { playerInBackrooms.Add(val3); } } } [ClientRpc] public void TeleportOutOfBackroomsClientRpc(int client) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1623403188u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, client); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1623403188u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { PlayerControllerB obj = StartOfRound.Instance.allPlayerScripts[client]; obj.TeleportPlayer(StartOfRound.Instance.playerSpawnPositions[0].position, false, 0f, false, true); obj.isInsideFactory = false; } } } [ClientRpc] public void GenerateClientRpc(int seed) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: 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_0134: 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_023f: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: 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_016a: 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_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_0373: Unknown result type (might be due to invalid IL or missing references) //IL_0387: Unknown result type (might be due to invalid IL or missing references) //IL_0545: Unknown result type (might be due to invalid IL or missing references) //IL_054a: Unknown result type (might be due to invalid IL or missing references) //IL_054d: Unknown result type (might be due to invalid IL or missing references) //IL_0559: Unknown result type (might be due to invalid IL or missing references) //IL_0560: Unknown result type (might be due to invalid IL or missing references) //IL_0565: Unknown result type (might be due to invalid IL or missing references) //IL_04d1: Unknown result type (might be due to invalid IL or missing references) //IL_049a: Unknown result type (might be due to invalid IL or missing references) //IL_04ae: 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_046c: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Unknown result type (might be due to invalid IL or missing references) //IL_042b: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(890432861u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, seed); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 890432861u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } PossibleSpawnPoint.Clear(); playerInBackrooms.Clear(); Random random = new Random(seed); Debug.Log((object)"Generate floor and ceiling"); for (int i = -Width / 2; i < Width / 2; i++) { for (int j = -Height / 2; j < Height / 2; j++) { Object.Instantiate<GameObject>(Floor, new Vector3((float)(i * 6), Offset, (float)(j * 6)), Quaternion.Euler(-90f, 0f, 0f), ((Component)this).transform); if (random.Next(100) < 85) { Object.Instantiate<GameObject>(LightlessCeiling, new Vector3((float)(i * 6), Offset + 5f, (float)(j * 6)), Quaternion.Euler(-90f, 0f, 0f), ((Component)this).transform); } else { Object.Instantiate<GameObject>(Ceiling, new Vector3((float)(i * 6), Offset + 5f, (float)(j * 6)), Quaternion.Euler(-90f, 0f, 0f), ((Component)this).transform); } } } Debug.Log((object)"Generate walls"); for (int k = -Width / 2; k < Width / 2; k++) { Object.Instantiate<GameObject>(Wall, new Vector3((float)(-Width / 2 * 6 - 3), Offset, (float)(k * 6)), Quaternion.Euler(-90f, 0f, 0f), ((Component)this).transform); if (k != 0) { Object.Instantiate<GameObject>(Wall, new Vector3((float)(Width / 2 * 6 - 3), Offset, (float)(k * 6)), Quaternion.Euler(-90f, 0f, 0f), ((Component)this).transform); continue; } Debug.Log((object)"Generate room"); Object.Instantiate<GameObject>(Room, new Vector3((float)(Width / 2 * 6 - 3), Offset, (float)(k * 6)), Quaternion.Euler(0f, 90f, 0f), ((Component)this).transform); } Debug.Log((object)"Generate walls 2"); for (int l = -Width / 2; l < Width / 2; l++) { Object.Instantiate<GameObject>(Wall, new Vector3((float)(l * 6), Offset, (float)(-Height / 2 * 6 - 3)), Quaternion.Euler(-90f, 90f, 0f), ((Component)this).transform); Object.Instantiate<GameObject>(Wall, new Vector3((float)(l * 6), Offset, (float)(Height / 2 * 6 - 3)), Quaternion.Euler(-90f, 90f, 0f), ((Component)this).transform); } Debug.Log((object)"Generate inside 2"); for (int m = -Width / 2; m < Width / 2; m++) { for (int n = -Height / 2; n < Height / 2; n++) { if (m == 0 && n == 0) { continue; } int num = random.Next(20); if (num < 15) { if (random.Next(10) < 5) { Object.Instantiate<GameObject>(Wall, new Vector3((float)(m * 6 - 3), Offset, (float)(n * 6)), Quaternion.Euler(-90f, 0f, 0f), ((Component)this).transform); } else { Object.Instantiate<GameObject>(Wall, new Vector3((float)(m * 6), Offset, (float)(n * 6 - 3)), Quaternion.Euler(-90f, 90f, 0f), ((Component)this).transform); } } else if (num == 16) { Object.Instantiate<GameObject>(Pillar, new Vector3((float)(m * 6), Offset, (float)(n * 6)), Quaternion.Euler(-90f, 0f, 0f), ((Component)this).transform); } else { PossibleSpawnPoint.Add(new Vector2((float)(m * 6), (float)(n * 6))); } } } if (((NetworkBehaviour)this).IsServer) { ((Component)this).GetComponent<NavMeshSurface>().BuildNavMesh(); GameObject val3 = Loader.AssetBundle.LoadAsset<GameObject>("assets/backrooms/smile.prefab"); for (int num2 = 0; num2 < Loader.NumberOfSmilers.Value; num2++) { Vector2 val4 = PossibleSpawnPoint[Random.Range(0, PossibleSpawnPoint.Count)]; Object.Instantiate<GameObject>(val3, new Vector3(val4.x, Offset, val4.y), Quaternion.identity, ((Component)this).transform).GetComponent<NetworkObject>().Spawn(false); } } } [ServerRpc(RequireOwnership = false)] public void TeleportOutOfBackroomsServerRpc(ulong clientId) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3409688981u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, clientId); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3409688981u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { TeleportOutOfBackroomsClientRpc((int)clientId); } } } protected override void __initializeVariables() { if (SharedOdds == null) { throw new Exception("Backrooms.SharedOdds cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SharedOdds).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SharedOdds, "SharedOdds"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SharedOdds); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_Backrooms() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(2180494496u, new RpcReceiveHandler(__rpc_handler_2180494496)); NetworkManager.__rpc_func_table.Add(2541916904u, new RpcReceiveHandler(__rpc_handler_2541916904)); NetworkManager.__rpc_func_table.Add(3078584200u, new RpcReceiveHandler(__rpc_handler_3078584200)); NetworkManager.__rpc_func_table.Add(1623403188u, new RpcReceiveHandler(__rpc_handler_1623403188)); NetworkManager.__rpc_func_table.Add(890432861u, new RpcReceiveHandler(__rpc_handler_890432861)); NetworkManager.__rpc_func_table.Add(3409688981u, new RpcReceiveHandler(__rpc_handler_3409688981)); } private static void __rpc_handler_2180494496(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)2; ((Backrooms)(object)target).CleanBackroomsClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2541916904(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int client = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref client); target.__rpc_exec_stage = (__RpcExecStage)1; ((Backrooms)(object)target).TeleportToBackroomsServerRpc(client); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3078584200(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int client = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref client); target.__rpc_exec_stage = (__RpcExecStage)2; ((Backrooms)(object)target).TeleportToBackroomsClientRpc(client); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1623403188(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int client = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref client); target.__rpc_exec_stage = (__RpcExecStage)2; ((Backrooms)(object)target).TeleportOutOfBackroomsClientRpc(client); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_890432861(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int seed = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref seed); target.__rpc_exec_stage = (__RpcExecStage)2; ((Backrooms)(object)target).GenerateClientRpc(seed); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3409688981(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ulong clientId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref clientId); target.__rpc_exec_stage = (__RpcExecStage)1; ((Backrooms)(object)target).TeleportOutOfBackroomsServerRpc(clientId); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "Backrooms"; } } public class Exit : MonoBehaviour { private void Start() { } private IEnumerator Teleport(ulong playerClientId) { StartOfRound.Instance.allPlayerScripts[playerClientId].beamOutParticle.Play(); yield return (object)new WaitForSeconds(3f); Backrooms.Instance.TeleportOutOfBackroomsServerRpc(playerClientId); } private void OnTriggerEnter(Collider other) { PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>(); if ((Object)(object)component != (Object)null) { ((MonoBehaviour)this).StartCoroutine(Teleport(component.playerClientId)); Backrooms.Instance.TeleportOutOfBackroomsServerRpc(component.playerClientId); } } } public static class Hook { [HarmonyPatch(typeof(KillLocalPlayer), "KillPlayer")] [HarmonyPrefix] private static bool BeforeKilling(PlayerControllerB playerWhoTriggered) { if (playerWhoTriggered.isPlayerDead || !playerWhoTriggered.AllowPlayerDeath()) { return true; } if (((Component)playerWhoTriggered).GetComponent<BackroomsHelper>().HasBeenInTheBackrooms) { return true; } Debug.Log((object)$"Killzone {Backrooms.Instance.SharedOdds.Value}"); if ((float)Random.Range(0, 100) < Backrooms.Instance.SharedOdds.Value) { Backrooms.Instance.TeleportToBackroomsServerRpc((int)playerWhoTriggered.playerClientId); return false; } return true; } [HarmonyPatch(typeof(PlayerControllerB), "DamagePlayer")] [HarmonyPrefix] private static bool BeforeDamage(PlayerControllerB __instance) { if (__instance.isPlayerDead || !__instance.AllowPlayerDeath()) { return true; } if (((Component)__instance).GetComponent<BackroomsHelper>().HasBeenInTheBackrooms) { return true; } Debug.Log((object)$"Damage taken {Backrooms.Instance.SharedOdds.Value}"); if ((float)Random.Range(0, 100) < Backrooms.Instance.SharedOdds.Value) { Backrooms.Instance.TeleportToBackroomsServerRpc((int)__instance.playerClientId); return false; } return true; } [HarmonyPatch(typeof(PlayerControllerB), "Start")] [HarmonyPostfix] private static void AddComponents(PlayerControllerB __instance) { ((Component)__instance).gameObject.AddComponent<BackroomsHelper>(); } [HarmonyPatch(typeof(RoundManager), "Start")] [HarmonyPostfix] private static void SpawnBackrooms(RoundManager __instance) { //IL_0031: 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) if (((NetworkBehaviour)__instance).IsServer) { Debug.Log((object)"Spawning backrooms"); Object.Instantiate<GameObject>(Loader.AssetBundle.LoadAsset<GameObject>("assets/backrooms/backrooms.prefab"), new Vector3(0f, Backrooms.Offset, 0f), Quaternion.identity).GetComponent<NetworkObject>().Spawn(false); } } [HarmonyPatch(typeof(RoundManager), "UnloadSceneObjectsEarly")] [HarmonyPostfix] public static void DeleteBackrooms(RoundManager __instance) { if (((NetworkBehaviour)__instance).IsServer) { Backrooms.Instance.ServerClean(); } } [HarmonyPatch(typeof(RoundManager), "LoadNewLevel")] [HarmonyPrefix] public static void GenerateBackrooms(RoundManager __instance) { if (((NetworkBehaviour)__instance).IsServer) { Backrooms.Instance.ServerGenerate(); } } [HarmonyPatch(typeof(StartOfRound), "WritePlayerNotes")] [HarmonyPostfix] public static void BackroomsPlayerNote(StartOfRound __instance) { for (int i = 0; i < __instance.gameStats.allPlayerStats.Length; i++) { if (__instance.gameStats.allPlayerStats[i].isActivePlayer && ((Component)__instance.allPlayerScripts[i]).GetComponent<BackroomsHelper>().HasBeenInTheBackrooms) { if (__instance.allPlayerScripts[i].isPlayerDead) { __instance.gameStats.allPlayerStats[i].playerNotes.Add("Should have been more careful in the Backrooms."); } else { __instance.gameStats.allPlayerStats[i].playerNotes.Add("Had a blast in the Backrooms."); } } } } [HarmonyPatch(typeof(MenuManager), "Start")] [HarmonyPostfix] public static void NetworkManagerPatch(MenuManager __instance) { if (!NetworkManager.Singleton.NetworkConfig.Prefabs.Prefabs.Select((NetworkPrefab pref) => ((Object)pref.Prefab).name).Contains("backrooms")) { Debug.Log((object)"Load prefabs to Network Manager"); string[] array = new string[2] { "assets/backrooms/backrooms.prefab", "assets/backrooms/smile.prefab" }; foreach (string text in array) { GameObject val = Loader.AssetBundle.LoadAsset<GameObject>(text); NetworkManager.Singleton.AddNetworkPrefab(val); } } } } [BepInPlugin("Neekhaulas.Backrooms", "Backrooms", "0.1.3")] public class Loader : BaseUnityPlugin { public static AssetBundle AssetBundle { get; private set; } public static ConfigEntry<float> TeleportationOdds { get; private set; } public static ConfigEntry<int> NumberOfSmilers { get; private set; } private void Awake() { TeleportationOdds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Teleportation odds", 3f, "Odds to be teleported (in %) - This settings has to be changed by the host"); NumberOfSmilers = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Number of smilers", 1, "Number of smilers to spawn in the Backrooms - This settings has to be changed by the host"); AssetBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "backrooms")); Harmony.CreateAndPatchAll(typeof(Hook), (string)null); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Backrooms is loaded!"); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); for (int i = 0; i < types.Length; i++) { MethodInfo[] methods = types[i].GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0) { methodInfo.Invoke(null, null); } } } } } public class SoundPatch : MonoBehaviour { private void Start() { ((Component)this).gameObject.AddComponent<OccludeAudio>(); ((Component)this).GetComponent<AudioSource>().Play(); } } public class Smiler : NetworkBehaviour { private NavMeshAgent NavMeshAgent; private PlayerControllerB Target; private void Start() { NavMeshAgent = ((Component)this).GetComponent<NavMeshAgent>(); } private void Update() { //IL_0079: 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_00e0: 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_00ac: Unknown result type (might be due to invalid IL or missing references) //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_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: 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) if (!((NetworkBehaviour)this).IsServer) { return; } if ((Object)(object)Target != (Object)null && Target.isPlayerDead) { Target = null; NavMeshAgent.speed = 2f; } if (!NavMeshAgent.pathPending && NavMeshAgent.remainingDistance <= NavMeshAgent.stoppingDistance) { if (NavMeshAgent.hasPath) { Vector3 velocity = NavMeshAgent.velocity; if (((Vector3)(ref velocity)).sqrMagnitude != 0f) { goto IL_00f0; } } if ((Object)(object)Target != (Object)null) { NavMeshAgent.SetDestination(((Component)Target).transform.position); } else { int index = Random.Range(0, Backrooms.Instance.PossibleSpawnPoint.Count); NavMeshAgent.SetDestination(Vector2.op_Implicit(Backrooms.Instance.PossibleSpawnPoint[index])); } } goto IL_00f0; IL_00f0: for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i]; if (val.isPlayerControlled && !val.isPlayerDead) { if (val.HasLineOfSightToPosition(((Component)this).transform.position + Vector3.up, 45f, 15, -1f)) { Target = val; NavMeshAgent.SetDestination(((Component)val).transform.position); NavMeshAgent.speed = 7f; break; } bool flag = false; if ((Object)(object)val.currentlyHeldObjectServer != (Object)null && ((object)val.currentlyHeldObjectServer).GetType() == typeof(FlashlightItem) && val.currentlyHeldObjectServer.isBeingUsed) { flag = true; } if ((Object)(object)val.pocketedFlashlight != (Object)null && ((object)val.pocketedFlashlight).GetType() == typeof(FlashlightItem) && val.pocketedFlashlight.isBeingUsed) { flag = true; } if (flag && val.HasLineOfSightToPosition(((Component)this).transform.position + Vector3.up, 45f, 100, -1f)) { Target = val; NavMeshAgent.SetDestination(((Component)val).transform.position); NavMeshAgent.speed = 7f; } } } } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } protected internal override string __getTypeName() { return "Smiler"; } }
plugins/BetterShotgunShells.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using LethalLib.Modules; 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: AssemblyTitle("BuyableShells")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BuyableShells")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("f1098099-7d96-4f78-bd10-8cf743e1f445")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace BuyableShells; [BepInPlugin("SalakStudios.BetterShotgunShells", "BetterShotgunShells", "1.0.1")] public class Plugin : BaseUnityPlugin { private const string modGUID = "SalakStudios.BetterShotgunShells"; private const string modName = "BetterShotgunShells"; private const string modVersion = "1.0.1"; private readonly Harmony harmony = new Harmony("SalakStudios.BetterShotgunShells"); internal static Plugin Instance; public static ManualLogSource mls; public bool added; public static ConfigEntry<int> ShellPrice; public static ConfigEntry<int> ItemRarity; public List<Item> AllItems => Resources.FindObjectsOfTypeAll<Item>().Concat(Object.FindObjectsByType<Item>((FindObjectsInactive)1, (FindObjectsSortMode)1)).ToList(); public Item ShotgunShell => ((IEnumerable<Item>)AllItems).FirstOrDefault((Func<Item, bool>)((Item item) => ((Object)item).name == "GunAmmo")); private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(typeof(Plugin)); mls = Logger.CreateLogSource("SalakStudios.BetterShotgunShells"); mls.LogInfo((object)"BetterShotgunShells Enabled"); SceneManager.sceneLoaded += OnSceneLoaded; ShellPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Settings", "Shell Price", 150, "How many credits the shotgun shell costs"); ItemRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Settings", "Shell Rarity", 3, "How rare the shell is to find on moons (Lower = Rarer, Higher = More Common)"); } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (!added && ((Scene)(ref scene)).name == "MainMenu") { added = true; ShotgunShell.itemName = "Shells"; ShotgunShell.creditsWorth = 0; Items.RegisterShopItem(ShotgunShell, ShellPrice.Value); Items.RegisterScrap(ShotgunShell, ItemRarity.Value, (LevelTypes)128); Items.RegisterScrap(ShotgunShell, ItemRarity.Value, (LevelTypes)256); Items.RegisterScrap(ShotgunShell, ItemRarity.Value, (LevelTypes)512); } } }
plugins/BetterStamina.dll
Decompiled a year agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BetterStamina.Config; using GameNetcodeStuff; using HarmonyLib; using Unity.Collections; 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: AssemblyTitle("BetterStamina")] [assembly: AssemblyDescription("Mod made by flipf17")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BetterStamina")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("1c42022e-b386-4342-baf0-67de1b7529e2")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace BetterStamina { [BepInPlugin("FlipMods.BetterStamina", "BetterStamina", "1.2.1")] public class Plugin : BaseUnityPlugin { private Harmony _harmony; public static Plugin instance; private void Awake() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown instance = this; ConfigSettings.BindConfigSettings(); _harmony = new Harmony("BetterStamina"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"BetterStamina loaded"); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } public static void LogError(string message) { ((BaseUnityPlugin)instance).Logger.LogError((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.BetterStamina"; public const string PLUGIN_NAME = "BetterStamina"; public const string PLUGIN_VERSION = "1.2.1"; } } namespace BetterStamina.Patches { [HarmonyPatch] internal class BetterStaminaPatcher { private static float currentCarryWeight; private static float reducedWeight; private static float currentSprintMeter; [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPrefix] public static void UpdateStaminaPrefix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { currentSprintMeter = __instance.sprintMeter; } } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] public static void UpdateStaminaPostfix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { float num = __instance.sprintMeter - currentSprintMeter; if (num < 0f) { __instance.sprintMeter = Mathf.Max(currentSprintMeter + num * ConfigSync.instance.staminaConsumptionMultiplier, 0f); } else if (num > 0f) { __instance.sprintMeter = Mathf.Min(currentSprintMeter + num * ConfigSync.instance.staminaRegenMultiplier, 1f); } } } [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] [HarmonyPrefix] public static void LateUpdatePrefix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { currentSprintMeter = __instance.sprintMeter; } } [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] [HarmonyPostfix] public static void LateUpdateStaminaPostfix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { float num = __instance.sprintMeter - currentSprintMeter; if (num < 0f) { __instance.sprintMeter = Mathf.Max(currentSprintMeter + num * ConfigSync.instance.staminaConsumptionMultiplier, 0f); } else if (num > 0f) { __instance.sprintMeter = Mathf.Min(currentSprintMeter + num * ConfigSync.instance.staminaRegenMultiplier, 1f); } } } [HarmonyPatch(typeof(PlayerControllerB), "Jump_performed")] [HarmonyPrefix] public static void JumpPerformedPrefix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { currentSprintMeter = __instance.sprintMeter; } } [HarmonyPatch(typeof(PlayerControllerB), "Jump_performed")] [HarmonyPostfix] public static void JumpPerformedPostfix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { float num = __instance.sprintMeter - currentSprintMeter; if (num < 0f) { __instance.sprintMeter = Mathf.Max(new float[1] { currentSprintMeter + num * ConfigSync.instance.jumpStaminaConsumptionMultiplier }); } } } } } namespace BetterStamina.Config { [Serializable] public static class ConfigSettings { public static ConfigEntry<float> staminaConsumptionMultiplierConfig; public static ConfigEntry<float> staminaRegenMultiplierConfig; public static ConfigEntry<float> jumpStaminaConsumptionMultiplierConfig; public static ConfigEntry<float> carryWeightPenaltyMultiplierConfig; public static ConfigEntry<float> movementSpeedMultiplierConfig; public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); staminaConsumptionMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "StaminaConsumptionMultiplier", 0.75f, "Multiplier for how much stamina drains while sprinting."); staminaRegenMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "StaminaRegenMultiplier", 1.5f, "Multiplier for how fast your stamina regens."); jumpStaminaConsumptionMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "JumpStaminaConsumptionMultiplier", 0.75f, "Multiplier for how much stamina jumping consumes."); carryWeightPenaltyMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "CarryWeightPenaltyMultiplier", 0.5f, "Multiplier for how much your speed/stamina consumption are affected by weight."); movementSpeedMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "MovementSpeedMultiplier", 1f, "Player movement speed multiplier."); ConfigSync.BuildDefaultConfig(); } } [Serializable] [HarmonyPatch] public class ConfigSync { public static ConfigSync defaultConfig; public static ConfigSync instance; public static PlayerControllerB localPlayerController; public static bool isSynced = false; private static float defaultMovementSpeed = 4.6f; public float staminaConsumptionMultiplier; public float staminaRegenMultiplier; public float jumpStaminaConsumptionMultiplier; public float carryWeightPenaltyMultiplier; public float movementSpeedMultiplier; public static void BuildDefaultConfig() { if (defaultConfig == null) { defaultConfig = new ConfigSync(); defaultConfig.staminaConsumptionMultiplier = ConfigSettings.staminaConsumptionMultiplierConfig.Value; defaultConfig.staminaRegenMultiplier = ConfigSettings.staminaRegenMultiplierConfig.Value; defaultConfig.jumpStaminaConsumptionMultiplier = ConfigSettings.jumpStaminaConsumptionMultiplierConfig.Value; defaultConfig.carryWeightPenaltyMultiplier = ConfigSettings.carryWeightPenaltyMultiplierConfig.Value; defaultConfig.movementSpeedMultiplier = ConfigSettings.movementSpeedMultiplierConfig.Value; instance = defaultConfig; } } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void InitializeLocalPlayer(PlayerControllerB __instance) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown localPlayerController = __instance; if (NetworkManager.Singleton.IsServer) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("BetterStaminaOnRequestConfigSync", new HandleNamedMessageDelegate(OnReceiveConfigSyncRequest)); OnLocalClientConfigSync(); } else { isSynced = false; NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("BetterStaminaOnReceiveConfigSync", new HandleNamedMessageDelegate(OnReceiveConfigSync)); RequestConfigSync(); } } public static void RequestConfigSync() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { Plugin.Log("Sending config sync request to server."); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BetterStaminaOnRequestConfigSync", 0uL, val, (NetworkDelivery)3); } else { Plugin.LogError("Failed to send config sync request."); } } public static void OnReceiveConfigSyncRequest(ulong clientId, FastBufferReader reader) { //IL_0053: 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_007c: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsServer) { Plugin.Log("Receiving config sync request from client with id: " + clientId + ". Sending config sync to client."); byte[] array = SerializeConfigToByteArray(instance); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(array.Length + 4, (Allocator)2, -1); int num = array.Length; ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BetterStaminaOnReceiveConfigSync", clientId, val, (NetworkDelivery)3); } } public static void OnReceiveConfigSync(ulong clientId, FastBufferReader reader) { //IL_0014: 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 (((FastBufferReader)(ref reader)).TryBeginRead(4)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); if (((FastBufferReader)(ref reader)).TryBeginRead(num)) { Plugin.Log("Receiving config sync from server."); byte[] data = new byte[num]; ((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0); instance = DeserializeFromByteArray(data); OnLocalClientConfigSync(); } else { Plugin.LogError("Error receiving sync from server."); } } else { Plugin.LogError("Error receiving bytes length."); } } public static void OnLocalClientConfigSync() { localPlayerController.movementSpeed = defaultMovementSpeed * instance.movementSpeedMultiplier; isSynced = true; } public static byte[] SerializeConfigToByteArray(ConfigSync config) { BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(); binaryFormatter.Serialize(memoryStream, config); return memoryStream.ToArray(); } public static ConfigSync DeserializeFromByteArray(byte[] data) { MemoryStream serializationStream = new MemoryStream(data); BinaryFormatter binaryFormatter = new BinaryFormatter(); return (ConfigSync)binaryFormatter.Deserialize(serializationStream); } } }
plugins/BiggerLobby.dll
Decompiled a year agousing System; using System.Collections; 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 System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BiggerLobby.Patches; using Dissonance.Audio.Playback; using GameNetcodeStuff; using HarmonyLib; using LC_API.BundleAPI; using LC_API.ServerAPI; using Microsoft.CodeAnalysis; using Steamworks; using Steamworks.Data; using TMPro; using Unity.Netcode; using UnityEngine; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BiggerLobby")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Increase the max players to 50 in Lethal Company")] [assembly: AssemblyFileVersion("2.5.0.0")] [assembly: AssemblyInformationalVersion("2.5.0")] [assembly: AssemblyProduct("BiggerLobby")] [assembly: AssemblyTitle("BiggerLobby")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.5.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 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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BiggerLobby { public static class Helper { public static T[] ResizeArray<T>(T[] oldArray, int newSize) { T[] array = new T[newSize]; oldArray.CopyTo(array, 0); return array; } public static void ResizeList<T>(this List<T> list, int size, T element = default(T)) { int count = list.Count; if (size < count) { list.RemoveRange(size, count - size); } else if (size > count) { if (size > list.Capacity) { list.Capacity = size; } list.AddRange(Enumerable.Repeat(element, size - count)); } } } [BepInPlugin("BiggerLobby", "BiggerLobby", "2.5.0")] public class Plugin : BaseUnityPlugin { public static bool oldhastime; public static int MaxPlayers = 16; public static bool instantiating; public static NetworkObject[] PlayerObjects = (NetworkObject[])(object)new NetworkObject[0]; public static Harmony _harmony; public static Harmony _harmony2; public static ConfigEntry<int>? _LoudnessMultiplier; public static bool Initialized = false; public static IDictionary<uint, NetworkObject> CustomNetObjects = new Dictionary<uint, NetworkObject>(); private void Awake() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Expected O, but got Unknown _LoudnessMultiplier = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Player loudness", 1, "Default player loudness"); _harmony = new Harmony("BiggerLobby"); _harmony2 = new Harmony("BiggerLobbyA"); _harmony.PatchAll(typeof(NonGamePatches)); _harmony.PatchAll(typeof(NonGamePatches.InternalPatches)); _harmony.PatchAll(typeof(NonGamePatches.InternalPatches2)); CustomNetObjects.Clear(); _harmony2.PatchAll(typeof(InternalPatch3)); _harmony2.PatchAll(typeof(ListSizeTranspilers)); _harmony2.PatchAll(typeof(PlayerObjects)); ((BaseUnityPlugin)this).Logger.LogInfo((object)"BiggerLobby loaded"); BundleLoader.OnLoadedAssets = (OnLoadedAssetsDelegate)Delegate.Combine((Delegate?)(object)BundleLoader.OnLoadedAssets, (Delegate?)new OnLoadedAssetsDelegate(OnLoaded)); } private void Start() { Initialize(); } private void OnDestroy() { Initialize(); } private void Initialize() { if (!Initialized) { Initialized = true; ModdedServer.SetServerModdedOnly(); } } private void OnLoaded() { Object.op_Implicit((Object)(object)BundleLoader.GetLoadedAsset<AudioMixer>("assets/diagetic.mixer")); } public static int GetPlayerCount() { return MaxPlayers; } public static int GetPlayerCountMinusOne() { return MaxPlayers - 1; } } public static class PluginInfo { public const string PLUGIN_GUID = "BiggerLobby"; public const string PLUGIN_NAME = "BiggerLobby"; public const string PLUGIN_VERSION = "2.5.0"; } } namespace BiggerLobby.Patches { [HarmonyPatch(typeof(HUDManager))] internal class InternalPatch3 { private static MethodInfo TargetMethod() { return typeof(HUDManager).GetMethod("AddChatMessage", BindingFlags.Instance | BindingFlags.NonPublic); } [HarmonyPrefix] private static void Prefix(HUDManager __instance, string chatMessage, string nameOfUserWhoTyped = "") { if (!(__instance.lastChatMessage == chatMessage)) { __instance.lastChatMessage = chatMessage; __instance.PingHUDElement(__instance.Chat, 4f, 1f, 0.2f); if (__instance.ChatMessageHistory.Count >= 4) { ((TMP_Text)__instance.chatText).text.Remove(0, __instance.ChatMessageHistory[0].Length); __instance.ChatMessageHistory.Remove(__instance.ChatMessageHistory[0]); } StringBuilder stringBuilder = new StringBuilder(chatMessage); for (int i = 1; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { stringBuilder.Replace("[playerNum" + i + "]", StartOfRound.Instance.allPlayerScripts[i].playerUsername); } stringBuilder.Replace("bizzlemip", "<color=#008282>bizzlemip</color>"); chatMessage = stringBuilder.ToString(); nameOfUserWhoTyped = nameOfUserWhoTyped.Replace("bizzlemip", "<color=#008282>bizzlemip</color>"); string item = ((!string.IsNullOrEmpty(nameOfUserWhoTyped)) ? ("<color=#FF0000>" + nameOfUserWhoTyped + "</color>: <color=#FFFF00>'" + chatMessage + "'</color>") : ("<color=#7069ff>" + chatMessage + "</color>")); __instance.ChatMessageHistory.Add(item); ((TMP_Text)__instance.chatText).text = ""; for (int j = 0; j < __instance.ChatMessageHistory.Count; j++) { TextMeshProUGUI chatText = __instance.chatText; ((TMP_Text)chatText).text = ((TMP_Text)chatText).text + "\n" + __instance.ChatMessageHistory[j]; } } } } [HarmonyPatch] public class ListSizeTranspilers { private static MethodInfo _playerCountMethod = AccessTools.Method(typeof(Plugin), "GetPlayerCount", (Type[])null, (Type[])null); private static MethodInfo _playerCountMinusOneMethod = AccessTools.Method(typeof(Plugin), "GetPlayerCountMinusOne", (Type[])null, (Type[])null); private static void CheckAndReplace(List<CodeInstruction> codes, int index) { if (codes[index].opcode == OpCodes.Ldc_I4_4) { Debug.Log((object)"ok gunna do it"); codes[index].opcode = OpCodes.Call; codes[index].operand = _playerCountMethod; Debug.Log((object)"ok gunna did it"); } } [HarmonyPatch(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[] { })] [HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")] [HarmonyPatch(typeof(CrawlerAI), "Start")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> SyncLevelsRpc(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Newarr) { Debug.Log((object)"newarr"); CheckAndReplace(list, i - 1); } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesServerRpc")] [HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")] [HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")] [HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")] [HarmonyPatch(typeof(SpringManAI), "DoAIInterval")] [HarmonyPatch(typeof(SpringManAI), "Update")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> SendNewPlayerValuesServerRpc(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Blt) { Debug.Log((object)"blt"); CheckAndReplace(list, i - 1); } } return list.AsEnumerable(); } [HarmonyPatch(typeof(StartOfRound), "EndOfGameClientRpc")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> EndOfGameClientRpc(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Brfalse && list[i - 1].opcode == OpCodes.Ldfld && list[i - 2].opcode == OpCodes.Ldfld && list[i - 3].opcode == OpCodes.Ldarg_0) { Debug.Log((object)list[i - 1].opcode); Debug.Log((object)list[i - 2].opcode); Debug.Log((object)list[i - 3].opcode); list[i - 1].opcode = OpCodes.Nop; list[i - 2].opcode = OpCodes.Nop; CheckAndReplace(list, i - 3); } } return list.AsEnumerable(); } [HarmonyPatch(typeof(QuickMenuManager), "ConfirmKickUserFromServer")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> ConfirmKickUserFromServer(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_I4_3) { list[i].opcode = OpCodes.Call; list[i].operand = _playerCountMinusOneMethod; Debug.Log((object)"Kick Fix Applied"); break; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesServerRpc")] [HarmonyPatch(typeof(StartOfRound), "OnClientConnect")] [HarmonyPatch(typeof(PlayerControllerB), "SpectateNextPlayer")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> SyncShipUnlockablesServerRpc(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_I4_4) { list[i].opcode = OpCodes.Call; list[i].operand = _playerCountMethod; } } return list.AsEnumerable(); } } [HarmonyPatch] public class NonGamePatches { [HarmonyPatch(typeof(GameNetworkManager))] internal class InternalPatches { private static MethodInfo TargetMethod() { return typeof(GameNetworkManager).GetMethod("ConnectionApproval", BindingFlags.Instance | BindingFlags.NonPublic); } [HarmonyPrefix] private static bool PostFix(GameNetworkManager __instance, ConnectionApprovalRequest request, ConnectionApprovalResponse response) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) Debug.Log((object)("Connection approval callback! Game version of client request: " + Encoding.ASCII.GetString(request.Payload).ToString())); Debug.Log((object)$"Joining client id: {request.ClientNetworkId}; Local/host client id: {NetworkManager.Singleton.LocalClientId}"); if (request.ClientNetworkId == NetworkManager.Singleton.LocalClientId) { Debug.Log((object)"Stopped connection approval callback, as the client in question was the host!"); return false; } bool flag = !__instance.disallowConnection; if (flag) { string @string = Encoding.ASCII.GetString(request.Payload); string[] array = @string.Split(","); if (string.IsNullOrEmpty(@string)) { response.Reason = "Unknown; please verify your game files."; flag = false; } else if (__instance.gameHasStarted) { response.Reason = "Game has already started!"; flag = false; } else if (__instance.gameVersionNum.ToString() != array[0]) { response.Reason = $"Game version mismatch! Their version: {__instance.gameVersionNum}. Your version: {array[0]}"; flag = false; } else if (!__instance.disableSteam && ((Object)(object)StartOfRound.Instance == (Object)null || array.Length < 2 || StartOfRound.Instance.KickedClientIds.Contains((ulong)Convert.ToInt64(array[1])))) { response.Reason = "You cannot rejoin after being kicked."; flag = false; } else if (!@string.Contains("BiggerLobbyVersion2.5.0")) { response.Reason = "You need to have <color=#008282>BiggerLobby V2.5.0</color> to join this server!"; flag = false; } } else { response.Reason = "The host was not accepting connections."; } Debug.Log((object)$"Approved connection?: {flag}. Connected players #: {__instance.connectedPlayers}"); Debug.Log((object)("Disapproval reason: " + response.Reason)); response.CreatePlayerObject = false; response.Approved = flag; response.Pending = false; return false; } } [HarmonyPatch(typeof(GameNetworkManager))] internal class InternalPatches2 { private static MethodInfo TargetMethod() { return typeof(GameNetworkManager).GetMethod("SteamMatchmaking_OnLobbyCreated", BindingFlags.Instance | BindingFlags.NonPublic); } [HarmonyPostfix] private static void PostFix(GameNetworkManager __instance, Result result, Lobby lobby) { ((Lobby)(ref lobby)).SetData("name", "[BiggerLobby]" + ((Lobby)(ref lobby)).GetData("name")); } } private static PropertyInfo _playbackVolumeProperty = typeof(VoicePlayback).GetInterface("IVoicePlaybackInternal").GetProperty("PlaybackVolume"); private static FieldInfo _lobbyListField = AccessTools.Field(typeof(SteamLobbyManager), "currentLobbyList"); [HarmonyPatch(typeof(StartOfRound), "UpdatePlayerVoiceEffects")] [HarmonyPrefix] public static void UpdatePlayerVoiceEffects(StartOfRound __instance) { if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null) { return; } typeof(StartOfRound).GetField("updatePlayerVoiceInterval", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(__instance, 2f); PlayerControllerB val = ((!GameNetworkManager.Instance.localPlayerController.isPlayerDead || !((Object)(object)GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript != (Object)null)) ? GameNetworkManager.Instance.localPlayerController : GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript); for (int i = 0; i < __instance.allPlayerScripts.Length; i++) { PlayerControllerB val2 = __instance.allPlayerScripts[i]; if ((!val2.isPlayerControlled && !val2.isPlayerDead) || (Object)(object)val2 == (Object)(object)GameNetworkManager.Instance.localPlayerController) { continue; } if (val2.voicePlayerState == null || val2.currentVoiceChatIngameSettings._playerState == null || (Object)(object)val2.currentVoiceChatAudioSource == (Object)null) { __instance.RefreshPlayerVoicePlaybackObjects(); if (val2.voicePlayerState == null || (Object)(object)val2.currentVoiceChatAudioSource == (Object)null) { Debug.Log((object)$"Was not able to access voice chat object for player #{i}; {val2.voicePlayerState == null}; {(Object)(object)val2.currentVoiceChatAudioSource == (Object)null}"); continue; } } AudioSource currentVoiceChatAudioSource = __instance.allPlayerScripts[i].currentVoiceChatAudioSource; bool flag = val2.speakingToWalkieTalkie && val.holdingWalkieTalkie && (Object)(object)val2 != (Object)(object)val; if (val2.isPlayerDead) { ((Behaviour)((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>()).enabled = false; ((Behaviour)((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>()).enabled = false; currentVoiceChatAudioSource.panStereo = 0f; SoundManager.Instance.playerVoicePitchTargets[val2.playerClientId] = 1f; SoundManager.Instance.SetPlayerPitch(1f, (int)val2.playerClientId); if (GameNetworkManager.Instance.localPlayerController.isPlayerDead) { currentVoiceChatAudioSource.spatialBlend = 0f; val2.currentVoiceChatIngameSettings.set2D = true; if ((Object)(object)val2.currentVoiceChatIngameSettings != (Object)null && (Object)(object)val2.currentVoiceChatIngameSettings._playbackComponent != (Object)null) { _playbackVolumeProperty.SetValue(val2.currentVoiceChatIngameSettings._playbackComponent, Mathf.Clamp((SoundManager.Instance.playerVoiceVolumes[i] + 1f) * (float)(2 * Plugin._LoudnessMultiplier.Value), 0f, 1f)); } } else { currentVoiceChatAudioSource.spatialBlend = 1f; val2.currentVoiceChatIngameSettings.set2D = false; if ((Object)(object)val2.currentVoiceChatIngameSettings != (Object)null && (Object)(object)val2.currentVoiceChatIngameSettings._playbackComponent != (Object)null) { _playbackVolumeProperty.SetValue(val2.currentVoiceChatIngameSettings._playbackComponent, 0); } } continue; } AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>(); OccludeAudio component2 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>(); ((Behaviour)component).enabled = true; component2.overridingLowPass = flag || __instance.allPlayerScripts[i].voiceMuffledByEnemy; ((Behaviour)((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>()).enabled = flag; if (!flag) { currentVoiceChatAudioSource.spatialBlend = 1f; val2.currentVoiceChatIngameSettings.set2D = false; currentVoiceChatAudioSource.bypassListenerEffects = false; currentVoiceChatAudioSource.bypassEffects = false; currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[val2.playerClientId]; component.lowpassResonanceQ = 1f; } else { currentVoiceChatAudioSource.spatialBlend = 0f; val2.currentVoiceChatIngameSettings.set2D = true; if (GameNetworkManager.Instance.localPlayerController.isPlayerDead) { currentVoiceChatAudioSource.panStereo = 0f; currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[val2.playerClientId]; currentVoiceChatAudioSource.bypassListenerEffects = false; currentVoiceChatAudioSource.bypassEffects = false; } else { currentVoiceChatAudioSource.panStereo = 0.4f; currentVoiceChatAudioSource.bypassListenerEffects = false; currentVoiceChatAudioSource.bypassEffects = false; currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[val2.playerClientId]; } component2.lowPassOverride = 4000f; component.lowpassResonanceQ = 3f; } if ((Object)(object)val2.currentVoiceChatIngameSettings != (Object)null && (Object)(object)val2.currentVoiceChatIngameSettings._playbackComponent != (Object)null) { _playbackVolumeProperty.SetValue(val2.currentVoiceChatIngameSettings._playbackComponent, Mathf.Clamp((SoundManager.Instance.playerVoiceVolumes[i] + 1f) * (float)(2 * Plugin._LoudnessMultiplier.Value), 0f, 1f)); } } } [HarmonyPatch(typeof(StartOfRound), "Awake")] [HarmonyPrefix] public static void ResizeLists(ref StartOfRound __instance) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown __instance.allPlayerObjects = Helper.ResizeArray(__instance.allPlayerObjects, Plugin.MaxPlayers); __instance.allPlayerScripts = Helper.ResizeArray(__instance.allPlayerScripts, Plugin.MaxPlayers); __instance.gameStats.allPlayerStats = Helper.ResizeArray(__instance.gameStats.allPlayerStats, Plugin.MaxPlayers); __instance.playerSpawnPositions = Helper.ResizeArray(__instance.playerSpawnPositions, Plugin.MaxPlayers); for (int i = 4; i < Plugin.MaxPlayers; i++) { __instance.gameStats.allPlayerStats[i] = new PlayerStats(); __instance.playerSpawnPositions[i] = __instance.playerSpawnPositions[0]; } } [HarmonyPatch(typeof(SoundManager), "SetPlayerVoiceFilters")] [HarmonyPrefix] public static bool SetPlayerVoiceFilters(ref SoundManager __instance) { for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (!StartOfRound.Instance.allPlayerScripts[i].isPlayerControlled && !StartOfRound.Instance.allPlayerScripts[i].isPlayerDead) { __instance.playerVoicePitches[i] = 1f; __instance.playerVoiceVolumes[i] = 1f; continue; } if (StartOfRound.Instance.allPlayerScripts[i].voicePlayerState != null) { typeof(VoicePlayback).GetProperty("Dissonance.Audio.Playback.IVoicePlaybackInternal.PlaybackVolume", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(StartOfRound.Instance.allPlayerScripts[i].currentVoiceChatIngameSettings._playbackComponent, Mathf.Clamp((SoundManager.Instance.playerVoiceVolumes[i] + 1f) * (float)(2 * Plugin._LoudnessMultiplier.Value), 0f, 1f)); } if (Mathf.Abs(__instance.playerVoicePitches[i] - __instance.playerVoicePitchTargets[i]) > 0.025f) { __instance.playerVoicePitches[i] = Mathf.Lerp(__instance.playerVoicePitches[i], __instance.playerVoicePitchTargets[i], 3f * Time.deltaTime); } else if (__instance.playerVoicePitches[i] != __instance.playerVoicePitchTargets[i]) { __instance.playerVoicePitches[i] = __instance.playerVoicePitchTargets[i]; } } return false; } [HarmonyPatch(typeof(MenuManager), "OnEnable")] [HarmonyPostfix] public static void CustomMenu(ref MenuManager __instance) { //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: 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_01ff: 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_021c: 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_0239: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_029c: 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_02c1: Unknown result type (might be due to invalid IL or missing references) GameObject p2; RectTransform rt9 = default(RectTransform); if (!__instance.isInitScene) { GameObject gameObject = ((Component)__instance.HostSettingsOptionsNormal.transform.parent.parent).gameObject; Component component = gameObject.GetComponent(typeof(RectTransform)); RectTransform val = (RectTransform)(object)((component is RectTransform) ? component : null); p2 = ((Component)gameObject.transform.Find("PrivatePublicDescription")).gameObject; Component component2 = p2.GetComponent(typeof(RectTransform)); RectTransform val2 = (RectTransform)(object)((component2 is RectTransform) ? component2 : null); Component component3 = ((Component)__instance.HostSettingsOptionsNormal.transform.Find("EnterAName")).gameObject.GetComponent(typeof(RectTransform)); RectTransform val3 = (RectTransform)(object)((component3 is RectTransform) ? component3 : null); GameObject gameObject2 = ((Component)__instance.HostSettingsOptionsNormal.transform.Find("ServerNameField")).gameObject; Component component4 = gameObject2.GetComponent(typeof(RectTransform)); RectTransform val4 = (RectTransform)(object)((component4 is RectTransform) ? component4 : null); Component component5 = ((Component)gameObject.transform.Find("Confirm")).gameObject.GetComponent(typeof(RectTransform)); RectTransform val5 = (RectTransform)(object)((component5 is RectTransform) ? component5 : null); Component component6 = ((Component)gameObject.transform.Find("Back")).gameObject.GetComponent(typeof(RectTransform)); RectTransform val6 = (RectTransform)(object)((component6 is RectTransform) ? component6 : null); Component component7 = ((Component)__instance.HostSettingsOptionsNormal.transform.Find("Public")).gameObject.GetComponent(typeof(RectTransform)); RectTransform val7 = (RectTransform)(object)((component7 is RectTransform) ? component7 : null); Component component8 = ((Component)__instance.HostSettingsOptionsNormal.transform.Find("Private")).gameObject.GetComponent(typeof(RectTransform)); Component obj = ((component8 is RectTransform) ? component8 : null); GameObject val8 = Object.Instantiate<GameObject>(gameObject2, gameObject2.transform.parent); ref RectTransform reference = ref rt9; Component component9 = val8.GetComponent(typeof(RectTransform)); reference = (RectTransform)(object)((component9 is RectTransform) ? component9 : null); val.sizeDelta = new Vector2(val.sizeDelta.x, 200f); val2.anchoredPosition = new Vector2(val2.anchoredPosition.x, -50f); val3.anchoredPosition = new Vector2(val3.anchoredPosition.x, 40f); val4.anchoredPosition = new Vector2(val4.anchoredPosition.x, 55f); val5.anchoredPosition = new Vector2(val5.anchoredPosition.x, -60f); val6.anchoredPosition = new Vector2(val6.anchoredPosition.x, -85f); val7.anchoredPosition = new Vector2(val7.anchoredPosition.x, -23f); ((RectTransform)obj).anchoredPosition = new Vector2(((RectTransform)obj).anchoredPosition.x, -23f); rt9.anchoredPosition = new Vector2(rt9.anchoredPosition.x, 21f); ((Object)rt9).name = "ServerPlayersField"; ((Component)rt9).GetComponent<TMP_InputField>().contentType = (ContentType)2; ((TMP_Text)((Component)((Component)rt9).transform.Find("Text Area").Find("Placeholder")).gameObject.GetComponent<TextMeshProUGUI>()).text = "Max players (16)..."; ((Component)rt9).transform.parent = __instance.HostSettingsOptionsNormal.transform; ((UnityEvent<string>)(object)((Component)rt9).GetComponent<TMP_InputField>().onValueChanged).AddListener((UnityAction<string>)delegate { OnChange(); }); } void OnChange() { string text = Regex.Replace(((Component)rt9).GetComponent<TMP_InputField>().text, "[^0-9]", ""); Debug.Log((object)text); if (!int.TryParse(text, out var result)) { result = 16; } result = Math.Min(Math.Max(result, 4), 40); Debug.Log((object)result); if (result > 16) { ((TMP_Text)p2.GetComponent<TextMeshProUGUI>()).text = "Notice: High max player counts\nmay cause lag."; } else if (((TMP_Text)p2.GetComponent<TextMeshProUGUI>()).text == "Notice: High max player counts\nmay cause lag.") { ((TMP_Text)p2.GetComponent<TextMeshProUGUI>()).text = "yeah you should be good now lol"; } } } [HarmonyPatch(typeof(MenuManager), "StartHosting")] [HarmonyPrefix] public static bool StartHost(MenuManager __instance) { //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) if (!GameNetworkManager.Instance.currentLobby.HasValue) { return true; } if (!int.TryParse(Regex.Replace(((TMP_Text)((Component)((Component)__instance.HostSettingsOptionsNormal.transform.Find("ServerPlayersField")).gameObject.transform.Find("Text Area").Find("Text")).gameObject.GetComponent<TextMeshProUGUI>()).text, "[^0-9]", ""), out var result)) { result = 16; } result = Math.Min(Math.Max(result, 4), 40); Lobby valueOrDefault = GameNetworkManager.Instance.currentLobby.GetValueOrDefault(); ((Lobby)(ref valueOrDefault)).SetData("MaxPlayers", result.ToString()); Debug.Log((object)$"SETTING MAX PLAYERS TO {result}!"); Plugin.MaxPlayers = result; if ((Object)(object)GameNetworkManager.Instance != (Object)null) { GameNetworkManager.Instance.maxAllowedPlayers = Plugin.MaxPlayers; } return true; } [HarmonyPatch(typeof(HUDManager), "FillEndGameStats")] [HarmonyPrefix] public static bool FillEndGameStats() { return false; } [HarmonyPatch(typeof(GameNetworkManager), "StartHost")] [HarmonyPrefix] public static bool DoTheThe() { Plugin.CustomNetObjects.Clear(); return true; } [HarmonyPatch(typeof(GameNetworkManager), "StartClient")] [HarmonyPrefix] public static bool StartClient(GameNetworkManager __instance) { Plugin.CustomNetObjects.Clear(); return true; } [HarmonyPatch(typeof(MenuManager), "StartAClient")] [HarmonyPrefix] public static bool StartAClient() { Plugin.CustomNetObjects.Clear(); Debug.Log((object)"LanRunningggg!"); return true; } [HarmonyPatch(typeof(SteamLobbyManager), "loadLobbyListAndFilter")] [HarmonyPostfix] public static IEnumerator LoadLobbyListAndFilter(IEnumerator result, SteamLobbyManager __instance) { while (result.MoveNext()) { yield return result.Current; } Debug.Log((object)"Injecting BL playercounts into lobby list."); LobbySlot[] componentsInChildren = ((Component)__instance.levelListContainer).GetComponentsInChildren<LobbySlot>(true); foreach (LobbySlot val in componentsInChildren) { try { ((TMP_Text)val.LobbyName).text = ((TMP_Text)val.LobbyName).text.Replace("[BiggerLobby]", "[BL]"); if (!int.TryParse(((Lobby)(ref val.thisLobby)).GetData("MaxPlayers"), out var result2)) { result2 = 4; } ((TMP_Text)val.playerCount).text = ((TMP_Text)val.playerCount).text.Replace("/ 4", $"/ {result2}"); } catch (Exception ex) { Debug.LogWarning((object)"Exception while injecting BL lobby metadata:"); Debug.LogWarning((object)ex); } } } [HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")] [HarmonyPrefix] public static void SetMaxMembers(ref int maxMembers) { maxMembers = Plugin.MaxPlayers; } [HarmonyPatch(typeof(GameNetworkManager), "SetConnectionDataBeforeConnecting")] [HarmonyPrefix] public static bool SetConnectionDataBeforeConnecting(GameNetworkManager __instance) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) __instance.localClientWaitingForApproval = true; Debug.Log((object)("Game version: " + __instance.gameVersionNum)); if (__instance.disableSteam) { NetworkManager.Singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(__instance.gameVersionNum + ",BiggerLobbyVersion2.5.0"); } else { NetworkManager.Singleton.NetworkConfig.ConnectionData = Encoding.ASCII.GetBytes(__instance.gameVersionNum + "," + SteamId.op_Implicit(SteamClient.SteamId) + ",BiggerLobbyVersion2.5.0"); } return false; } [HarmonyPatch(typeof(GameNetworkManager), "LobbyDataIsJoinable")] [HarmonyPrefix] public static bool SkipLobbySizeCheck(ref GameNetworkManager __instance, ref bool __result, Lobby lobby) { //IL_004f: 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) string data = ((Lobby)(ref lobby)).GetData("vers"); if (!int.TryParse(((Lobby)(ref lobby)).GetData("MaxPlayers"), out var result)) { result = 16; } result = Math.Min(Math.Max(result, 4), 40); if (((Lobby)(ref lobby)).MemberCount >= result || ((Lobby)(ref lobby)).MemberCount < 1) { Debug.Log((object)$"Lobby join denied! Too many members in lobby! {((Lobby)(ref lobby)).Id}"); Object.FindObjectOfType<MenuManager>().SetLoadingScreen(false, (RoomEnter)4, "The server is full!"); __result = false; return false; } if (data != __instance.gameVersionNum.ToString()) { Debug.Log((object)$"Lobby join denied! Attempted to join vers.{data} lobby id: {((Lobby)(ref lobby)).Id}"); Object.FindObjectOfType<MenuManager>().SetLoadingScreen(false, (RoomEnter)2, $"The server host is playing on version {data} while you are on version {__instance.gameVersionNum}."); __result = false; return false; } if (((Lobby)(ref lobby)).GetData("joinable") == "false") { Debug.Log((object)"Lobby join denied! Host lobby is not joinable"); Object.FindObjectOfType<MenuManager>().SetLoadingScreen(false, (RoomEnter)2, "The server host has already landed their ship, or they are still loading in."); __result = false; return false; } Plugin.MaxPlayers = result; Debug.Log((object)$"SETTING MAX PLAYERS TO {result}!"); if ((Object)(object)__instance != (Object)null) { __instance.maxAllowedPlayers = Plugin.MaxPlayers; } __result = true; return false; } } [HarmonyPatch] internal class PlayerObjects { private static StartOfRound startOfRound; private static bool instantiating; private static int nextClientId; private static PlayerControllerB referencePlayer; [HarmonyPatch(typeof(StartOfRound), "Awake")] [HarmonyPrefix] public static void ResizeLists(ref StartOfRound __instance) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown __instance.allPlayerObjects = Helper.ResizeArray(__instance.allPlayerObjects, Plugin.MaxPlayers); __instance.allPlayerScripts = Helper.ResizeArray(__instance.allPlayerScripts, Plugin.MaxPlayers); __instance.gameStats.allPlayerStats = Helper.ResizeArray(__instance.gameStats.allPlayerStats, Plugin.MaxPlayers); __instance.playerSpawnPositions = Helper.ResizeArray(__instance.playerSpawnPositions, Plugin.MaxPlayers); for (int i = 4; i < Plugin.MaxPlayers; i++) { __instance.gameStats.allPlayerStats[i] = new PlayerStats(); __instance.playerSpawnPositions[i] = __instance.playerSpawnPositions[0]; } } [HarmonyPatch(typeof(ForestGiantAI), "Start")] [HarmonyPrefix] public static bool ResizeLists2(ref ForestGiantAI __instance) { __instance.playerStealthMeters = Helper.ResizeArray(__instance.playerStealthMeters, Plugin.MaxPlayers); return true; } [HarmonyPatch(typeof(HUDManager), "Awake")] [HarmonyPostfix] public static void ResizeLists2(ref HUDManager __instance) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown __instance.endgameStatsAnimator = Object.Instantiate<Animator>(__instance.endgameStatsAnimator); __instance.playerLevels = Helper.ResizeArray(__instance.playerLevels, Plugin.MaxPlayers); for (int i = 4; i < Plugin.MaxPlayers; i++) { __instance.playerLevels[i] = new PlayerLevel(); } } [HarmonyPatch(typeof(SoundManager), "Awake")] [HarmonyPostfix] public static void SoundWake(ref SoundManager __instance) { __instance.playerVoiceMixers = Helper.ResizeArray(__instance.playerVoiceMixers, Plugin.MaxPlayers); for (int i = 0; i < Plugin.MaxPlayers; i++) { __instance.playerVoiceMixers[i] = __instance.diageticMixer.outputAudioMixerGroup; } } [HarmonyPatch(typeof(SoundManager), "Start")] [HarmonyPostfix] public static void ResizeSoundManagerLists(ref SoundManager __instance) { __instance.playerVoicePitchLerpSpeed = new float[Plugin.MaxPlayers + 1]; __instance.playerVoicePitchTargets = new float[Plugin.MaxPlayers + 1]; __instance.playerVoiceVolumes = new float[Plugin.MaxPlayers + 1]; __instance.playerVoicePitches = new float[Plugin.MaxPlayers + 1]; for (int i = 1; i < Plugin.MaxPlayers + 1; i++) { __instance.playerVoicePitchLerpSpeed[i] = 3f; __instance.playerVoicePitchTargets[i] = 1f; __instance.playerVoicePitches[i] = 1f; __instance.playerVoiceVolumes[i] = 1f; } } [HarmonyPatch(typeof(EnemyAI), "EnableEnemyMesh")] [HarmonyPrefix] public static bool EnableEnemyMesh(EnemyAI __instance, bool enable, bool overrideDoNotSet = false) { int layer = ((!enable) ? 23 : 19); for (int i = 0; i < __instance.skinnedMeshRenderers.Length; i++) { if (Object.op_Implicit((Object)(object)__instance.skinnedMeshRenderers[i]) && (!((Component)__instance.skinnedMeshRenderers[i]).CompareTag("DoNotSet") || overrideDoNotSet)) { ((Component)__instance.skinnedMeshRenderers[i]).gameObject.layer = layer; } } for (int j = 0; j < __instance.meshRenderers.Length; j++) { if (Object.op_Implicit((Object)(object)__instance.meshRenderers[j]) && (!((Component)__instance.meshRenderers[j]).CompareTag("DoNotSet") || overrideDoNotSet)) { ((Component)__instance.meshRenderers[j]).gameObject.layer = layer; } } return false; } [HarmonyPatch(typeof(ShipTeleporter), "Awake")] [HarmonyPrefix] public static bool Awake2(ShipTeleporter __instance) { int[] array = new int[Plugin.MaxPlayers]; for (int i = 0; i < Plugin.MaxPlayers; i++) { array[i] = -1; } typeof(ShipTeleporter).GetField("playersBeingTeleported", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(__instance, array); __instance.buttonTrigger.interactable = false; typeof(ShipTeleporter).GetField("cooldownTime", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(__instance, __instance.cooldownAmount); return false; } [HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")] [HarmonyPrefix] public static bool AddPlayers(NetworkSceneManager __instance) { //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) startOfRound = StartOfRound.Instance; if ((Object)(object)startOfRound.allPlayerObjects[Plugin.MaxPlayers - 1] != (Object)null) { return true; } referencePlayer = startOfRound.allPlayerObjects[0].GetComponent<PlayerControllerB>(); GameObject playerPrefab = startOfRound.playerPrefab; Transform transform = ((Component)startOfRound.playersContainer).transform; FieldInfo field = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.NonPublic); PropertyInfo property = typeof(NetworkObject).GetProperty("NetworkObjectId", BindingFlags.Instance | BindingFlags.Public); typeof(NetworkSceneManager).GetField("ScenePlacedObjects", BindingFlags.Instance | BindingFlags.NonPublic); instantiating = true; typeof(NetworkSpawnManager).GetMethod("SpawnNetworkObjectLocally", BindingFlags.Instance | BindingFlags.NonPublic, null, CallingConventions.Any, new Type[6] { typeof(NetworkObject), typeof(ulong), typeof(bool), typeof(bool), typeof(ulong), typeof(bool) }, null); for (int i = 4; i < Plugin.MaxPlayers; i++) { nextClientId = i; GameObject val = Object.Instantiate<GameObject>(playerPrefab, transform); PlayerControllerB component = val.GetComponent<PlayerControllerB>(); NetworkObject component2 = val.GetComponent<NetworkObject>(); NetworkObject component3 = ((Component)val.transform.Find("PlayerPhysicsBox")).gameObject.GetComponent<NetworkObject>(); NetworkObject component4 = ((Component)val.transform.Find("ScavengerModel/metarig/ScavengerModelArmsOnly/metarig/spine.003/shoulder.R/arm.R_upper/arm.R_lower/hand.R/LocalItemHolder")).gameObject.GetComponent<NetworkObject>(); NetworkObject component5 = ((Component)val.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/shoulder.R/arm.R_upper/arm.R_lower/hand.R/ServerItemHolder")).gameObject.GetComponent<NetworkObject>(); component.TeleportPlayer(StartOfRound.Instance.notSpawnedPosition.position, false, 0f, false, true); startOfRound.allPlayerObjects[i] = val; startOfRound.allPlayerScripts[i] = component; uint num = (uint)(6942069 + i); ulong num2 = 6942069uL + (ulong)i; uint num3 = (uint)(123456789 + i); uint num4 = (uint)(987654321 + i); uint num5 = (uint)(124585949 + i); ulong num6 = 123456789uL + (ulong)i; ulong num7 = 987654321uL + (ulong)i; ulong num8 = 124585949uL + (ulong)i; Scene scene = ((Component)component2).gameObject.scene; _ = ((Scene)(ref scene)).handle; field.SetValue(component2, num); property.SetValue(component2, num2); field.SetValue(component3, num3); property.SetValue(component3, num6); field.SetValue(component4, num4); property.SetValue(component4, num7); field.SetValue(component5, num5); property.SetValue(component5, num8); ManualCameraRenderer[] array = Object.FindObjectsByType<ManualCameraRenderer>((FindObjectsInactive)1, (FindObjectsSortMode)0); for (int j = 0; j < array.Length; j++) { array[j].AddTransformAsTargetToRadar(((Component)component).transform, "Player #" + j, false); } } instantiating = false; return true; } [HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")] [HarmonyPrefix] public static bool AddUserToPlayerList(QuickMenuManager __instance, ulong steamId, string playerName, int playerObjectId) { if (playerObjectId >= 0 && playerObjectId <= Plugin.MaxPlayers) { __instance.playerListSlots[playerObjectId].KickUserButton.SetActive(((NetworkBehaviour)StartOfRound.Instance).IsServer); __instance.playerListSlots[playerObjectId].slotContainer.SetActive(true); __instance.playerListSlots[playerObjectId].isConnected = true; __instance.playerListSlots[playerObjectId].playerSteamId = steamId; ((TMP_Text)__instance.playerListSlots[playerObjectId].usernameHeader).text = playerName.Replace("bizzlemip", "<color=#008282>bizzlemip</color>"); if ((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null) { __instance.playerListSlots[playerObjectId].volumeSliderContainer.SetActive(playerObjectId != (int)GameNetworkManager.Instance.localPlayerController.playerClientId); } } return false; } [HarmonyPatch(typeof(QuickMenuManager), "Update")] [HarmonyPrefix] private static bool Update(QuickMenuManager __instance) { for (int i = 0; i < __instance.playerListSlots.Length; i++) { if (__instance.playerListSlots[i].isConnected) { float num = __instance.playerListSlots[i].volumeSlider.value / __instance.playerListSlots[i].volumeSlider.maxValue; if (num == -1f) { SoundManager.Instance.playerVoiceVolumes[i] = -1f; } else { SoundManager.Instance.playerVoiceVolumes[i] = num; } } } return false; } [HarmonyPatch(typeof(QuickMenuManager), "Start")] [HarmonyPrefix] public static bool FixPlayerList(ref QuickMenuManager __instance) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0192: 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_020d: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Expected O, but got Unknown //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_0335: Expected O, but got Unknown GameObject val = null; GameObject gameObject = ((Component)__instance.playerListPanel.transform.Find("Image")).gameObject; if (Object.op_Implicit((Object)(object)gameObject.transform.Find("Mask"))) { val = ((Component)gameObject.transform.Find("Mask")).gameObject; } GameObject val2 = new GameObject("Mask"); GameObject val3 = new GameObject("ScrollViewport"); GameObject val4 = new GameObject("BGCollision"); GameObject val5 = new GameObject("ScrollContent"); val2.transform.SetParent(gameObject.transform); val3.transform.SetParent(val2.transform); val4.transform.SetParent(val3.transform); val5.transform.SetParent(val3.transform); val2.transform.localScale = Vector3.one; val3.transform.localScale = Vector3.one; val5.transform.localScale = Vector3.one; val2.AddComponent<RectTransform>().sizeDelta = new Vector2(300f, 280f); val2.transform.localPosition = new Vector3(-10f, 110f, 0f); val3.transform.localPosition = new Vector3(0f, -10f, 0f); val5.AddComponent<RectTransform>().pivot = new Vector2(0.5f, 1f); val2.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 1f); val2.transform.localPosition = new Vector3(-10f, 110f, 0f); val2.AddComponent<RectMask2D>(); VerticalLayoutGroup val6 = val5.AddComponent<VerticalLayoutGroup>(); ContentSizeFitter obj = val5.AddComponent<ContentSizeFitter>(); ScrollRect obj2 = val3.AddComponent<ScrollRect>(); obj2.viewport = val3.AddComponent<RectTransform>(); obj2.content = val5.GetComponent<RectTransform>(); obj2.horizontal = false; Image val7 = val4.AddComponent<Image>(); val4.GetComponent<RectTransform>().anchorMin = new Vector2(0f, 0f); val4.GetComponent<RectTransform>().anchorMax = new Vector2(1f, 1f); ((Graphic)val7).color = new Color(255f, 255f, 255f, 0f); ((HorizontalOrVerticalLayoutGroup)val6).spacing = 50f; obj.horizontalFit = (FitMode)0; obj.verticalFit = (FitMode)2; __instance.playerListSlots = Helper.ResizeArray(__instance.playerListSlots, Plugin.MaxPlayers); for (int i = 0; i < Plugin.MaxPlayers; i++) { if (i < 4) { __instance.playerListSlots[i].slotContainer.transform.SetParent(val5.transform); continue; } PlayerListSlot val8 = new PlayerListSlot(); GameObject val9 = (val8.slotContainer = Object.Instantiate<GameObject>(__instance.playerListSlots[0].slotContainer)); val8.volumeSliderContainer = ((Component)val9.transform.Find("VoiceVolumeSlider")).gameObject; val8.KickUserButton = ((Component)val9.transform.Find("KickButton")).gameObject; QuickMenuManager yeahoriginal = __instance; int localI = i; ((UnityEvent)val8.KickUserButton.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { yeahoriginal.KickUserFromServer(localI); }); val8.isConnected = false; val8.usernameHeader = ((Component)val9.transform.Find("PlayerNameButton").Find("PName")).gameObject.GetComponent<TextMeshProUGUI>(); val8.volumeSlider = ((Component)val9.transform.Find("VoiceVolumeSlider").Find("Slider")).gameObject.GetComponent<Slider>(); val8.playerSteamId = __instance.playerListSlots[0].playerSteamId; val9.transform.SetParent(val5.transform, false); __instance.playerListSlots[i] = val8; } if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } return true; } [HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")] [HarmonyPrefix] public static bool SyncShipUnlockablesClientRpc(StartOfRound __instance, int[] playerSuitIDs, bool shipLightsOn, Vector3[] placeableObjectPositions, Vector3[] placeableObjectRotations, int[] placeableObjects, int[] storedItems, int[] scrapValues, int[] itemSaveData) { Debug.Log((object)"INITIAL ARRAY LENGTHS"); Debug.Log((object)__instance.allPlayerScripts.Length); Debug.Log((object)playerSuitIDs.Length); return true; } [HarmonyPatch(typeof(ManualCameraRenderer), "Awake")] [HarmonyPrefix] public static bool Mawake(ref ManualCameraRenderer __instance) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown for (int i = 0; i < 4; i++) { __instance.radarTargets.Add(new TransformAndName(((Component)StartOfRound.Instance.allPlayerScripts[i]).transform, StartOfRound.Instance.allPlayerScripts[i].playerUsername, false)); } __instance.targetTransformIndex = 0; __instance.targetedPlayer = StartOfRound.Instance.allPlayerScripts[0]; return false; } [HarmonyPatch(typeof(PlayerControllerB), "Awake")] [HarmonyPrefix] public static bool FixPlayerObject(ref PlayerControllerB __instance) { if (!instantiating) { return true; } ((Object)((Component)__instance).gameObject).name = $"ExtraPlayer{nextClientId}"; __instance.playerClientId = (ulong)nextClientId; __instance.actualClientId = (ulong)nextClientId; StartOfRound.Instance.allPlayerObjects[nextClientId] = ((Component)((Component)__instance).transform.parent).gameObject; StartOfRound.Instance.allPlayerScripts[nextClientId] = __instance; FieldInfo[] fields = typeof(PlayerControllerB).GetFields(); foreach (FieldInfo fieldInfo in fields) { object value = fieldInfo.GetValue(__instance); object value2 = fieldInfo.GetValue(referencePlayer); if (value == null && value2 != null) { fieldInfo.SetValue(__instance, value2); } } ((Behaviour)__instance).enabled = true; return true; } [HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> GetPlayerSpawnPosition(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); list[0].opcode = OpCodes.Ldc_I4_1; return list.AsEnumerable(); } } }
plugins/BonkHitSFX.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using BonkHitSFX.Patches; 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(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("BonkHitSFX")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BonkHitSFX")] [assembly: AssemblyTitle("BonkHitSFX")] [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 BonkHitSFX { [BepInPlugin("sunnobunno.bonkhitsfx", "Bonk Hit SFX", "1.0.4")] public class BonkHitSFXBase : BaseUnityPlugin { private const string modGUID = "sunnobunno.bonkhitsfx"; private const string modName = "Bonk Hit SFX"; private const string modVersion = "1.0.4"; private readonly Harmony harmony = new Harmony("sunnobunno.bonkhitsfx"); private static BonkHitSFXBase? Instance; internal ManualLogSource? mls; internal static AudioClip[]? newHitSFX; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("sunnobunno.bonkhitsfx"); mls.LogInfo((object)"sunnobunno.bonkhitsfx is loading."); string location = ((BaseUnityPlugin)Instance).Info.Location; string text = "BonkHitSFX.dll"; string text2 = location.TrimEnd(text.ToCharArray()); string text3 = text2 + "bonkhitsfx"; AssetBundle val = AssetBundle.LoadFromFile(text3); if ((Object)(object)val == (Object)null) { mls.LogError((object)"Failed to load audio assets!"); return; } newHitSFX = val.LoadAssetWithSubAssets<AudioClip>("Assets/bonkhitsfx.mp3"); harmony.PatchAll(typeof(HitSFXPatch)); mls.LogInfo((object)"sunnobunno.bonkhitsfx is loaded. Ow."); } } } namespace BonkHitSFX.Patches { [HarmonyPatch(typeof(Shovel))] internal class HitSFXPatch { [HarmonyPatch("HitShovelClientRpc")] [HarmonyPatch("HitShovel")] [HarmonyPrefix] public static void hitSFXPatch(ref AudioClip[] ___hitSFX) { AudioClip[] newHitSFX = BonkHitSFXBase.newHitSFX; ___hitSFX = newHitSFX; } } }
plugins/BuyableShotgun.dll
Decompiled a year 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.Logging; using HarmonyLib; using LethalLib.Modules; using Microsoft.CodeAnalysis; 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(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("BuyableShotgun")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyCopyright("Copyright © 2023 MegaPiggy")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("BuyableShotgun")] [assembly: AssemblyTitle("BuyableShotgun")] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BuyableShotgun { [BepInPlugin("MegaPiggy.BuyableShotgun", "BuyableShotgun", "1.0.0")] public class BuyableShotgun : BaseUnityPlugin { private const string modGUID = "MegaPiggy.BuyableShotgun"; private const string modName = "BuyableShotgun"; private const string modVersion = "1.0.0"; private readonly Harmony harmony = new Harmony("MegaPiggy.BuyableShotgun"); private static BuyableShotgun Instance; public int ShotgunPrice; public bool added; private static ManualLogSource LoggerInstance => ((BaseUnityPlugin)Instance).Logger; public List<Item> AllItems => Resources.FindObjectsOfTypeAll<Item>().Concat(Object.FindObjectsByType<Item>((FindObjectsInactive)1, (FindObjectsSortMode)1)).ToList(); public Item Shotgun => ((IEnumerable<Item>)AllItems).FirstOrDefault((Func<Item, bool>)((Item item) => ((Object)item).name == "Shotgun")); private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(); ShotgunPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Prices", "ShotgunPrice", 700, "Credits needed to buy shotgun").Value; SceneManager.sceneLoaded += OnSceneLoaded; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin BuyableShotgun is loaded with version 1.0.0!"); } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (!added && ((Scene)(ref scene)).name == "MainMenu") { added = true; Items.RegisterShopItem(Shotgun, ShotgunPrice); } } } }
plugins/DontTouchMe.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using GameNetcodeStuff; using HarmonyLib; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("DontTouchMe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DontTouchMe")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("2b5c0b79-7fa5-44d5-a3d7-384bed3474cb")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] internal class <Module> { static <Module>() { } } namespace DontTouchMe; public class Assets { public static AssetBundle MainAssetBundle; public static EnemyType EnemyType; public static TerminalNode EnemyNode; public static TerminalKeyword EnemyKeyword; public static AudioClip AudioMasked1; public static AudioClip AudioMasked2; internal static Stream GetEmbededResource(string name) { return Assembly.GetExecutingAssembly().GetManifestResourceStream("DontTouchMe." + name); } public static void Init() { Stream embededResource = GetEmbededResource("dtm.bundle"); MainAssetBundle = AssetBundle.LoadFromStream(embededResource); EnemyType = MainAssetBundle.LoadAsset<EnemyType>("Assets/Mods/DontTouchMe/Resources/DTMEnemy.asset"); EnemyNode = MainAssetBundle.LoadAsset<TerminalNode>("Assets/Mods/DontTouchMe/Resources/DTMNode.asset"); EnemyKeyword = MainAssetBundle.LoadAsset<TerminalKeyword>("Assets/Mods/DontTouchMe/Resources/DTMKeyword.asset"); AudioMasked1 = MainAssetBundle.LoadAsset<AudioClip>("Assets/Mods/DontTouchMe/Resources/dtm_masked_laugh1.wav"); AudioMasked2 = MainAssetBundle.LoadAsset<AudioClip>("Assets/Mods/DontTouchMe/Resources/dtm_masked_laugh2.wav"); } } public class DTMEntityAI : EnemyAI { public static List<DTMEntityAI> Instances = new List<DTMEntityAI>(); [Header("DTM Specific")] public InteractTrigger[] Triggers; public GameObject Music; public AudioSource VoiceA; public AudioSource VoiceB; private float AttackTime; private bool IsAttacking; private bool HasAttacked; private bool AttemptedMurder; public MaskedPlayerEnemy MaskedEnemy; private float StaringTimestamp; [Header("Disguise")] public GameObject MainModel; public GameObject Disguise; private int DisguiseID; private float ScreenShakeTime; private const float KillWindowMin = 2.3f; private const float KillWindowMax = 3.5f; private float KillWindowStart = 2.8f; private const string ButtonTouchParam = "Touched"; private const string ButtonPressParam = "Press"; private Coroutine ExplodePlayerCoroutine; public static int Count => Instances.Count; public static DTMEntityAI GetClosest(Vector3 pos) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) DTMEntityAI dTMEntityAI = null; if (Instances.Count == 0) { return dTMEntityAI; } if (Instances.Count == 1) { return Instances[0]; } float num = float.MaxValue; foreach (DTMEntityAI instance in Instances) { if ((Object)(object)instance == (Object)null) { Instances.RemoveAll((DTMEntityAI v) => (Object)(object)v == (Object)null); dTMEntityAI = GetClosest(pos); break; } float num2 = Vector3.Distance(((Component)instance).transform.position, pos); if ((Object)(object)dTMEntityAI == (Object)null || num2 < num) { dTMEntityAI = instance; num = num2; } } return dTMEntityAI; } public void SetTrigger(bool interactable) { InteractTrigger[] triggers = Triggers; foreach (InteractTrigger val in triggers) { val.interactable = interactable; } } public bool CanBeShocked() { if (!IsAttacking) { return !HasAttacked; } return false; } public override void OnDestroy() { ((EnemyAI)this).OnDestroy(); Instances.Remove(this); } public override void Start() { //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown Instances.Add(this); base.skinnedMeshRenderers = ((Component)this).gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(true); base.meshRenderers = ((Component)this).gameObject.GetComponentsInChildren<MeshRenderer>(true); base.thisNetworkObject = ((Component)this).gameObject.GetComponentInChildren<NetworkObject>(true); base.thisEnemyIndex = RoundManager.Instance.numberOfEnemiesInScene; RoundManager instance = RoundManager.Instance; instance.numberOfEnemiesInScene++; base.isOutside = Plugin.SpawnOutsideChance > 0 && Random.Range(0, 100) < Plugin.SpawnOutsideChance; if (base.isOutside) { base.allAINodes = GameObject.FindGameObjectsWithTag("OutsideAINode"); if ((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null) { ((EnemyAI)this).EnableEnemyMesh(!StartOfRound.Instance.hangarDoorsClosed || !GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom, false); } } else { base.allAINodes = GameObject.FindGameObjectsWithTag("AINode"); } base.serverPosition = ((Component)this).transform.position; base.updatePositionThreshold = 0f; base.path1 = new NavMeshPath(); base.openDoorSpeedMultiplier = base.enemyType.doorSpeedMultiplier; ResetInteraction(changeLocation: true); Debug.Log((object)"DON'T TOUCH ME | DON'T TOUCH ME | DON'T TOUCH ME | DON'T TOUCH ME | DON'T TOUCH ME | DON'T TOUCH ME"); Debug.Log((object)("Spawned Outside: " + base.isOutside)); } private void ResetInteraction(bool changeLocation) { //IL_0092: 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_009d: 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_00ae: 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_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) MaskedEnemy = null; base.targetPlayer = null; IsAttacking = false; HasAttacked = false; AttemptedMurder = false; SetTrigger(interactable: true); Music.SetActive(false); ((Component)VoiceA).gameObject.SetActive(false); base.creatureAnimator.ResetTrigger("Touched"); base.creatureAnimator.ResetTrigger("Press"); if (changeLocation) { if (((NetworkBehaviour)this).IsOwner) { Vector3 position = base.allAINodes[Random.Range(0, base.allAINodes.Length)].transform.position; position = RoundManager.Instance.GetNavMeshPosition(position, RoundManager.Instance.navHit, 1f, -1); ((Component)this).transform.position = position; ((Component)this).transform.rotation = Quaternion.Euler(0f, Random.Range(-180f, 180f), 0f); DisguiseID = ((Random.Range(0, 100) < Plugin.DisguiseAsItemChance) ? Random.Range(1, Disguise.transform.childCount) : (-1)); Debug.Log((object)"[DTM] Trying to sync position with other players."); SyncSpawnOnServer(); } else { base.isClientCalculatingAI = false; } } } public override void Update() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0389: Unknown result type (might be due to invalid IL or missing references) //IL_038e: Unknown result type (might be due to invalid IL or missing references) //IL_0393: Unknown result type (might be due to invalid IL or missing references) //IL_0397: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: Unknown result type (might be due to invalid IL or missing references) //IL_03b0: Unknown result type (might be due to invalid IL or missing references) //IL_03c9: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)MaskedEnemy != (Object)null) { if (((NetworkBehaviour)MaskedEnemy).IsOwner && !((EnemyAI)MaskedEnemy).isEnemyDead && ((EnemyAI)MaskedEnemy).moveTowardsDestination && Vector3.Distance(((EnemyAI)MaskedEnemy).destination, ((Component)this).transform.position) < 1.5f && Object.op_Implicit((Object)(object)base.targetPlayer) && ((EnemyAI)MaskedEnemy).isOutside == !base.targetPlayer.isInsideFactory && !base.targetPlayer.isPlayerDead && ((EnemyAI)MaskedEnemy).currentBehaviourState != null) { float num = Vector3.Distance(((Component)MaskedEnemy).transform.position, ((Component)this).transform.position); switch (((EnemyAI)MaskedEnemy).currentBehaviourState.name) { case "FoundDTM": if (!(num > 1.5f)) { Debug.Log((object)"[MASK] Start staring."); StaringTimestamp = Time.time + Random.Range(1f, 4f); MaskedEnemy.LookAtPlayerServerRpc((int)base.targetPlayer.playerClientId); ((EnemyAI)MaskedEnemy).SetDestinationToPosition(((Component)MaskedEnemy).transform.position, false); ((EnemyAI)MaskedEnemy).SwitchToBehaviourState(((EnemyAI)MaskedEnemy).currentBehaviourStateIndex + 1); } break; case "StareDTM": if (!(Time.time < StaringTimestamp)) { Debug.Log((object)"[MASK] Look at the button."); StaringTimestamp = Time.time + Random.Range(1f, 2f); MaskedEnemy.StopLookingAtTransformServerRpc(); MaskedEnemy.LookAtPositionServerRpc(((Component)this).transform.position, 10f); ((EnemyAI)MaskedEnemy).SwitchToBehaviourState(((EnemyAI)MaskedEnemy).currentBehaviourStateIndex + 1); } break; case "PressDTM": if (!(Time.time < StaringTimestamp)) { Debug.Log((object)"[MASK] Pressing the button."); OnTouched(base.targetPlayer); MaskedEnemy.StopLookingAtTransformServerRpc(); ((EnemyAI)MaskedEnemy).SwitchToBehaviourState(0); MaskedEnemy = null; base.targetPlayer = null; } break; } } else { Debug.Log((object)"[MASK] Lost interest."); MaskedEnemy.StopLookingAtTransformServerRpc(); ((EnemyAI)MaskedEnemy).SwitchToBehaviourState(0); MaskedEnemy = null; base.targetPlayer = null; } } if (!IsAttacking) { return; } if (Object.op_Implicit((Object)(object)MaskedEnemy)) { MaskedEnemy = null; base.targetPlayer = null; } float num2 = Time.time - AttackTime; PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; bool flag = ((EnemyAI)this).PlayerIsTargetable(localPlayerController, false, false) || (localPlayerController.hasBegunSpectating && Object.op_Implicit((Object)(object)localPlayerController.spectatedPlayerScript) && ((EnemyAI)this).PlayerIsTargetable(localPlayerController.spectatedPlayerScript, false, false)); if (flag && ScreenShakeTime < Time.time) { HUDManager.Instance.ShakeCamera((ScreenShakeType)3); ScreenShakeTime = Time.time + 0.1f; } AudioSource voiceA = VoiceA; bool flag3 = (VoiceB.mute = flag); voiceA.mute = !flag3; if (num2 > KillWindowStart && num2 < 4.4f) { if (localPlayerController.isPlayerControlled && !localPlayerController.isPlayerDead && flag) { Vector3 val = ((Component)localPlayerController).transform.position - ((Component)this).transform.position; Vector3 val2 = ((Vector3)(ref val)).normalized * Random.Range(15f, 30f); val2.y = Random.Range(10f, 15f); localPlayerController.KillPlayer(val2, true, (CauseOfDeath)3, 0); ExplodePlayerServerRpc((int)localPlayerController.playerClientId); } if (Plugin.IncludeMonstersOnKill && ((NetworkBehaviour)this).IsServer && !AttemptedMurder) { foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies) { if (Object.op_Implicit((Object)(object)spawnedEnemy) && spawnedEnemy.isOutside == base.isOutside && (Object)(object)((Component)spawnedEnemy).gameObject != (Object)(object)((Component)this).gameObject && spawnedEnemy.thisNetworkObject.IsSpawned && (Plugin.IncludeUnkillableMonsters || spawnedEnemy.enemyType.canDie)) { Debug.Log((object)("[DTM] Killing " + ((Object)spawnedEnemy).name)); spawnedEnemy.thisNetworkObject.Despawn(true); } } AttemptedMurder = true; } } if (num2 >= 5f) { if (Plugin.DestroyEntityAfterTouch) { IsAttacking = false; HasAttacked = true; ((EnemyAI)this).KillEnemy(true); } else { ResetInteraction(Plugin.ChangeLocationAfterTouch); } } } private IEnumerator ExplodePlayerEffect(int clientId) { PlayerControllerB killedPlayer = StartOfRound.Instance.allPlayerScripts[clientId]; float startTime = Time.realtimeSinceStartup; yield return (object)new WaitUntil((Func<bool>)(() => Time.realtimeSinceStartup - startTime > 1f || (Object)(object)killedPlayer.deadBody != (Object)null)); Transform transform = ((Component)killedPlayer).transform; if ((Object)(object)killedPlayer.deadBody != (Object)null) { transform = ((Component)killedPlayer.deadBody).transform; } Object.Instantiate<GameObject>(StartOfRound.Instance.explosionPrefab, transform.position + Vector3.up * 0.5f, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true); base.inSpecialAnimation = false; } [ClientRpc] private void ExplodePlayerClientRpc(int clientId) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3906254083u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, clientId); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3906254083u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { if (ExplodePlayerCoroutine != null) { ((MonoBehaviour)this).StopCoroutine(ExplodePlayerCoroutine); } ExplodePlayerCoroutine = ((MonoBehaviour)this).StartCoroutine(ExplodePlayerEffect(clientId)); } } [ServerRpc(RequireOwnership = false)] private void ExplodePlayerServerRpc(int clientId) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(877622320u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, clientId); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 877622320u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ExplodePlayerClientRpc(clientId); } } } private void UpdateDisguise() { MainModel.SetActive(DisguiseID < 1); Disguise.SetActive(!MainModel.activeSelf); if (Disguise.activeSelf) { Transform transform = Disguise.transform; for (int i = 1; i < transform.childCount; i++) { ((Component)transform.GetChild(i)).gameObject.SetActive(i == DisguiseID); } } } private void SyncSpawnOnServer() { //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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_001b: 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) base.serverPosition = ((Component)this).transform.position; if (((NetworkBehaviour)this).IsOwner) { SpawnClientRpc(base.serverPosition, ((Component)this).transform.eulerAngles.y, DisguiseID); } else { SpawnServerRpc(base.serverPosition, ((Component)this).transform.eulerAngles.y, DisguiseID); } } [ClientRpc] public void SpawnClientRpc(Vector3 newPos, float yRot, int disguise) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3860255087u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref newPos); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref yRot, default(ForPrimitives)); BytePacker.WriteValueBitPacked(val2, disguise); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3860255087u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { DisguiseID = disguise; ((Component)this).transform.position = newPos; ((Component)this).transform.rotation = Quaternion.Euler(0f, yRot, 0f); Music.SetActive(Plugin.PlayMusic && DisguiseID < 1); UpdateDisguise(); } } } [ServerRpc] public void SpawnServerRpc(Vector3 newPos, float yRot, int disguise) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Invalid comparison between Unknown and I4 //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: 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_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2003288437u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref newPos); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref yRot, default(ForPrimitives)); BytePacker.WriteValueBitPacked(val2, disguise); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2003288437u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { SpawnClientRpc(newPos, yRot, disguise); } } public void OnTouched(PlayerControllerB player) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) if (!IsAttacking && !((Object)(object)player == (Object)null)) { int num = ((DisguiseID > 0) ? 80 : 20); if (Random.Range(0, 100) > num) { StartAttack(!player.isInsideFactory); } else if (Random.Range(0, 100) < 10) { player.JumpToFearLevel(1f, true); } else { player.DamagePlayer(999, true, true, (CauseOfDeath)0, Random.Range(1, 3), false, default(Vector3)); } } } public void StartAttack(bool outside) { Debug.Log((object)"[DTM] Starting attack"); if (((NetworkBehaviour)this).IsOwner) { AttackClientRpc(outside); } else { AttackServerRpc(outside); } } [ClientRpc] public void AttackClientRpc(bool outside) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0083: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3888608358u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref outside, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3888608358u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Debug.Log((object)"[DTM] Attempting attack on client"); if (!IsAttacking && !HasAttacked) { AttackTime = Time.time; ScreenShakeTime = 0f; KillWindowStart = Random.Range(2.3f, 3.5f); DisguiseID = -1; Disguise.SetActive(false); MainModel.SetActive(true); Music.SetActive(false); ((Component)VoiceA).gameObject.SetActive(true); base.isOutside = outside; SetTrigger(interactable: false); IsAttacking = true; base.creatureAnimator.SetTrigger("Touched"); } } } [ServerRpc(RequireOwnership = false)] public void AttackServerRpc(bool outside) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0083: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2283008872u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref outside, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2283008872u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Debug.Log((object)"[DTM] Attempting attack from server"); AttackClientRpc(outside); } } } public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false) { Debug.Log((object)("[DTM] Hit by enemy: " + (object)playerWhoHit)); OnTouched(playerWhoHit); } public override void SetEnemyStunned(bool setToStunned, float setToStunTime = 1f, PlayerControllerB setStunnedByPlayer = null) { if (setToStunned) { OnTouched(setStunnedByPlayer); } } protected override void __initializeVariables() { ((EnemyAI)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_DTMEntityAI() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(3906254083u, new RpcReceiveHandler(__rpc_handler_3906254083)); NetworkManager.__rpc_func_table.Add(877622320u, new RpcReceiveHandler(__rpc_handler_877622320)); NetworkManager.__rpc_func_table.Add(3860255087u, new RpcReceiveHandler(__rpc_handler_3860255087)); NetworkManager.__rpc_func_table.Add(2003288437u, new RpcReceiveHandler(__rpc_handler_2003288437)); NetworkManager.__rpc_func_table.Add(3888608358u, new RpcReceiveHandler(__rpc_handler_3888608358)); NetworkManager.__rpc_func_table.Add(2283008872u, new RpcReceiveHandler(__rpc_handler_2283008872)); } private static void __rpc_handler_3906254083(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int clientId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref clientId); target.__rpc_exec_stage = (__RpcExecStage)2; ((DTMEntityAI)(object)target).ExplodePlayerClientRpc(clientId); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_877622320(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int clientId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref clientId); target.__rpc_exec_stage = (__RpcExecStage)1; ((DTMEntityAI)(object)target).ExplodePlayerServerRpc(clientId); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3860255087(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_003c: 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_004b: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { Vector3 newPos = default(Vector3); ((FastBufferReader)(ref reader)).ReadValueSafe(ref newPos); float yRot = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref yRot, default(ForPrimitives)); int disguise = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref disguise); target.__rpc_exec_stage = (__RpcExecStage)2; ((DTMEntityAI)(object)target).SpawnClientRpc(newPos, yRot, disguise); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2003288437(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: 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_0055: Invalid comparison between Unknown and I4 NetworkManager networkManager = target.NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } Vector3 newPos = default(Vector3); ((FastBufferReader)(ref reader)).ReadValueSafe(ref newPos); float yRot = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref yRot, default(ForPrimitives)); int disguise = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref disguise); target.__rpc_exec_stage = (__RpcExecStage)1; ((DTMEntityAI)(object)target).SpawnServerRpc(newPos, yRot, disguise); target.__rpc_exec_stage = (__RpcExecStage)0; } private static void __rpc_handler_3888608358(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool outside = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref outside, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)2; ((DTMEntityAI)(object)target).AttackClientRpc(outside); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2283008872(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool outside = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref outside, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)1; ((DTMEntityAI)(object)target).AttackServerRpc(outside); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "DTMEntityAI"; } } public class DTMHitBox : MonoBehaviour, IHittable, IShockableWithGun { public DTMEntityAI mainScript; bool IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit, bool playHitSFX) { ((EnemyAI)mainScript).SetEnemyStunned(true, 1f, playerWhoHit); return true; } bool IShockableWithGun.CanBeShocked() { return mainScript.CanBeShocked(); } Vector3 IShockableWithGun.GetShockablePosition() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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_001e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)((EnemyAI)mainScript).eye != (Object)null) { return ((EnemyAI)mainScript).eye.position; } return ((Component)this).transform.position + Vector3.up * 1f; } float IShockableWithGun.GetDifficultyMultiplier() { return ((EnemyAI)mainScript).enemyType.stunGameDifficultyMultiplier; } void IShockableWithGun.ShockWithGun(PlayerControllerB shockedByPlayer) { ((EnemyAI)mainScript).SetEnemyStunned(true, 0.25f, shockedByPlayer); DTMEntityAI dTMEntityAI = mainScript; ((EnemyAI)dTMEntityAI).stunnedIndefinitely = ((EnemyAI)dTMEntityAI).stunnedIndefinitely + 1; } Transform IShockableWithGun.GetShockableTransform() { return ((Component)this).transform; } NetworkObject IShockableWithGun.GetNetworkObject() { return ((NetworkBehaviour)mainScript).NetworkObject; } void IShockableWithGun.StopShockingWithGun() { } } [HarmonyPatch(typeof(MaskedPlayerEnemy))] internal class MaskedEnemyPatch { public const float InteractProximity = 1.5f; public const float DetectProximity = 10f; public const float StaringTimeMin = 1f; public const float StaringTimeMax = 4f; private static EnemyBehaviourState[] BehaviourStates; public const string BehaviourStateFound = "FoundDTM"; public const string BehaviourStateStare = "StareDTM"; public const string BehaviourStatePress = "PressDTM"; [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch(ref MaskedPlayerEnemy __instance) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown //IL_0062: 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_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown if (BehaviourStates == null) { BehaviourStates = (EnemyBehaviourState[])(object)new EnemyBehaviourState[3] { new EnemyBehaviourState { name = "FoundDTM", playOneShotVoice = ((Object)(object)Assets.AudioMasked1 != (Object)null), VoiceClip = Assets.AudioMasked1 }, new EnemyBehaviourState { name = "StareDTM", VoiceClip = null, playOneShotVoice = false }, new EnemyBehaviourState { name = "PressDTM", playOneShotVoice = ((Object)(object)Assets.AudioMasked2 != (Object)null), VoiceClip = Assets.AudioMasked2 } }; } EnemyBehaviourState[] enemyBehaviourStates = ((EnemyAI)__instance).enemyBehaviourStates; int num = enemyBehaviourStates.Length; EnemyBehaviourState[] array = (EnemyBehaviourState[])(object)new EnemyBehaviourState[num + BehaviourStates.Length]; for (int i = 0; i < array.Length; i++) { array[i] = ((i < num) ? enemyBehaviourStates[i] : BehaviourStates[i % num]); } ((EnemyAI)__instance).enemyBehaviourStates = array; } [HarmonyPatch("DoAIInterval")] [HarmonyPostfix] private static void DoAIIntervalPatch(ref MaskedPlayerEnemy __instance) { //IL_001f: 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_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Expected O, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: 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_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) if (DTMEntityAI.Count <= 0 || ((EnemyAI)__instance).currentBehaviourStateIndex != 1) { return; } Vector3 position = ((Component)__instance).transform.position; DTMEntityAI closest = DTMEntityAI.GetClosest(position); if ((Object)(object)closest == (Object)null || !closest.CanBeShocked() || (Object)(object)closest.MaskedEnemy != (Object)null) { return; } Vector3 position2 = ((Component)closest).transform.position; float num = Vector3.Distance(position, position2); PlayerControllerB targetPlayer = ((EnemyAI)__instance).targetPlayer; if ((Object)(object)targetPlayer != (Object)null && ((EnemyAI)__instance).movingTowardsTargetPlayer && num < 10f && !((EnemyAI)__instance).PathIsIntersectedByLineOfSight(position2, false, true)) { ((EnemyAI)__instance).path1 = new NavMeshPath(); if (((EnemyAI)__instance).agent.CalculatePath(position2, ((EnemyAI)__instance).path1) && !(Vector3.Distance(((EnemyAI)__instance).path1.corners[((EnemyAI)__instance).path1.corners.Length - 1], RoundManager.Instance.GetNavMeshPosition(position2, RoundManager.Instance.navHit, 2.7f, -1)) > 1.55f) && ((EnemyAI)__instance).SetDestinationToPosition(position2, true)) { __instance.StopLookingAtTransformServerRpc(); ((EnemyAI)__instance).SwitchToBehaviourState(Array.IndexOf(((EnemyAI)__instance).enemyBehaviourStates, BehaviourStates[0])); closest.MaskedEnemy = __instance; ((EnemyAI)closest).targetPlayer = targetPlayer; } } } } [BepInPlugin("Kittenji.DontTouchMe", "Don't Touch Me", "1.2.1")] public class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(GameNetworkManager))] internal class GameNetworkManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch() { ((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(Assets.EnemyType.enemyPrefab); Debug.Log((object)"[DTM] Added network prefab"); } } [HarmonyPatch(typeof(Terminal))] internal class TerminalPatch { private static Random TerminalRandom = new Random(); private static FieldInfo InteractTriggerField = AccessTools.Field(typeof(Terminal), "terminalTrigger"); private static InteractTrigger m_Trigger; private static bool HandlingSpecialEvent; private static InteractTrigger GetTrigger(Terminal __instance) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown if ((Object)(object)m_Trigger == (Object)null) { m_Trigger = (InteractTrigger)InteractTriggerField.GetValue(__instance); } return m_Trigger; } private static void PerformRandomTPOnPlayer(PlayerControllerB localPlayer, int index, bool redirected = false) { //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_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_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: 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_0204: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: 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_006e: 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_0076: 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_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: 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_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) if (localPlayer.isPlayerDead) { return; } bool flag; Vector3 val; switch (index) { default: return; case 0: case 1: { flag = index == 0; GameObject[] array = (flag ? RoundManager.Instance.insideAINodes : RoundManager.Instance.outsideAINodes); if (array.Length != 0) { val = array[Random.Range(0, array.Length)].transform.position; val = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(val, 10f, default(NavMeshHit)); Debug.LogWarning((object)"Where am I anyway?"); break; } return; } case 2: { Turret[] array2 = Object.FindObjectsOfType<Turret>(false); if (array2 == null || array2.Length == 0) { PerformRandomTPOnPlayer(localPlayer, redirected ? Random.Range(0, 2) : 3, redirected: true); return; } Turret val3 = array2[Random.Range(0, array2.Length)]; if ((Object)(object)val3 == (Object)null) { return; } val = ((Component)val3).transform.position; flag = val.y < -80f; val = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(val, 2f, default(NavMeshHit)); Debug.LogError((object)"Run Forest, RUN!!!"); break; } case 3: { Landmine[] array3 = Object.FindObjectsOfType<Landmine>(false); if (array3 == null || array3.Length == 0) { PerformRandomTPOnPlayer(localPlayer, redirected ? Random.Range(0, 2) : 2, redirected: true); return; } Landmine val4 = array3[Random.Range(0, array3.Length)]; if ((Object)(object)val4 == (Object)null) { return; } val = ((Component)val4).transform.position; flag = val.y < -80f; val = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(val, 2f, default(NavMeshHit)); Debug.LogError((object)"WAIT, DON'T MOVE!!!... Or do... I'm a programmer, not a land mine inspector."); break; } case 4: { List<EnemyAI> spawnedEnemies = RoundManager.Instance.SpawnedEnemies; if (spawnedEnemies == null || spawnedEnemies.Count == 0) { PerformRandomTPOnPlayer(localPlayer, Random.Range(0, 2), redirected: true); return; } EnemyAI val2 = spawnedEnemies[Random.Range(0, spawnedEnemies.Count)]; val = ((Component)val2).transform.position; flag = val.y < -80f; val = RoundManager.Instance.GetRandomNavMeshPositionInRadiusSpherical(val, 8f, default(NavMeshHit)); Debug.LogError((object)"OH NO!, that is horrible!!!............ anyway.."); break; } case 5: val = ((Component)localPlayer).transform.position + Vector3.up * 100f; flag = false; Debug.LogError((object)"Fly like a bird... wait, why are you falling?"); break; } if (!localPlayer.isPlayerDead) { localPlayer.DropAllHeldItems(true, false); localPlayer.isInElevator = false; localPlayer.isInHangarShipRoom = false; localPlayer.isInsideFactory = flag; localPlayer.averageVelocity = 0f; localPlayer.velocityLastFrame = Vector3.zero; localPlayer.TeleportPlayer(val, false, 0f, false, true); HUDManager.Instance.ShakeCamera((ScreenShakeType)1); } } private static IEnumerator SpecialEvent(Terminal __instance, int index) { HandlingSpecialEvent = true; PlayerControllerB localPlayer = GameNetworkManager.Instance.localPlayerController; InteractTrigger trigger = GetTrigger(__instance); if (!Object.op_Implicit((Object)(object)trigger)) { HandlingSpecialEvent = false; yield break; } yield return (object)new WaitForSeconds(0.35f); switch (index) { case 1: __instance.QuitTerminal(); if (Random.Range(0, 100) < 34) { while (trigger.currentCooldownValue > 0f) { yield return null; } localPlayer.DropAllHeldItems(true, false); Debug.LogError((object)"Haha, butter fingers!"); } else { Debug.LogWarning((object)"GET OUT!"); } break; case 2: __instance.QuitTerminal(); while (trigger.currentCooldownValue > 0f) { yield return null; } if (!StartOfRound.Instance.inShipPhase) { index = RoundManager.Instance.GetRandomWeightedIndex(Terminal_Weights_TP, (Random)null); PerformRandomTPOnPlayer(localPlayer, index); } break; case 3: { __instance.QuitTerminal(); while (trigger.currentCooldownValue > 0f) { yield return null; } for (int i = 0; i < localPlayer.ItemSlots.Length; i++) { GrabbableObject val = localPlayer.ItemSlots[i]; if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.itemProperties) && val.itemProperties.requiresBattery) { val.insertedBattery = new Battery(true, 0f); } } Debug.LogError((object)"This mod is not sponsored by DURACELL"); break; } case 4: { __instance.QuitTerminal(); while (trigger.currentCooldownValue > 0f) { yield return null; } if (StartOfRound.Instance.inShipPhase) { break; } GameObject[] outsideAINodes = RoundManager.Instance.outsideAINodes; if (outsideAINodes.Length != 0) { int num = Random.Range(1, 5); for (int j = 0; j < num; j++) { RoundManager.Instance.SpawnEnemyOnServer(Vector3.zero, Random.Range(-180f, 180f), -3); } Debug.LogError((object)("OOPS! Have fun with " + ((num > 1) ? "those" : "that") + "...")); } break; } case 5: __instance.QuitTerminal(); while (trigger.currentCooldownValue > 0f) { yield return null; } if (!StartOfRound.Instance.inShipPhase && localPlayer.health > 5) { localPlayer.DamagePlayer(localPlayer.health - 5, true, true, (CauseOfDeath)0, 0, false, default(Vector3)); Debug.LogError((object)"Ouch, that must hurt."); } break; case 6: __instance.QuitTerminal(); while (trigger.currentCooldownValue > 0f) { yield return null; } if (!StartOfRound.Instance.inShipPhase) { localPlayer.KillPlayer(Vector3.up, true, (CauseOfDeath)0, 0); Debug.LogError((object)"Curiosity killed the cat, in this case... you"); } break; } HandlingSpecialEvent = false; } [HarmonyPatch("RunTerminalEvents")] [HarmonyPostfix] private static void RunTerminalEventsPatch(ref Terminal __instance, TerminalNode node) { if (node.terminalEvent == "dontReadMe") { Debug.Log((object)"Don't read me, please."); int randomWeightedIndex = RoundManager.Instance.GetRandomWeightedIndex(Terminal_Weights, TerminalRandom); if (!HandlingSpecialEvent) { ((MonoBehaviour)__instance).StartCoroutine(SpecialEvent(__instance, randomWeightedIndex)); } } } [HarmonyPatch("Start")] [HarmonyPrefix] private static void StartPatch(ref Terminal __instance) { //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Expected O, but got Unknown Debug.Log((object)"[DTM] Adding terminal entries"); TerminalNode terminalNode = Assets.EnemyNode; TerminalKeyword val = __instance.terminalNodes.allKeywords.First((TerminalKeyword k) => k.word == "info"); if (!__instance.enemyFiles.Any((TerminalNode x) => x.creatureName == terminalNode.creatureName)) { TerminalKeyword keyword = Assets.EnemyKeyword; keyword.defaultVerb = val; List<TerminalKeyword> list = __instance.terminalNodes.allKeywords.ToList(); if (!list.Any((TerminalKeyword x) => x.word == keyword.word)) { list.Add(keyword); __instance.terminalNodes.allKeywords = list.ToArray(); } List<CompatibleNoun> list2 = val.compatibleNouns.ToList(); if (!list2.Any((CompatibleNoun x) => x.noun.word == keyword.word)) { list2.Add(new CompatibleNoun { noun = keyword, result = terminalNode }); } val.compatibleNouns = list2.ToArray(); terminalNode.creatureFileID = __instance.enemyFiles.Count; __instance.enemyFiles.Add(terminalNode); Assets.EnemyType.enemyPrefab.GetComponentInChildren<ScanNodeProperties>().creatureScanID = terminalNode.creatureFileID; Debug.Log((object)"[DTM] Done adding entries."); } } } [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void AwakePatch(ref StartOfRound __instance) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown EnemyType enemyDef = Assets.EnemyType; SelectableLevel[] levels = __instance.levels; foreach (SelectableLevel val in levels) { if (val.Enemies.Count >= 2 && !val.Enemies.Any((SpawnableEnemyWithRarity e) => (Object)(object)e.enemyType == (Object)(object)enemyDef)) { Debug.Log((object)("[DTM] Adding entity to level: " + val.PlanetName)); val.Enemies.Add(new SpawnableEnemyWithRarity { enemyType = enemyDef, rarity = SpawnRarity }); } } } } private const string modGUID = "Kittenji.DontTouchMe"; private readonly Harmony harmony = new Harmony("Kittenji.DontTouchMe"); public static bool PlayMusic = true; public static bool IncludeMonstersOnKill = true; public static bool IncludeUnkillableMonsters = true; public static bool DestroyMonstersOnKill = true; public static int SpawnRarity = 24; public static int SpawnOutsideChance = 2; public static bool ChangeLocationAfterTouch = true; public static bool DestroyEntityAfterTouch = true; public static int DisguiseAsItemChance = 40; private const int Terminal_Weight_None = 5; private const int Terminal_Weight_Quit = 50; private const int Terminal_Weight_TP = 15; private const int Terminal_Weight_Battery = 14; private const int Terminal_Weight_Punish = 14; private const int Terminal_Weight_Break = 3; private const int Terminal_Weight_Kill = 1; private const int Terminal_Weight_TP_Inside = 36; private const int Terminal_Weight_TP_Outside = 36; private const int Terminal_Weight_TP_Turret = 18; private const int Terminal_Weight_TP_Landmine = 6; private const int Terminal_Weight_TP_Monster = 3; private const int Terminal_Weight_TP_Sky = 1; private const int Terminal_Punish_Min = 1; private const int Terminal_Punish_Max = 5; private static readonly int[] Terminal_Weights = new int[7] { 5, 50, 15, 14, 14, 3, 1 }; private static readonly int[] Terminal_Weights_TP = new int[6] { 36, 36, 18, 6, 3, 1 }; private void Awake() { SpawnRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Spawning", "Spawn Rarity", 24, "Spawn rarity. Lower value means lower chance to spawn. (default = 24)").Value; SpawnOutsideChance = ((BaseUnityPlugin)this).Config.Bind<int>("Spawning", "Spawn Rarity Outside", 2, "Random chance percentage for this entity to spawn outside. (default = 2)").Value; DisguiseAsItemChance = ((BaseUnityPlugin)this).Config.Bind<int>("Spawning", "Disguise As Item Chance", 45, "Random chance percentage for this entity to disguise itself as an item. (default = 45)").Value; ChangeLocationAfterTouch = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Changes Location", true, "If 'true' the entity will change it's position to a random location after the animation. (default = true)").Value; DestroyEntityAfterTouch = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Destroy After Touch", false, "If 'true' the entity will hide for the rest of the round after touch. It will teleport to a different location. (default = false)").Value; IncludeMonstersOnKill = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Include Monsters On Kill", true, "If 'true' the entity will not pick favorites and will try killing monsters in the facility as well. (default = true)").Value; DestroyMonstersOnKill = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Destroy Monsters On Kill", true, "If 'true' monsters will directly despawn to prevent lag and other potential issues. (default = true)").Value; IncludeUnkillableMonsters = ((BaseUnityPlugin)this).Config.Bind<bool>("Interaction", "Include Unkillable Monsters", true, "If 'true' the entity will also kill unkillable monsters too. (default = true)").Value; PlayMusic = ((BaseUnityPlugin)this).Config.Bind<bool>("Audio", "Play Music", true, "If 'true' the entity will play ominous music (Lobotomy Corp OST - Neutral 01) that can be heard in the distance, getting more noticeable the closer you get to it. (default = true)").Value; SpawnRarity = Mathf.Min(100, Mathf.Max(1, SpawnRarity)); SpawnOutsideChance = Mathf.Min(100, Mathf.Max(0, SpawnOutsideChance)); DisguiseAsItemChance = Mathf.Min(100, Mathf.Max(0, DisguiseAsItemChance)); ((BaseUnityPlugin)this).Config.Save(); Assets.Init(); harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Patched!"); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array = types; foreach (Type type in array) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array2 = methods; foreach (MethodInfo methodInfo in array2) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } } }
plugins/DynamicDeadline1.2.2.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using DynamicDeadlineMod.Patches; using HarmonyLib; 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: AssemblyTitle("DynamicDeadlineMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DynamicDeadlineMod")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("78c98d39-8b11-4a2c-bccb-e32338f5bacf")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace DynamicDeadlineMod { [BepInPlugin("Haha.DynamicDeadline", "Dynamic Deadline", "1.2.2")] public class DynamicDeadlineMod : BaseUnityPlugin { private const string modGUID = "Haha.DynamicDeadline"; private const string modName = "Dynamic Deadline"; private const string modVersion = "1.2.2"; private readonly Harmony harmony = new Harmony("Haha.DynamicDeadline"); public static DynamicDeadlineMod Instance; internal static ConfigEntry<float> MinScrapValuePerDay; internal static ConfigEntry<bool> legacyCal; internal static ConfigEntry<float> legacyDailyValue; internal static ConfigEntry<bool> useMinMax; internal static ConfigEntry<float> setMinimumDays; internal static ConfigEntry<float> setMaximumDays; internal ManualLogSource mls; internal void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Dynamic Deadline"); mls.LogInfo((object)"No more short deadlines for excessive quotas."); MinScrapValuePerDay = ((BaseUnityPlugin)this).Config.Bind<float>("Customizable Values", "Minimum Daily ScrapValue", 200f, "Set this value to the minimum scrap value you should achieve per day. This will ignore the calculation for daily scrap if it's below this number."); useMinMax = ((BaseUnityPlugin)this).Config.Bind<bool>("Customizable Values", "Use Custom Deadline Range", false, "Set to true if you want to use the custom minimum/maximum deadline range."); setMinimumDays = ((BaseUnityPlugin)this).Config.Bind<float>("Customizable Values", "Minimum Deadline", 3f, "If Use Custom Deadline Range is enabled, this is the minimum deadline you will have."); setMaximumDays = ((BaseUnityPlugin)this).Config.Bind<float>("Customizable Values", "Maximum Deadline", float.MaxValue, "If use Custom Deadline Range is enabled, this is the maximum deadline you will have."); legacyCal = ((BaseUnityPlugin)this).Config.Bind<bool>("Customizeable Values - Legacy", "Legacy Calculations", false, "Set to true if you want to use the deadline calculation from 1.1.0 prior."); legacyDailyValue = ((BaseUnityPlugin)this).Config.Bind<float>("Customizeable Values - Legacy", "Daily Scrap Value", 200f, "Set this number to the value of scrap you can reasonably achieve in a single day."); harmony.PatchAll(typeof(DynamicDeadlineMod)); harmony.PatchAll(typeof(ProfitQuotaPatch)); } } } namespace DynamicDeadlineMod.Patches { [HarmonyPatch(typeof(TimeOfDay), "SyncTimeClientRpc")] public class FixTheDeadline { [HarmonyPrefix] public static void DeadlineBroke() { string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName; float num; if (ES3.KeyExists("totalOfAverage")) { num = ES3.Load<float>("totalOfAverage", currentSaveFileName, 0f); } else { ES3.Save<float>("totalOfAverage", 0f, currentSaveFileName); num = ES3.Load<float>("totalOfAverage", currentSaveFileName, 0f); } if (num < DynamicDeadlineMod.MinScrapValuePerDay.Value * (float)TimeOfDay.Instance.timesFulfilledQuota) { num = DynamicDeadlineMod.MinScrapValuePerDay.Value * (float)TimeOfDay.Instance.timesFulfilledQuota; float num2 = num / (float)TimeOfDay.Instance.timesFulfilledQuota; float num3 = Mathf.Clamp(Mathf.Ceil((float)TimeOfDay.Instance.profitQuota / num2), 3f, float.MaxValue); ES3.Save<float>("totalOfAverage", num, currentSaveFileName); TimeOfDay.Instance.timeUntilDeadline = 700f * num3; ES3.Save<float>("previousDeadline", num3, currentSaveFileName); } } } [HarmonyPatch(typeof(GameNetworkManager), "ResetSavedGameValues")] public class ResetSavedValuesPatch { [HarmonyPrefix] public static void ResetSavedValues() { string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName; ES3.Save<float>("previousDeadline", 3f, currentSaveFileName); ES3.Save<float>("totalOfAverage", 0f, currentSaveFileName); } } [HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")] public class ProfitQuotaPatch { private static float quotaFulfilled; [HarmonyPrefix] public static void GetQuotaFulfilled() { quotaFulfilled = TimeOfDay.Instance.quotaFulfilled; } [HarmonyPostfix] private static void DynamicDeadline(TimeOfDay __instance) { string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName; bool isHost = ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost; float num = TimeOfDay.Instance.timesFulfilledQuota; float num2 = ((!DynamicDeadlineMod.useMinMax.Value) ? 3f : DynamicDeadlineMod.setMinimumDays.Value); float num3 = ((!DynamicDeadlineMod.useMinMax.Value) ? float.MaxValue : DynamicDeadlineMod.setMaximumDays.Value); float num4; if (ES3.KeyExists("previousDeadline")) { num4 = ES3.Load<float>("previousDeadline", currentSaveFileName, 3f); DynamicDeadlineMod.Instance.mls.LogInfo((object)$"Successfully loaded the previous totalOfAverage variable! totalofAverage is: {num4}"); } else { ES3.Save<float>("previousDeadline", 3f, currentSaveFileName); num4 = ES3.Load<float>("previousDeadline", currentSaveFileName, 3f); DynamicDeadlineMod.Instance.mls.LogInfo((object)"Could not load previousDeadline variable as it does not exist! Creating now!"); } float num5; if (ES3.KeyExists("totalOfAverage")) { num5 = ES3.Load<float>("totalOfAverage", currentSaveFileName, 0f); DynamicDeadlineMod.Instance.mls.LogInfo((object)$"Successfully loaded the previous totalOfAverage variable! totalofAverage is: {num5}"); } else { ES3.Save<float>("totalOfAverage", 0f, currentSaveFileName); num5 = ES3.Load<float>("totalOfAverage", currentSaveFileName, 0f); DynamicDeadlineMod.Instance.mls.LogInfo((object)"Could not load totalOfAverage variable as it does not exist! Creating now!"); } if (isHost && !DynamicDeadlineMod.legacyCal.Value) { float num6 = Mathf.Clamp(Mathf.Ceil(quotaFulfilled / num4), DynamicDeadlineMod.MinScrapValuePerDay.Value, 1000f); if (num5 == 0f && num != 0f) { num5 = DynamicDeadlineMod.MinScrapValuePerDay.Value * num - 1f; } float num7 = num5 / num; float num8 = Mathf.Clamp(Mathf.Ceil((float)__instance.profitQuota / num7), num2, num3); num5 += num6; __instance.timeUntilDeadline = __instance.totalTime * num8; DynamicDeadlineMod.Instance.mls.LogInfo((object)$"This person is the host, changing deadline. DailyValue registered as {num6}, new average is {num7}, and host is currently on their {num} run!"); TimeOfDay.Instance.SyncTimeClientRpc(__instance.globalTime, (int)__instance.timeUntilDeadline); DynamicDeadlineMod.Instance.mls.LogInfo((object)$"The new deadline is {num8} days."); num4 = num8; DynamicDeadlineMod.Instance.mls.LogInfo((object)$"Did the value get assigned properly? Previous deadline is {num4}"); ES3.Save<float>("previousDeadline", num4, currentSaveFileName); ES3.Save<float>("totalOfAverage", num5, currentSaveFileName); } else if (isHost && DynamicDeadlineMod.legacyCal.Value) { __instance.timeUntilDeadline = __instance.totalTime * Mathf.Clamp(Mathf.Ceil((float)__instance.profitQuota / DynamicDeadlineMod.legacyDailyValue.Value), num2, num3); DynamicDeadlineMod.Instance.mls.LogInfo((object)"This person is the host and using the legacy difficulty calculations. Changing deadline."); TimeOfDay.Instance.SyncTimeClientRpc(__instance.globalTime, (int)__instance.timeUntilDeadline); } else { DynamicDeadlineMod.Instance.mls.LogInfo((object)"This person is not the host. Will not change deadline or send rpc."); } } } }
plugins/FreeJester/FreeJester.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using FreeJester.Patches; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("FreeJester")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FreeJester")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("cb752f14-68ca-44e9-836b-f8a323fbbf36")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace FreeJester { [BepInPlugin("atg.FreeJester", "Free Jester", "1.0.3")] public class FreeJesterBase : BaseUnityPlugin { private const string modGUID = "atg.FreeJester"; private const string modName = "Free Jester"; private const string modVersion = "1.0.3"; private Harmony harmony = new Harmony("atg.FreeJester"); private static FreeJesterBase Instance; internal ManualLogSource mls; internal static AudioClip[] newSFX; private void Awake() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("atg.FreeJester"); mls.LogInfo((object)"Starting Free Jester :D"); mls.LogInfo((object)(((BaseUnityPlugin)Instance).Info.Location.TrimEnd("FreeJester.dll".ToCharArray()) + "freebird")); AssetBundle val = AssetBundle.LoadFromFile(((BaseUnityPlugin)Instance).Info.Location.TrimEnd("FreeJester.dll".ToCharArray()) + "freebird"); if ((Object)val == (Object)null) { mls.LogError((object)"Failed to load audio assets!"); return; } newSFX = val.LoadAssetWithSubAssets<AudioClip>("assets/freebird.mp3"); harmony.PatchAll(typeof(JesterAIPatch)); mls.LogInfo((object)"Free Jester is loaded"); harmony.PatchAll(typeof(FreeJesterBase)); } } } namespace FreeJester.Patches { [HarmonyPatch(typeof(JesterAI))] internal class JesterAIPatch { [HarmonyPatch("Start")] [HarmonyPrefix] public static void FreeJesterPatch(ref AudioClip ___popGoesTheWeaselTheme) { AudioClip[] newSFX = FreeJesterBase.newSFX; if (newSFX != null && newSFX.Length != 0) { AudioClip val = newSFX[0]; ___popGoesTheWeaselTheme = val; } } } }
plugins/FreeMoons.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; 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("FreeMoons")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("FreeMoons")] [assembly: AssemblyTitle("FreeMoons")] [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 SRH.Mods.LC { [BepInPlugin("SlushyRH.LethalCompany.FreeMoons", "FreeMoons", "1.0.1")] public class FreeMoonsPlugin : BaseUnityPlugin { private const string GUID = "SlushyRH.LethalCompany.FreeMoons"; private const string NAME = "FreeMoons"; private const string VERSION = "1.0.1"; private readonly Harmony harmony = new Harmony("SlushyRH.LethalCompany.FreeMoons"); public static FreeMoonsPlugin Instance { get; private set; } public ManualLogSource Log { get; private set; } private void Awake() { Log = Logger.CreateLogSource("SlushyRH.LethalCompany.FreeMoons"); if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(typeof(MoonPricePatch)); } } [HarmonyPatch(typeof(Terminal))] internal class MoonPricePatch { private static Terminal terminal = null; private static int totalCostOfItems = -5; [HarmonyPatch("Awake")] [HarmonyPostfix] private static void FindTerminal() { FreeMoonsPlugin.Instance.Log.LogInfo((object)"Finding terminal object!"); terminal = Object.FindObjectOfType<Terminal>(); if ((Object)(object)terminal == (Object)null) { FreeMoonsPlugin.Instance.Log.LogError((object)"Failed to find terminal object!"); } else { FreeMoonsPlugin.Instance.Log.LogInfo((object)"Found terminal object!"); } } [HarmonyPatch("LoadNewNode")] [HarmonyPrefix] private static void LoadNewNodePatchBefore(ref TerminalNode node) { if ((!((Object)(object)terminal == (Object)null) || !((Object)(object)node == (Object)null)) && node.buyRerouteToMoon == -2) { Traverse val = Traverse.Create((object)terminal).Field("totalCostOfItems"); totalCostOfItems = (int)val.GetValue(); val.SetValue((object)0); } } [HarmonyPatch("LoadNewNode")] [HarmonyPostfix] private static void LoadNewNodePatchAfter(ref TerminalNode node) { if ((!((Object)(object)terminal == (Object)null) || !((Object)(object)node == (Object)null)) && totalCostOfItems != -5) { Traverse val = Traverse.Create((object)terminal).Field("totalCostOfItems"); val.SetValue((object)0); totalCostOfItems = -5; } } [HarmonyPatch("LoadNewNodeIfAffordable")] [HarmonyPrefix] private static void LoadNewNodeIfAffordablePatch(ref TerminalNode node) { if (!((Object)(object)node == (Object)null) && node.buyRerouteToMoon != -1) { node.itemCost = 0; } } } }
plugins/HotbarPlus.dll
Decompiled a year agousing System; 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.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using HotbarPlus.Config; using HotbarPlus.Patches; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; 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: AssemblyTitle("HotbarPlus")] [assembly: AssemblyDescription("Mod made by flipf17.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HotbarPlus")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("fab060f0-b006-42ea-ba6f-473f4850c587")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace HotbarPlus { [HarmonyPatch] internal class Keybinds { private static InputAction[] quickItemShortcutActions; private static PlayerControllerB localPlayerController; private static bool setHotbarSize; [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void OnLocalPlayerConnect(PlayerControllerB __instance) { localPlayerController = __instance; setHotbarSize = false; if (!ConfigSettings.useOriginalKeybindsDefaultEmotes.Value) { InputActionAsset actions = IngamePlayerSettings.Instance.playerInput.actions; InputAction val = actions.FindAction("Emote1", false); InputAction val2 = actions.FindAction("Emote2", false); InputActionRebindingExtensions.ApplyBindingOverride(val, "<Keyboard>/f1", (string)null, (string)null); InputActionRebindingExtensions.ApplyBindingOverride(val2, "<Keyboard>/f2", (string)null, (string)null); } } public static void OnSetHotbarSize() { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown setHotbarSize = true; if (ConfigSettings.useHotbarNumberHotkeysConfig.Value) { quickItemShortcutActions = (InputAction[])(object)new InputAction[PlayerPatcher.newHotbarSize]; for (int i = 0; i < quickItemShortcutActions.Length; i++) { quickItemShortcutActions[i] = new InputAction((string)null, (InputActionType)0, $"<Keyboard>/{i + 1}", "Press", (string)null, (string)null); } } if (((Component)localPlayerController).gameObject.activeSelf) { SubscribeToEvents(); } } private static void SubscribeToEvents() { if (quickItemShortcutActions != null && ConfigSettings.useHotbarNumberHotkeysConfig.Value) { for (int i = 0; i < quickItemShortcutActions.Length; i++) { quickItemShortcutActions[i].Enable(); quickItemShortcutActions[i].performed += OnPressItemSlotHotkeyAction; } } } [HarmonyPatch(typeof(PlayerControllerB), "OnEnable")] [HarmonyPostfix] public static void OnEnable(PlayerControllerB __instance) { if ((Object)(object)__instance == (Object)(object)localPlayerController && setHotbarSize) { SubscribeToEvents(); } } [HarmonyPatch(typeof(PlayerControllerB), "OnDisable")] [HarmonyPostfix] public static void OnDisable(PlayerControllerB __instance) { if (quickItemShortcutActions != null && setHotbarSize && (!((Object)(object)localPlayerController != (Object)null) || !((Object)(object)__instance != (Object)(object)localPlayerController))) { for (int i = 0; i < quickItemShortcutActions.Length; i++) { quickItemShortcutActions[i].performed -= OnPressItemSlotHotkeyAction; quickItemShortcutActions[i].Disable(); } } } private static void OnPressItemSlotHotkeyAction(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && localPlayerController.isPlayerControlled && !localPlayerController.inTerminalMenu && !localPlayerController.twoHanded && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject) && ((CallbackContext)(ref context)).performed) { string name = ((CallbackContext)(ref context)).control.name; if (int.TryParse(name, out var result)) { result--; HotbarSlotSync.SwapHotbarSlot(result); } } } } [HarmonyPatch] internal static class HotbarSlotSync { private static PlayerControllerB localPlayerController; [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void Init(PlayerControllerB __instance) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)__instance) { localPlayerController = __instance; NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("HotbarPlus-OnHotbarSlotChangeClientRpc", new HandleNamedMessageDelegate(OnHotbarSlotChangeClientRpc)); if (NetworkManager.Singleton.IsServer) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("HotbarPlus-OnHotbarSlotChangeServerRpc", new HandleNamedMessageDelegate(OnHotbarSlotChangeServerRpc)); } } } private static void SendHotbarSlotChange(int hotbarSlot) { //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_0056: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); try { Plugin.Log("Sending hotbar swap slot: " + hotbarSlot); ((FastBufferWriter)(ref val)).WriteValue<int>(ref hotbarSlot, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("HotbarPlus-OnHotbarSlotChangeServerRpc", 0uL, val, (NetworkDelivery)3); return; } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } Plugin.Log("Failed to send hotbar swap index."); } private static void OnHotbarSlotChangeServerRpc(ulong clientId, FastBufferReader reader) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0082: 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_009e: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(4)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives)); Plugin.Log("Receiving request for hotbar swap. Slot: " + num + " ClientId: " + clientId); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref clientId, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("HotbarPlus-OnHotbarSlotChangeClientRpc", val, (NetworkDelivery)3); return; } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } Plugin.Log("Failed to receive hotbar swap index from Client: " + clientId); } private static void OnHotbarSlotChangeClientRpc(ulong clientId, FastBufferReader reader) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsClient) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(12)) { int hotbarSlot = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref hotbarSlot, default(ForPrimitives)); ulong num = default(ulong); ((FastBufferReader)(ref reader)).ReadValue<ulong>(ref num, default(ForPrimitives)); Plugin.Log("Receiving update for hotbar swap. Slot: " + hotbarSlot + " ClientId: " + num); if (num == localPlayerController.actualClientId || UpdateClientHotbarSlot(num, hotbarSlot)) { return; } Plugin.Log("Failed to receive hotbar swap index from Client: " + num); } Plugin.Log("Failed to receive hotbar swap index from Client"); } private static bool UpdateClientHotbarSlot(ulong clientId, int hotbarSlot) { Plugin.Log("Updating hotbar slot: " + hotbarSlot + " ClientId: " + clientId); for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (StartOfRound.Instance.allPlayerScripts[i].actualClientId == clientId) { CallSwitchToItemSlotMethod(StartOfRound.Instance.allPlayerScripts[i], hotbarSlot); return true; } } return false; } public static void SwapHotbarSlot(int hotbarIndex) { if (hotbarIndex < PlayerPatcher.targetHotbarSize) { SendHotbarSlotChange(hotbarIndex); CallSwitchToItemSlotMethod(localPlayerController, hotbarIndex); } } private static void CallSwitchToItemSlotMethod(PlayerControllerB playerController, int hotbarIndex) { if (hotbarIndex < PlayerPatcher.targetHotbarSize && playerController.currentItemSlot != hotbarIndex) { ShipBuildModeManager.Instance.CancelBuildMode(true); MethodInfo method = ((object)playerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(playerController, new object[2] { hotbarIndex, null }); if ((Object)(object)playerController.currentlyHeldObjectServer != (Object)null) { ((Component)playerController.currentlyHeldObjectServer).gameObject.GetComponent<AudioSource>().PlayOneShot(playerController.currentlyHeldObjectServer.itemProperties.grabSFX, 0.6f); } } } } [BepInPlugin("FlipMods.HotbarPlus", "HotbarPlus", "1.4.6")] public class Plugin : BaseUnityPlugin { public static Plugin instance; private Harmony _harmony; private void Awake() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown instance = this; _harmony = new Harmony("HotbarPlus"); ConfigSettings.BindConfigSettings(); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"HotbarPlus loaded"); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } public static void LogError(string message) { ((BaseUnityPlugin)instance).Logger.LogError((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.HotbarPlus"; public const string PLUGIN_NAME = "HotbarPlus"; public const string PLUGIN_VERSION = "1.4.6"; } } namespace HotbarPlus.Patches { [HarmonyPatch] internal class HUDPatcher { public static float hotbarSlotSize = 40f; public static void ResizeHotbarSlotsHUD() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_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_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) List<Image> list = new List<Image>(HUDManager.Instance.itemSlotIconFrames); List<Image> list2 = new List<Image>(HUDManager.Instance.itemSlotIcons); float num = (hotbarSlotSize + ConfigSettings.overrideHotbarSpacing.Value) * ConfigSettings.overrideHotbarHudSize.Value; float num2 = ((Graphic)list[0]).rectTransform.anchoredPosition.y + 36f * ((ConfigSettings.overrideHotbarHudSize.Value - 1f) / 2f); Vector3 eulerAngles = ((Transform)((Graphic)list[0]).rectTransform).eulerAngles; Vector3 eulerAngles2 = ((Transform)((Graphic)list2[0]).rectTransform).eulerAngles; for (int i = 0; i < Mathf.Max(PlayerPatcher.targetHotbarSize, PlayerPatcher.initialHotbarSize); i++) { if (i >= PlayerPatcher.targetHotbarSize) { Object.Destroy((Object)(object)list[PlayerPatcher.targetHotbarSize]); Object.Destroy((Object)(object)list2[PlayerPatcher.targetHotbarSize]); list.RemoveAt(PlayerPatcher.targetHotbarSize); list2.RemoveAt(PlayerPatcher.targetHotbarSize); continue; } if (i >= PlayerPatcher.initialHotbarSize) { list.Insert(i, Object.Instantiate<Image>(list[i - 1], ((Component)list[0]).transform.parent)); ((Component)list[i]).transform.SetSiblingIndex(((Component)list[i - 1]).transform.GetSiblingIndex() + 1); list2.Insert(i, ((Component)((Component)list[i]).transform.GetChild(0)).GetComponent<Image>()); } ((Object)list[i]).name = $"Slot{i}"; ((Graphic)list[i]).rectTransform.anchoredPosition = Vector2.up * num2; ((Transform)((Graphic)list[i]).rectTransform).eulerAngles = eulerAngles; ((Object)list2[i]).name = "Icon"; ((Transform)((Graphic)list2[i]).rectTransform).eulerAngles = eulerAngles2; } float num3 = num * (float)(PlayerPatcher.targetHotbarSize - 1); float num4 = num3 / 2f; for (int j = 0; j < PlayerPatcher.targetHotbarSize; j++) { float num5 = (float)j * num - num4; ((Graphic)list[j]).rectTransform.anchoredPosition = new Vector2(num5, num2); RectTransform rectTransform = ((Graphic)list[j]).rectTransform; rectTransform.sizeDelta *= ConfigSettings.overrideHotbarHudSize.Value; RectTransform rectTransform2 = ((Graphic)list2[j]).rectTransform; rectTransform2.sizeDelta *= ConfigSettings.overrideHotbarHudSize.Value; } HUDManager.Instance.itemSlotIconFrames = list.ToArray(); HUDManager.Instance.itemSlotIcons = list2.ToArray(); } [HarmonyPatch(typeof(HUDManager), "PingHUDElement")] [HarmonyPrefix] public static void PingHUDElement(HUDElement element, ref float startAlpha, ref float endAlpha, HUDManager __instance) { if (element != __instance.Inventory || endAlpha != 0.13f) { return; } if (startAlpha == 0.13f && StartOfRound.Instance.localPlayerController.twoHanded) { endAlpha = 1f; return; } endAlpha = Mathf.Clamp(ConfigSettings.overrideFadeHudAlpha.Value, 0f, 1f); if (startAlpha == 0.13f) { startAlpha = endAlpha; } } } [HarmonyPatch] public class PlayerPatcher { public static PlayerControllerB localPlayerController; public static int initialHotbarSize = -1; public static int postInitialHotbarSize = -1; public static int targetHotbarSize = -1; public static int newHotbarSize = -1; private static bool droppingItem = false; [HarmonyPatch(typeof(PlayerControllerB), "Awake")] [HarmonyPostfix] public static void GetInitialHotbarSize(PlayerControllerB __instance) { if (initialHotbarSize == -1) { initialHotbarSize = __instance.ItemSlots.Length; } } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void InitializeLocalPlayer(PlayerControllerB __instance) { localPlayerController = __instance; } public static void ResizeInventory() { postInitialHotbarSize = localPlayerController.ItemSlots.Length; targetHotbarSize = Mathf.Clamp(ConfigSync.instance.hotbarSize, 0, 10); newHotbarSize = Mathf.Clamp(ConfigSync.instance.hotbarSize + (postInitialHotbarSize - initialHotbarSize), 0, 10); for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i]; val.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[newHotbarSize]; } } private static int CallGetNextItemSlot(PlayerControllerB __instance, bool forward, int index) { int currentItemSlot = __instance.currentItemSlot; __instance.currentItemSlot = index; MethodInfo method = ((object)__instance).GetType().GetMethod("NextItemSlot", BindingFlags.Instance | BindingFlags.NonPublic); index = (int)method.Invoke(__instance, new object[1] { forward }); __instance.currentItemSlot = currentItemSlot; return index; } private static void CallSwitchToItemSlot(PlayerControllerB __instance, int index) { MethodInfo method = ((object)__instance).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic); index = (int)method.Invoke(__instance, new object[2] { index, null }); } [HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchSwitchItemInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); if (!ConfigSettings.disableFasterHotbarSwapping.Value) { for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.3f) { list[i].operand = ConfigSettings.minSwapItemInterval; break; } } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "ActivateItem_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchActivateItemInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); if (!ConfigSettings.disableFasterItemActivate.Value) { for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.075f) { list[i].operand = ConfigSettings.minActivateItemInterval; break; } } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "Discard_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchDiscardItemInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); if (!ConfigSettings.disableFasterItemDropping.Value) { for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.2f) { list[i].operand = ConfigSettings.minDiscardItemInterval; } } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "Interact_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchInteractInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.2f) { list[i].operand = ConfigSettings.minInteractInterval; break; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> PatchPerformEmoteInterval(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4 && (float)list[i].operand == 0.5f) { list[i].operand = ConfigSettings.minUseEmoteInterval; break; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> InvertHotbarScrollDirection(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); if (ConfigSettings.invertHotbarScrollDirectionConfig.Value) { for (int i = 1; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ble_Un && list[i - 1].opcode == OpCodes.Ldc_R4 && (float)list[i - 1].operand == 0f) { list[i].opcode = OpCodes.Bge_Un; break; } } } return list.AsEnumerable(); } } } namespace HotbarPlus.Config { public static class ConfigSettings { public static ConfigEntry<int> hotbarSizeConfig; public static ConfigEntry<bool> useHotbarNumberHotkeysConfig; public static ConfigEntry<bool> invertHotbarScrollDirectionConfig; public static ConfigEntry<float> overrideHotbarSpacing; public static ConfigEntry<float> overrideFadeHudAlpha; public static ConfigEntry<float> overrideHotbarHudSize; public static ConfigEntry<bool> useItemQuickDropConfig; public static ConfigEntry<bool> useOriginalKeybindsDefaultEmotes; public static ConfigEntry<string> rebindEmote1Config; public static ConfigEntry<string> rebindEmote2Config; public static ConfigEntry<bool> disableFasterHotbarSwapping; public static ConfigEntry<bool> disableFasterItemDropping; public static ConfigEntry<bool> disableFasterItemActivate; public static string[] currentEntryHeaders = new string[2] { "Server-side", "Client-side" }; public static string[] currentEntryNames = new string[7] { "HotbarSize", "UseHotbarNumberHotkeys", "InvertHotbarScrollDirection", "UseItemQuickDropConfig", "RebindDefaultEmotes", "RebindEmote1", "RebindEmote2" }; public static float minSwapItemInterval = 0.05f; public static float minActivateItemInterval = 0.05f; public static float minDiscardItemInterval = 0.05f; public static float minInteractInterval = 0.05f; public static float minUseEmoteInterval = 0.25f; public static List<ConfigEntryBase> configEntries = new List<ConfigEntryBase>(); public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); hotbarSizeConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Server-side", "HotbarSize", 4, "[Host only] The amount of hotbar slots player will have. This will sync with other clients who have the mod."); useHotbarNumberHotkeysConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseHotbarNumberHotkeys", true, "Use the quick item selection numerical hotkeys."); invertHotbarScrollDirectionConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "InvertHotbarScrollDirection", true, "Inverts the direction in which you scroll on the hotbar. Will not affect the terminal scrolling direction."); overrideHotbarSpacing = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Client-side", "OverrideHotbarHudSpacing", 10f, "The spacing between each hotbar slot UI element. Not recommended to go below 0... But no one is stopping you."); overrideFadeHudAlpha = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Client-side", "OverrideFadeHudAlpha", 0.13f, "Sets the alpha for when the hotbar hud fades. Default = 0.13 | Fade completely: 0 | Never fade: 1"); overrideHotbarHudSize = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Client-side", "OverrideHotbarHudSize", 1f, "Scales the hotbar slot HUD elements by a multiplier. HUD spacing and position will be scaled/adjusted automatically."); useItemQuickDropConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseItemQuickDropConfig", true, "If enabled, dropping an item will automatically swap to the next item for easier chain dropping."); useOriginalKeybindsDefaultEmotes = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseOriginalKeybindsDefaultEmotes", false, "If false, the default emotes will be rebound by this mod."); rebindEmote1Config = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Client-side", "RebindEmote1", "<Keyboard>/f1", "Sets the new keybind for the default emote 1, if RebindDefaultEmotes is true."); rebindEmote2Config = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Client-side", "RebindEmote2", "<Keyboard>/f2", "Sets the new keybind for the default emote 2, if RebindDefaultEmotes is true."); disableFasterHotbarSwapping = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseDefaultItemSwapInterval", false, "If true, the interval (delay) between swapping items will not be reduced by this mod."); disableFasterItemDropping = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseDefaultItemDropInterval", false, "If true, the interval (delay) between dropping items will not be reduced by this mod."); disableFasterItemActivate = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Client-side", "UseDefaultItemActivateInterval", false, "If true, the interval (delay) between activating items will not be reduced by this mod."); ((BaseUnityPlugin)Plugin.instance).Config.Reload(); RemoveOldConfigs(); ConfigSync.BuildDefaultConfig(); } public static void RemoveOldConfigs() { try { ConfigFile config = ((BaseUnityPlugin)Plugin.instance).Config; string configFilePath = config.ConfigFilePath; if (!File.Exists(configFilePath)) { return; } List<string> list = File.ReadAllLines(configFilePath).ToList(); List<string> list2 = new List<string>(); bool flag = false; bool flag2 = false; foreach (string item in list) { if (item.Length <= 0) { if (list2[list2.Count - 1].Length > 0) { list2.Add(item); } flag2 = true; continue; } if (item.StartsWith("[")) { string value = item.Trim(new char[1] { '[' }).Trim(new char[1] { ']' }); if (currentEntryHeaders.Contains(value)) { list2.Add(item); } } else if (!flag2 || item.StartsWith("#")) { list2.Add(item); } flag2 = false; } File.WriteAllLines(configFilePath, list2); config.Reload(); } catch { } } } [HarmonyPatch] public class ConfigSync { public static ConfigSync defaultConfig; public static ConfigSync instance; public static PlayerControllerB localPlayerController; public static bool isSynced; public int hotbarSize = 4; public ConfigSync() { hotbarSize = ConfigSettings.hotbarSizeConfig.Value; } public static void BuildDefaultConfig() { defaultConfig = new ConfigSync(); instance = new ConfigSync(); } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void InitializeLocalPlayer(PlayerControllerB __instance) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown localPlayerController = __instance; if (NetworkManager.Singleton.IsServer) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("HotbarPlusOnRequestConfigSync", new HandleNamedMessageDelegate(OnReceiveConfigSyncRequest)); OnLocalClientConfigSync(); return; } instance.hotbarSize = 4; isSynced = false; NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("HotbarPlusOnReceiveConfigSync", new HandleNamedMessageDelegate(OnReceiveConfigSync)); RequestConfigSync(); } public static void RequestConfigSync() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { Plugin.Log("Sending config sync request to server."); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("HotbarPlusOnRequestConfigSync", 0uL, new FastBufferWriter(0, (Allocator)2, -1), (NetworkDelivery)3); } else { Plugin.LogError("Failed to send config sync request."); } } public static void OnReceiveConfigSyncRequest(ulong clientId, FastBufferReader reader) { //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_0065: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsServer) { Plugin.Log("Receiving hotbar size sync request from client with id: " + clientId + ". Sending config sync to client."); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref instance.hotbarSize, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("HotbarPlusOnReceiveConfigSync", clientId, val, (NetworkDelivery)3); } } public static void OnReceiveConfigSync(ulong clientId, FastBufferReader reader) { //IL_001f: 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) if (((FastBufferReader)(ref reader)).TryBeginRead(4)) { Plugin.Log("Receiving hotbar size sync from server."); int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); instance.hotbarSize = num; OnLocalClientConfigSync(); } else { Plugin.LogError("Error receiving config sync from server."); } } public static void OnLocalClientConfigSync() { isSynced = true; PlayerPatcher.ResizeInventory(); HUDPatcher.ResizeHotbarSlotsHUD(); Keybinds.OnSetHotbarSize(); } } }
plugins/LC_API.dll
Decompiled a year agousing System; using System.Collections.Concurrent; 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.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LC_API.BundleAPI; using LC_API.ClientAPI; using LC_API.Comp; using LC_API.Data; using LC_API.Extensions; using LC_API.GameInterfaceAPI; using LC_API.ManualPatches; using LC_API.ServerAPI; using Microsoft.CodeAnalysis; using Steamworks; using Steamworks.Data; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.InputSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")] [assembly: AssemblyCompany("LC_API")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Utilities for plugin devs")] [assembly: AssemblyFileVersion("2.1.4.0")] [assembly: AssemblyInformationalVersion("2.1.4")] [assembly: AssemblyProduct("LC_API")] [assembly: AssemblyTitle("LC_API")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.1.4.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 LC_API { internal static class CheatDatabase { private const string DAT_CD_BROADCAST = "LC_API_CD_Broadcast"; private const string SIG_REQ_GUID = "LC_API_ReqGUID"; private const string SIG_SEND_MODS = "LC_APISendMods"; private static Dictionary<string, PluginInfo> PluginsLoaded = new Dictionary<string, PluginInfo>(); public static void RunLocalCheatDetector() { PluginsLoaded = Chainloader.PluginInfos; using Dictionary<string, PluginInfo>.ValueCollection.Enumerator enumerator = PluginsLoaded.Values.GetEnumerator(); while (enumerator.MoveNext()) { switch (enumerator.Current.Metadata.GUID) { case "mikes.lethalcompany.mikestweaks": case "mom.llama.enhancer": case "Posiedon.GameMaster": case "LethalCompanyScalingMaster": case "verity.amberalert": ModdedServer.SetServerModdedOnly(); break; } } } public static void OtherPlayerCheatDetector() { Plugin.Log.LogWarning((object)"Asking all other players for their mod list.."); GameTips.ShowTip("Mod List:", "Asking all other players for installed mods.."); GameTips.ShowTip("Mod List:", "Check the logs for more detailed results.\n<size=13>(Note that if someone doesnt show up on the list, they may not have LC_API installed)</size>"); Networking.Broadcast("LC_API_CD_Broadcast", "LC_API_ReqGUID"); } internal static void CDNetGetString(string data, string signature) { if (data == "LC_API_CD_Broadcast" && signature == "LC_API_ReqGUID") { string text = ""; foreach (PluginInfo value in PluginsLoaded.Values) { text = text + "\n" + value.Metadata.GUID; } Networking.Broadcast(GameNetworkManager.Instance.localPlayerController.playerUsername + " responded with these mods:" + text, "LC_APISendMods"); } if (signature == "LC_APISendMods") { GameTips.ShowTip("Mod List:", data); Plugin.Log.LogWarning((object)data); } } } [BepInPlugin("LC_API", "LC_API", "2.1.4")] public sealed class Plugin : BaseUnityPlugin { internal static ManualLogSource Log; private ConfigEntry<bool> configOverrideModServer; private ConfigEntry<bool> configLegacyAssetLoading; private ConfigEntry<bool> configDisableBundleLoader; public static bool Initialized { get; private set; } private void Awake() { //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Expected O, but got Unknown //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Expected O, but got Unknown //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Expected O, but got Unknown //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown configOverrideModServer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Force modded server browser", false, "Should the API force you into the modded server browser?"); configLegacyAssetLoading = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Legacy asset bundle loading", false, "Should the BundleLoader use legacy asset loading? Turning this on may help with loading assets from older plugins."); configDisableBundleLoader = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Disable BundleLoader", false, "Should the BundleLoader be turned off? Enable this if you are having problems with mods that load assets using a different method from LC_API's BundleLoader."); CommandHandler.commandPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Prefix", "/", "Command prefix"); Log = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogWarning((object)"\n.____ _________ _____ __________ .___ \r\n| | \\_ ___ \\ / _ \\ \\______ \\| | \r\n| | / \\ \\/ / /_\\ \\ | ___/| | \r\n| |___\\ \\____ / | \\| | | | \r\n|_______ \\\\______ /______\\____|__ /|____| |___| \r\n \\/ \\//_____/ \\/ \r\n "); ((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Starting up.."); if (configOverrideModServer.Value) { ModdedServer.SetServerModdedOnly(); } Harmony val = new Harmony("ModAPI"); MethodInfo methodInfo = AccessTools.Method(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated", (Type[])null, (Type[])null); AccessTools.Method(typeof(GameNetworkManager), "LobbyDataIsJoinable", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerPatch), "OnLobbyCreate", (Type[])null, (Type[])null); MethodInfo methodInfo3 = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null); MethodInfo methodInfo4 = AccessTools.Method(typeof(ServerPatch), "CacheMenuManager", (Type[])null, (Type[])null); MethodInfo methodInfo5 = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null); MethodInfo methodInfo6 = AccessTools.Method(typeof(ServerPatch), "ChatInterpreter", (Type[])null, (Type[])null); MethodInfo methodInfo7 = AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null); MethodInfo methodInfo8 = AccessTools.Method(typeof(CommandHandler.SubmitChatPatch), "Transpiler", (Type[])null, (Type[])null); val.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)methodInfo5, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null); Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, new Action<string, string>(CheatDatabase.CDNetGetString)); Networking.GetListString = (Action<List<string>, string>)Delegate.Combine(Networking.GetListString, new Action<List<string>, string>(Networking.LCAPI_NET_SYNCVAR_SET)); } internal void Start() { Initialize(); } internal void OnDestroy() { Initialize(); } internal void Initialize() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown if (!Initialized) { Initialized = true; if (!configDisableBundleLoader.Value) { BundleLoader.Load(configLegacyAssetLoading.Value); } GameObject val = new GameObject("API"); Object.DontDestroyOnLoad((Object)val); val.AddComponent<LC_APIManager>(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Started!"); CheatDatabase.RunLocalCheatDetector(); } } internal static void PatchMethodManual(MethodInfo method, MethodInfo patch, Harmony harmony) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown harmony.Patch((MethodBase)method, new HarmonyMethod(patch), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "LC_API"; public const string PLUGIN_NAME = "LC_API"; public const string PLUGIN_VERSION = "2.1.4"; } } namespace LC_API.ServerAPI { public static class ModdedServer { private static bool moddedOnly; [Obsolete("Use SetServerModdedOnly() instead. This will be removed/private in a future update.")] public static bool setModdedOnly; public static bool ModdedOnly => moddedOnly; public static void SetServerModdedOnly() { moddedOnly = true; Plugin.Log.LogMessage((object)"A plugin has set your game to only allow you to play with other people who have mods!"); } public static void OnSceneLoaded() { if (Object.op_Implicit((Object)(object)GameNetworkManager.Instance) && ModdedOnly) { GameNetworkManager instance = GameNetworkManager.Instance; instance.gameVersionNum += 16440; setModdedOnly = true; } } } public static class Networking { public static Action<string, string> GetString = delegate { }; public static Action<List<string>, string> GetListString = delegate { }; public static Action<int, string> GetInt = delegate { }; public static Action<float, string> GetFloat = delegate { }; public static Action<Vector3, string> GetVector3 = delegate { }; private static Dictionary<string, string> syncStringVars = new Dictionary<string, string>(); public static void Broadcast(string data, string signature) { if (data.Contains("/")) { Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )"); return; } HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDstring.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1); } public static void Broadcast(List<string> data, string signature) { string text = ""; foreach (string datum in data) { if (datum.Contains("/")) { Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )"); return; } if (datum.Contains("\n")) { Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( NewLine )"); return; } text = text + datum + "\n"; } HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data?.ToString() + "/" + signature + "/" + NetworkBroadcastDataType.BDlistString.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1); } public static void Broadcast(int data, string signature) { HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDint.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1); } public static void Broadcast(float data, string signature) { HUDManager.Instance.AddTextToChatOnServer("<size=0>NWE/" + data + "/" + signature + "/" + NetworkBroadcastDataType.BDfloat.ToString() + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1); } public static void Broadcast(Vector3 data, string signature) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) HUDManager instance = HUDManager.Instance; string[] obj = new string[9] { "<size=0>NWE/", null, null, null, null, null, null, null, null }; Vector3 val = data; obj[1] = ((object)(Vector3)(ref val)).ToString(); obj[2] = "/"; obj[3] = signature; obj[4] = "/"; obj[5] = NetworkBroadcastDataType.BDvector3.ToString(); obj[6] = "/"; obj[7] = GameNetworkManager.Instance.localPlayerController.playerClientId.ToString(); obj[8] = "/</size>"; instance.AddTextToChatOnServer(string.Concat(obj), -1); } public static void RegisterSyncVariable(string name) { if (!syncStringVars.ContainsKey(name)) { syncStringVars.Add(name, ""); } else { Plugin.Log.LogError((object)("Cannot register Sync Variable! A Sync Variable has already been registered with name " + name)); } } public static void SetSyncVariable(string name, string value) { if (syncStringVars.ContainsKey(name)) { syncStringVars[name] = value; Broadcast(new List<string> { name, value }, "LCAPI_NET_SYNCVAR_SET"); } else { Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!")); } } private static void SetSyncVariableB(string name, string value) { if (syncStringVars.ContainsKey(name)) { syncStringVars[name] = value; } else { Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!")); } } internal static void LCAPI_NET_SYNCVAR_SET(List<string> list, string arg2) { if (arg2 == "LCAPI_NET_SYNCVAR_SET") { SetSyncVariableB(list[0], list[1]); } } public static string GetSyncVariable(string name) { if (syncStringVars.ContainsKey(name)) { return syncStringVars[name]; } Plugin.Log.LogError((object)("Cannot get the value of Sync Variable " + name + " as it is not registered!")); return ""; } private static void GotString(string data, string signature) { } private static void GotInt(int data, string signature) { } private static void GotFloat(float data, string signature) { } private static void GotVector3(Vector3 data, string signature) { } } } namespace LC_API.ManualPatches { internal static class ServerPatch { internal static bool OnLobbyCreate(GameNetworkManager __instance, Result result, Lobby lobby) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0009: Unknown result type (might be due to invalid IL or missing references) if ((int)result != 1) { Debug.LogError((object)$"Lobby could not be created! {result}", (Object)(object)__instance); } __instance.lobbyHostSettings.lobbyName = "[MODDED]" + __instance.lobbyHostSettings.lobbyName.ToString(); Plugin.Log.LogMessage((object)"server pre-setup success"); return true; } internal static bool CacheMenuManager(MenuManager __instance) { LC_APIManager.MenuManager = __instance; return true; } internal static bool ChatInterpreter(HUDManager __instance, string chatMessage) { //IL_0312: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) if (!chatMessage.Contains("NWE") || !chatMessage.Contains("<size=0>")) { return true; } string[] array = chatMessage.Split(new char[1] { '/' }); if (array.Length < 5) { if (array.Length >= 3) { if (!int.TryParse(array[4], out var result)) { Plugin.Log.LogWarning((object)"Failed to parse player ID!!"); return false; } if ((result == (int)GameNetworkManager.Instance.localPlayerController.playerClientId) & !LC_APIManager.netTester) { return false; } Enum.TryParse<NetworkBroadcastDataType>(array[3], out var result2); switch (result2) { case NetworkBroadcastDataType.BDstring: Networking.GetString(array[1], array[2]); break; case NetworkBroadcastDataType.BDint: Networking.GetInt(int.Parse(array[1]), array[2]); break; case NetworkBroadcastDataType.BDfloat: Networking.GetFloat(float.Parse(array[1]), array[2]); break; case NetworkBroadcastDataType.BDvector3: { string[] array2 = array[1].Replace("(", "").Replace(")", "").Split(new char[1] { ',' }); Vector3 arg = default(Vector3); if (array2.Length == 3) { if (float.TryParse(array2[0], out var result3) && float.TryParse(array2[1], out var result4) && float.TryParse(array2[2], out var result5)) { arg.x = result3; arg.y = result4; arg.z = result5; } else { Plugin.Log.LogError((object)"Vector3 Network receive fail. This is a failure of the API, and it should be reported as a bug."); } } else { Plugin.Log.LogError((object)"Vector3 Network receive fail. This is a failure of the API, and it should be reported as a bug."); } Networking.GetVector3(arg, array[2]); break; } case NetworkBroadcastDataType.BDlistString: { string[] source = array[1].Split(new char[1] { '\n' }); Networking.GetListString(source.ToList(), array[2]); break; } } _ = LC_APIManager.netTester; return false; } Plugin.Log.LogError((object)"Generic Network receive fail. This is a failure of the API, and it should be reported as a bug."); Plugin.Log.LogError((object)$"Generic Network receive fail (expected 5+ data fragments, got {array.Length}). This is a failure of the API, and it should be reported as a bug."); return true; } if (!int.TryParse(array[4], out var result6)) { Plugin.Log.LogWarning((object)("Failed to parse player ID '" + array[4] + "'!!")); return false; } if ((result6 == (int)GameNetworkManager.Instance.localPlayerController.playerClientId) & !LC_APIManager.netTester) { return false; } if (!Enum.TryParse<NetworkBroadcastDataType>(array[3], out var result7)) { Plugin.Log.LogError((object)("Unknown datatype - unable to parse '" + array[3] + "' into a known data type!")); return false; } switch (result7) { case NetworkBroadcastDataType.BDstring: Networking.GetString.InvokeActionSafe(array[1], array[2]); break; case NetworkBroadcastDataType.BDint: Networking.GetInt.InvokeActionSafe(int.Parse(array[1]), array[2]); break; case NetworkBroadcastDataType.BDfloat: Networking.GetFloat.InvokeActionSafe(float.Parse(array[1]), array[2]); break; case NetworkBroadcastDataType.BDvector3: { string text = array[1].Trim('(', ')'); string[] array3 = text.Split(new char[1] { ',' }); Vector3 param = default(Vector3); float result8; float result9; float result10; if (array3.Length != 3) { Plugin.Log.LogError((object)$"Vector3 Network receive fail (expected 3 numbers, got {array3.Length} number(?)(s) instead). This is a failure of the API, and it should be reported as a bug. (passing an empty Vector3 in its place)"); } else if (float.TryParse(array3[0], out result8) && float.TryParse(array3[1], out result9) && float.TryParse(array3[2], out result10)) { param.x = result8; param.y = result9; param.z = result10; } else { Plugin.Log.LogError((object)("Vector3 Network receive fail (failed to parse '" + text + "' as numbers). This is a failure of the API, and it should be reported as a bug.")); } Networking.GetVector3.InvokeActionSafe(param, array[2]); break; } } _ = LC_APIManager.netTester; return false; } internal static bool ChatCommands(HUDManager __instance, CallbackContext context) { if (__instance.chatTextField.text.ToLower().Contains("/modcheck")) { CheatDatabase.OtherPlayerCheatDetector(); return false; } return true; } } } namespace LC_API.GameInterfaceAPI { public static class GameState { private static readonly Action NothingAction = delegate { }; public static int AlivePlayerCount { get; private set; } public static ShipState ShipState { get; private set; } public static event Action PlayerDied; public static event Action LandOnMoon; public static event Action WentIntoOrbit; public static event Action ShipStartedLeaving; internal static void GSUpdate() { if (!((Object)(object)StartOfRound.Instance == (Object)null)) { if (StartOfRound.Instance.shipHasLanded && ShipState != ShipState.OnMoon) { ShipState = ShipState.OnMoon; GameState.LandOnMoon.InvokeActionSafe(); } if (StartOfRound.Instance.inShipPhase && ShipState != 0) { ShipState = ShipState.InOrbit; GameState.WentIntoOrbit.InvokeActionSafe(); } if (StartOfRound.Instance.shipIsLeaving && ShipState != ShipState.LeavingMoon) { ShipState = ShipState.LeavingMoon; GameState.ShipStartedLeaving.InvokeActionSafe(); } if (AlivePlayerCount < StartOfRound.Instance.livingPlayers) { GameState.PlayerDied.InvokeActionSafe(); } AlivePlayerCount = StartOfRound.Instance.livingPlayers; } } static GameState() { GameState.PlayerDied = NothingAction; GameState.LandOnMoon = NothingAction; GameState.WentIntoOrbit = NothingAction; GameState.ShipStartedLeaving = NothingAction; } } public class GameTips { private static List<string> tipHeaders = new List<string>(); private static List<string> tipBodys = new List<string>(); private static float lastMessageTime; public static void ShowTip(string header, string body) { tipHeaders.Add(header); tipBodys.Add(body); } public static void UpdateInternal() { lastMessageTime -= Time.deltaTime; if ((tipHeaders.Count > 0) & (lastMessageTime < 0f)) { lastMessageTime = 5f; if ((Object)(object)HUDManager.Instance != (Object)null) { HUDManager.Instance.DisplayTip(tipHeaders[0], tipBodys[0], false, false, "LC_Tip1"); } tipHeaders.RemoveAt(0); tipBodys.RemoveAt(0); } } } } namespace LC_API.Extensions { public static class DelegateExtensions { private static readonly PropertyInfo PluginGetLogger = AccessTools.Property(typeof(BaseUnityPlugin), "Logger"); public static void InvokeActionSafe(this Action action) { //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (action == null) { return; } Delegate[] invocationList = action.GetInvocationList(); foreach (Delegate @delegate in invocationList) { try { ((Action)@delegate)(); } catch (Exception ex) { Plugin.Log.LogError((object)"Exception while invoking hook callback!"); string asmName = @delegate.GetMethodInfo().DeclaringType.Assembly.FullName; PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo pi) => ((object)pi.Instance).GetType().Assembly.FullName == asmName)); if (val == null) { Plugin.Log.LogError((object)ex.ToString()); break; } ((ManualLogSource)PluginGetLogger.GetValue(val.Instance)).LogError((object)ex.ToString()); } } } public static void InvokeActionSafe<T>(this Action<T> action, T param) { //IL_009f: Unknown result type (might be due to invalid IL or missing references) if (action == null) { return; } Delegate[] invocationList = action.GetInvocationList(); foreach (Delegate @delegate in invocationList) { try { ((Action<T>)@delegate)(param); } catch (Exception ex) { Plugin.Log.LogError((object)"Exception while invoking hook callback!"); string asmName = @delegate.GetMethodInfo().DeclaringType.Assembly.FullName; PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo pi) => ((object)pi.Instance).GetType().Assembly.FullName == asmName)); if (val == null) { Plugin.Log.LogError((object)ex.ToString()); break; } ((ManualLogSource)PluginGetLogger.GetValue(val.Instance)).LogError((object)ex.ToString()); } } } public static void InvokeActionSafe<T1, T2>(this Action<T1, T2> action, T1 param1, T2 param2) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) if (action == null) { return; } Delegate[] invocationList = action.GetInvocationList(); foreach (Delegate @delegate in invocationList) { try { ((Action<T1, T2>)@delegate)(param1, param2); } catch (Exception ex) { Plugin.Log.LogError((object)"Exception while invoking hook callback!"); string asmName = @delegate.GetMethodInfo().DeclaringType.Assembly.FullName; PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo pi) => ((object)pi.Instance).GetType().Assembly.FullName == asmName)); if (val == null) { Plugin.Log.LogError((object)ex.ToString()); break; } ((ManualLogSource)PluginGetLogger.GetValue(val.Instance)).LogError((object)ex.ToString()); } } } internal static void InvokeParameterlessDelegate<T>(this T paramlessDelegate) where T : Delegate { //IL_00b9: Unknown result type (might be due to invalid IL or missing references) if ((Delegate?)paramlessDelegate == (Delegate?)null) { return; } Delegate[] invocationList = paramlessDelegate.GetInvocationList(); foreach (Delegate @delegate in invocationList) { try { ((T)@delegate).DynamicInvoke(); } catch (Exception ex) { Plugin.Log.LogError((object)"Exception while invoking hook callback!"); string asmName = @delegate.GetMethodInfo().DeclaringType.Assembly.FullName; PluginInfo val = ((IEnumerable<PluginInfo>)Chainloader.PluginInfos.Values).FirstOrDefault((Func<PluginInfo, bool>)((PluginInfo pi) => ((object)pi.Instance).GetType().Assembly.FullName == asmName)); if (val == null) { Plugin.Log.LogError((object)ex.ToString()); break; } ((ManualLogSource)PluginGetLogger.GetValue(val.Instance)).LogError((object)ex.ToString()); } } } } } namespace LC_API.Data { internal enum NetworkBroadcastDataType { Unknown, BDint, BDfloat, BDvector3, BDstring, BDlistString } public enum ShipState { InOrbit, OnMoon, LeavingMoon } } namespace LC_API.Comp { internal class LC_APIManager : MonoBehaviour { public static MenuManager MenuManager; public static bool netTester; private static int playerCount; private static bool wanttoCheckMods; private static float lobbychecktimer; public void Update() { GameState.GSUpdate(); GameTips.UpdateInternal(); if ((((Object)(object)HUDManager.Instance != (Object)null) & netTester) && (Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null) { Networking.Broadcast("testerData", "testerSignature"); } if (!ModdedServer.setModdedOnly) { ModdedServer.OnSceneLoaded(); } else if (ModdedServer.ModdedOnly && (Object)(object)MenuManager != (Object)null && Object.op_Implicit((Object)(object)MenuManager.versionNumberText)) { ((TMP_Text)MenuManager.versionNumberText).text = $"v{GameNetworkManager.Instance.gameVersionNum - 16440}\nMOD"; } if ((Object)(object)GameNetworkManager.Instance != (Object)null) { if (playerCount < GameNetworkManager.Instance.connectedPlayers) { lobbychecktimer = -4.5f; wanttoCheckMods = true; } playerCount = GameNetworkManager.Instance.connectedPlayers; } if (lobbychecktimer < 0f) { lobbychecktimer += Time.deltaTime; } else if (wanttoCheckMods && (Object)(object)HUDManager.Instance != (Object)null) { wanttoCheckMods = false; CD(); } } private void CD() { CheatDatabase.OtherPlayerCheatDetector(); } } } namespace LC_API.ClientAPI { public static class CommandHandler { internal static class SubmitChatPatch { private static bool HandleMessage(HUDManager manager) { string text = manager.chatTextField.text; if (!Utility.IsNullOrWhiteSpace(text) && text.StartsWith(commandPrefix.Value)) { string[] array = text.Split(new char[1] { ' ' }); string text2 = array[0].Substring(commandPrefix.Value.Length); if (TryGetCommandHandler(text2, out var handler)) { string[] obj = array.Skip(1).ToArray(); try { handler(obj); } catch (Exception ex) { Plugin.Log.LogError((object)("Error handling command: " + text2)); Plugin.Log.LogError((object)ex); } } manager.localPlayer.isTypingChat = false; manager.chatTextField.text = ""; EventSystem.current.SetSelectedGameObject((GameObject)null); ((Behaviour)manager.typingIndicator).enabled = false; return true; } return false; } internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { List<CodeInstruction> newInstructions = new List<CodeInstruction>(instructions); Label label = generator.DefineLabel(); newInstructions[newInstructions.Count - 1].labels.Add(label); int index = newInstructions.FindIndex((CodeInstruction i) => i.opcode == OpCodes.Ldfld && (FieldInfo)i.operand == AccessTools.Field(typeof(PlayerControllerB), "isPlayerDead")) - 2; newInstructions.InsertRange(index, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3] { CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), newInstructions[index]), new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(SubmitChatPatch), "HandleMessage", (Type[])null, (Type[])null)), new CodeInstruction(OpCodes.Brtrue, (object)label) }); for (int z = 0; z < newInstructions.Count; z++) { yield return newInstructions[z]; } } } internal static ConfigEntry<string> commandPrefix; internal static Dictionary<string, Action<string[]>> CommandHandlers = new Dictionary<string, Action<string[]>>(); internal static Dictionary<string, List<string>> CommandAliases = new Dictionary<string, List<string>>(); public static bool RegisterCommand(string command, Action<string[]> handler) { if (command.Contains(" ") || CommandHandlers.ContainsKey(command)) { return false; } CommandHandlers.Add(command, handler); return true; } public static bool RegisterCommand(string command, List<string> aliases, Action<string[]> handler) { if (command.Contains(" ") || GetCommandHandler(command) != null) { return false; } foreach (string alias in aliases) { if (alias.Contains(" ") || GetCommandHandler(alias) != null) { return false; } } CommandHandlers.Add(command, handler); CommandAliases.Add(command, aliases); return true; } public static bool UnregisterCommand(string command) { CommandAliases.Remove(command); return CommandHandlers.Remove(command); } internal static Action<string[]> GetCommandHandler(string command) { if (CommandHandlers.TryGetValue(command, out var value)) { return value; } foreach (KeyValuePair<string, List<string>> commandAlias in CommandAliases) { if (commandAlias.Value.Contains(command)) { return CommandHandlers[commandAlias.Key]; } } return null; } internal static bool TryGetCommandHandler(string command, out Action<string[]> handler) { handler = GetCommandHandler(command); return handler != null; } } } namespace LC_API.BundleAPI { public static class BundleLoader { [Obsolete("Use OnLoadedBundles instead. This will be removed/private in a future update.")] public delegate void OnLoadedAssetsDelegate(); [Obsolete("Use GetLoadedAsset instead. This will be removed/private in a future update.")] public static ConcurrentDictionary<string, Object> assets = new ConcurrentDictionary<string, Object>(); [Obsolete("Use OnLoadedBundles instead. This will be removed/private in a future update.")] public static OnLoadedAssetsDelegate OnLoadedAssets = LoadAssetsCompleted; public static bool AssetsInLegacyDirectory { get; private set; } public static bool LegacyLoadingEnabled { get; private set; } public static event Action OnLoadedBundles; internal static void Load(bool legacyLoading) { LegacyLoadingEnabled = legacyLoading; Plugin.Log.LogMessage((object)"BundleAPI will now load all asset bundles..."); string path = Path.Combine(Paths.BepInExRootPath, "Bundles"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); Plugin.Log.LogMessage((object)"BundleAPI Created legacy bundle directory in BepInEx/Bundles"); } string[] array = (from x in Directory.GetFiles(path, "*", SearchOption.AllDirectories) where !x.EndsWith(".manifest", StringComparison.CurrentCultureIgnoreCase) select x).ToArray(); AssetsInLegacyDirectory = array.Length != 0; if (!AssetsInLegacyDirectory) { Plugin.Log.LogMessage((object)"BundleAPI got no assets to load from legacy directory"); } if (AssetsInLegacyDirectory) { Plugin.Log.LogWarning((object)"The path BepInEx > Bundles is outdated and should not be used anymore! Bundles will be loaded from BepInEx > plugins from now on"); LoadAllAssetsFromDirectory(array, legacyLoading); } string[] invalidEndings = new string[8] { ".dll", ".json", ".png", ".md", ".old", ".txt", ".exe", ".lem" }; path = Path.Combine(Paths.BepInExRootPath, "plugins"); array = (from file in Directory.GetFiles(path, "*", SearchOption.AllDirectories) where !invalidEndings.Any((string ending) => file.EndsWith(ending, StringComparison.CurrentCultureIgnoreCase)) select file).ToArray(); byte[] bytes = Encoding.ASCII.GetBytes("UnityFS"); List<string> list = new List<string>(); string[] array2 = array; foreach (string text in array2) { byte[] array3 = new byte[bytes.Length]; using (FileStream fileStream = File.Open(text, FileMode.Open)) { fileStream.Read(array3, 0, array3.Length); } if (array3.SequenceEqual(bytes)) { list.Add(text); } } array = list.ToArray(); if (array.Length == 0) { Plugin.Log.LogMessage((object)"BundleAPI got no assets to load from plugins folder"); } else { LoadAllAssetsFromDirectory(array, legacyLoading); } OnLoadedAssets.InvokeParameterlessDelegate(); BundleLoader.OnLoadedBundles.InvokeActionSafe(); } private static void LoadAllAssetsFromDirectory(string[] array, bool legacyLoading) { if (legacyLoading) { Plugin.Log.LogMessage((object)("BundleAPI got " + array.Length + " AssetBundles to load!")); for (int i = 0; i < array.Length; i++) { try { SaveAsset(array[i], legacyLoading); } catch (Exception) { Plugin.Log.LogError((object)("Failed to load an assetbundle! Path: " + array[i])); } } return; } Plugin.Log.LogMessage((object)("BundleAPI got " + array.Length + " AssetBundles to load!")); for (int j = 0; j < array.Length; j++) { try { SaveAsset(array[j], legacyLoading); } catch (Exception) { Plugin.Log.LogError((object)("Failed to load an assetbundle! Path: " + array[j])); } } } public static void SaveAsset(string path, bool legacyLoad) { AssetBundle val = AssetBundle.LoadFromFile(path); try { string[] allAssetNames = val.GetAllAssetNames(); foreach (string text in allAssetNames) { Plugin.Log.LogMessage((object)("Got asset for load: " + text)); Object val2 = val.LoadAsset(text); if (val2 == (Object)null) { Plugin.Log.LogWarning((object)$"Skipped/failed loading an asset (from bundle '{((Object)val).name}') - Asset path: {val2}"); continue; } string key = (legacyLoad ? text.ToUpper() : text.ToLower()); if (assets.ContainsKey(key)) { Plugin.Log.LogError((object)"BundleAPI got duplicate asset!"); break; } assets.TryAdd(key, val2); Plugin.Log.LogMessage((object)("Loaded asset: " + val2.name)); } } finally { if (val != null) { val.Unload(false); } } } public static TAsset GetLoadedAsset<TAsset>(string itemPath) where TAsset : Object { Object value = null; if (LegacyLoadingEnabled) { assets.TryGetValue(itemPath.ToUpper(), out value); } if (value == (Object)null) { assets.TryGetValue(itemPath.ToLower(), out value); } return (TAsset)(object)value; } private static void LoadAssetsCompleted() { Plugin.Log.LogMessage((object)"BundleAPI finished loading all assets."); } static BundleLoader() { BundleLoader.OnLoadedBundles = LoadAssetsCompleted; } } }
plugins/LCOuijaBoard.dll
Decompiled a year agousing System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using BepInEx; using GameNetcodeStuff; using HarmonyLib; using LCOuijaBoard.Properties; using LethalLib.Modules; using TMPro; using Unity.Netcode; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; 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: AssemblyTitle("LCOuijaBoard")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LCOuijaBoard")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("1c1acc88-8f86-45d6-beb9-9b98f2302980")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] internal class <Module> { static <Module>() { } } namespace LCOuijaBoard { [BepInPlugin("Electric.OuijaBoard", "OuijaBoard", "1.5.0")] public class Plugin : BaseUnityPlugin { private class UIHandler { public static GameObject inputObject; public static TMP_InputField input; public static bool registered; public static float lastError; public static TMP_InputField GetInput() { if (registered && (Object)(object)input != (Object)null) { return input; } inputObject = ((Component)OuijaTextUI.transform.GetChild(2)).gameObject; input = inputObject.GetComponent<TMP_InputField>(); ((UnityEvent<string>)(object)input.onSubmit).AddListener((UnityAction<string>)SubmitUI); ((UnityEvent<string>)(object)input.onEndEdit).AddListener((UnityAction<string>)EndEditUI); registered = true; return input; } public static void hide() { OuijaTextUI.SetActive(false); input.text = ""; } public static void ToggleUI(CallbackContext context) { PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; Debug.Log((object)"Ouija Text UI Toggle Requested"); if (!DEVDEBUG && ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerDead)) { Debug.Log((object)"Ouija Text UI Toggle Denied: Not Dead"); return; } if ((Object)(object)OuijaTextUI == (Object)null) { Debug.LogError((object)"Ouija Text UI Toggle Denied: No UI"); return; } bool flag = !OuijaTextUI.active; GetInput(); Debug.Log((object)$"Ouija Text UI Toggle Accepted: New State is {flag}"); if (!flag) { if (!input.isFocused || !OuijaTextUI.active) { OuijaTextUI.SetActive(false); } } else { OuijaTextUI.SetActive(true); input.ActivateInputField(); ((Selectable)input).Select(); } } public static void SubmitUI(string msg) { AttemptSend(msg); } public static void EndEditUI(string msg) { hide(); } public static bool AttemptSend(string msg) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_0079: Unknown result type (might be due to invalid IL or missing references) string[] value = msg.Split(new char[1] { ' ' }).ToArray(); Object[] array = Object.FindObjectsOfType(typeof(GameObject)); List<GameObject> list = new List<GameObject>(); Object[] array2 = array; for (int i = 0; i < array2.Length; i++) { GameObject val = (GameObject)array2[i]; if ((((Object)val).name == "OuijaBoardScrap(Clone)" || ((Object)val).name == "OuijaBoardStore(Clone)") && !((GrabbableObject)(PhysicsProp)val.GetComponent(typeof(PhysicsProp))).isHeld) { list.Add(val); } } if (list.Count > 0) { if (!StartOfRoundPatch.complete) { ShowError("Boards on cooldown"); return false; } string text = string.Join("", value); if (Regex.Match(text, "([A-Za-z\\d ])+").Value.Length != text.Length) { ShowError("Invalid character(s)"); return false; } text = text.Replace(" ", ""); if (text.Length > 10) { ShowError("Too many characters"); return false; } OuijaNetworker.Instance.WriteOut(text); return true; } ShowError("No valid boards"); return false; } public static void ShowError(string msg) { if ((Object)(object)OuijaErrorUI != (Object)null) { Debug.Log((object)("Ouija Board showing erorr: " + msg)); ((Component)OuijaErrorUI.transform.GetChild(0)).GetComponent<TMP_Text>().text = msg; OuijaErrorUI.SetActive(true); lastError = Time.time; } } } [HarmonyPatch(typeof(StartOfRound))] public class StartOfRoundPatch { public static int writeIndex = 0; public static List<string> names = new List<string>(); public static List<GameObject> boards = new List<GameObject>(); public static float timer = 0f; public static double amount = 0.0; public static bool complete = true; [HarmonyPatch("Update")] [HarmonyPostfix] private static void Update(ref StartOfRound __instance) { PlayerControllerB localPlayerController = __instance.localPlayerController; if (!DEVDEBUG && !localPlayerController.isPlayerDead && Object.op_Implicit((Object)(object)OuijaTextUI) && OuijaTextUI.active) { Debug.Log((object)"Ouija Text UI closed since player is not dead"); OuijaTextUI.SetActive(false); } if (Object.op_Implicit((Object)(object)OuijaErrorUI) && OuijaErrorUI.active && Time.time - UIHandler.lastError > 2f) { Debug.Log((object)"Ouija Error UI closed"); OuijaErrorUI.SetActive(false); } if (writeIndex < names.Count) { amount = Mathf.Clamp(timer / 1.2f, 0f, 1f); MoveUpdate(names[writeIndex]); timer += Time.deltaTime; if (timer >= 3f) { amount = 1.0; MoveUpdate(names[writeIndex]); timer = 0f; writeIndex++; } } else if (!complete) { if (timer < 5f) { timer += Time.deltaTime; } else { complete = true; timer = 0f; amount = 0.0; } } if ((Object)(object)OuijaTextUI != (Object)null) { ((Component)OuijaTextUI.transform.GetChild(3)).gameObject.SetActive(!complete); } } public static void MoveUpdate(string name) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_012e: 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_0148: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: 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_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_023f: 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_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown int num = -1; bool flag = false; PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; foreach (GameObject board in boards) { if (!Object.op_Implicit((Object)(object)board) || ((GrabbableObject)(PhysicsProp)board.GetComponent(typeof(PhysicsProp))).isHeld) { continue; } flag = true; if (num == -1) { num = 0; foreach (Transform item in board.transform.GetChild(0).GetChild(3)) { Transform val = item; GameObject gameObject = ((Component)val).gameObject; if (((Object)gameObject).name == name) { break; } num++; } if (num == -1) { amount = 0.0; writeIndex++; break; } } Vector3 localPosition = board.transform.GetChild(0).GetChild(3).GetChild(num) .localPosition; Vector3 localPosition2 = board.transform.GetChild(0).GetChild(4).localPosition; GameObject gameObject2 = ((Component)board.transform.GetChild(0).GetChild(2)).gameObject; if (amount == 0.0) { gameObject2.GetComponent<AudioSource>().Play(); if (makesSound) { RoundManager.Instance.PlayAudibleNoise(board.transform.position, 8f, 0.3f, 0, false, 8925); } } Vector3 val2 = localPosition + new Vector3(0f, 0.166f, 0f); gameObject2.transform.localPosition = Vector3.Lerp(localPosition2, val2, (float)amount); if (amount == 1.0) { board.transform.GetChild(0).GetChild(4).localPosition = val2; } if (Vector3.Distance(((Component)localPlayerController).transform.position, board.transform.position) < 5f) { localPlayerController.insanityLevel += Time.deltaTime * 0.5f; } } if (!flag) { writeIndex = names.Count; } } } [HarmonyPatch(typeof(PlayerControllerB))] [HarmonyPriority(500)] public class PlayerPatch { [HarmonyPatch("Interact_performed")] [HarmonyPrefix] private static void InteractPrefixPatch(ref PlayerControllerB __instance, out bool __state) { __state = __instance.isPlayerDead; if (Object.op_Implicit((Object)(object)OuijaTextUI) && OuijaTextUI.active) { __instance.isPlayerDead = false; } } [HarmonyPatch("Interact_performed")] [HarmonyPostfix] private static void InteractPostfixPatch(ref PlayerControllerB __instance, bool __state) { __instance.isPlayerDead = __state; } } public class OuijaNetworker : NetworkBehaviour { public static OuijaNetworker Instance; private void Awake() { Instance = this; } public void WriteOut(string message) { if (((NetworkBehaviour)this).IsOwner) { WriteOutClientRpc(message); } else { WriteOutServerRpc(message); } } [ClientRpc] public void WriteOutClientRpc(string message) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: 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_0123: Expected O, but got Unknown //IL_015b: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3508306228u, val, (RpcDelivery)0); bool flag = message != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(message, false); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3508306228u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } Object[] array = Object.FindObjectsOfType(typeof(GameObject)); List<GameObject> list = new List<GameObject>(); Object[] array2 = array; for (int i = 0; i < array2.Length; i++) { GameObject val3 = (GameObject)array2[i]; if ((((Object)val3).name == "OuijaBoardScrap(Clone)" || ((Object)val3).name == "OuijaBoardStore(Clone)") && !((GrabbableObject)(PhysicsProp)val3.GetComponent(typeof(PhysicsProp))).isHeld) { list.Add(val3); } } List<string> list2 = new List<string>(); switch (message) { case "yes": case "y": list2.Add("Yes"); break; case "no": case "n": list2.Add("No"); break; case "goodbye": case "bye": list2.Add("Goodbye"); break; default: list2 = (from c in message.ToUpper().ToCharArray() select c.ToString()).ToList(); break; } StartOfRoundPatch.amount = 0.0; StartOfRoundPatch.complete = false; StartOfRoundPatch.writeIndex = 0; StartOfRoundPatch.names = list2; StartOfRoundPatch.boards = list; } [ServerRpc(RequireOwnership = false)] public void WriteOutServerRpc(string message) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3320529116u, val, (RpcDelivery)0); bool flag = message != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(message, false); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3320529116u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { WriteOutClientRpc(message); } } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_OuijaNetworker() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(3508306228u, new RpcReceiveHandler(__rpc_handler_3508306228)); NetworkManager.__rpc_func_table.Add(3320529116u, new RpcReceiveHandler(__rpc_handler_3320529116)); } private static void __rpc_handler_3508306228(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0061: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string message = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref message, false); } target.__rpc_exec_stage = (__RpcExecStage)2; ((OuijaNetworker)(object)target).WriteOutClientRpc(message); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3320529116(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0061: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string message = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref message, false); } target.__rpc_exec_stage = (__RpcExecStage)1; ((OuijaNetworker)(object)target).WriteOutServerRpc(message); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "OuijaNetworker"; } } [HarmonyPatch(typeof(RoundManager))] internal class RoundManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch(ref RoundManager __instance) { if (((NetworkBehaviour)__instance).IsServer && (Object)(object)OuijaNetworker.Instance == (Object)null) { GameObject val = Object.Instantiate<GameObject>(OuijaNetworkerPrefab); val.GetComponent<NetworkObject>().Spawn(true); } OuijaTextUI = Object.Instantiate<GameObject>(OuijaTextUIPrefab); OuijaTextUI.SetActive(false); OuijaErrorUI = Object.Instantiate<GameObject>(OuijaErrorUIPrefab); OuijaErrorUI.SetActive(false); } } private const string modGUID = "Electric.OuijaBoard"; private const string modName = "OuijaBoard"; private const string modVersion = "1.5.0"; private readonly Harmony harmony = new Harmony("Electric.OuijaBoard"); private static MethodInfo chat; public static bool storeEnabled; public static int storeCost; public static bool scrapEnabled; public static int scrapRarity; public static bool makesSound; private static bool DEVDEBUG; public static GameObject OuijaNetworkerPrefab; public static GameObject OuijaTextUIPrefab; public static GameObject OuijaTextUI; public static GameObject OuijaErrorUIPrefab; public static GameObject OuijaErrorUI; private void Awake() { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown AssetBundle val = AssetBundle.LoadFromMemory(Resources.fullboard); OuijaNetworkerPrefab = val.LoadAsset<GameObject>("Assets/OuijaNetworker.prefab"); OuijaNetworkerPrefab.AddComponent<OuijaNetworker>(); OuijaTextUIPrefab = val.LoadAsset<GameObject>("Assets/OuijaTextUI.prefab"); OuijaErrorUIPrefab = val.LoadAsset<GameObject>("Assets/OuijaErrorUI.prefab"); GameObject val2 = val.LoadAsset<GameObject>("Assets/OuijaBoardStore.prefab"); GameObject val3 = val.LoadAsset<GameObject>("Assets/OuijaBoardScrap.prefab"); NetworkPrefabs.RegisterNetworkPrefab(OuijaNetworkerPrefab); NetworkPrefabs.RegisterNetworkPrefab(val2); NetworkPrefabs.RegisterNetworkPrefab(val3); InputAction val4 = new InputAction((string)null, (InputActionType)0, "<Keyboard>/#(" + ((BaseUnityPlugin)this).Config.Bind<string>("General", "Keybind", "o", "(Clientside) The key that will open the Ouija Board UI. Note: This will NOT change the tooltip on the item").Value + ")", (string)null, (string)null, (string)null); val4.performed += UIHandler.ToggleUI; val4.Enable(); chat = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null); storeEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Store", "Enabled", true, "Allow Ouija Board to be bought in the store").Value; storeCost = ((BaseUnityPlugin)this).Config.Bind<int>("Store", "Cost", 100, "Cost of a Ouija Board in the store (Store must be enabled)").Value; scrapEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Scrap", "Enabled", false, "Allow the Ouija Board to spawn in the facility").Value; scrapRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Scrap", "Rarity Weight", 20, "Chance for a Ouija Board to spawn as scrap").Value; if (storeCost < 0) { storeCost = 0; } if (scrapRarity < 0) { scrapRarity = 0; } makesSound = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Makes Sound", true, "Enables the Ouija Board's sliding to be heard by enemies").Value; Item val5 = val.LoadAsset<Item>("Assets/OuijaBoardStoreItem.asset"); Item val6 = val.LoadAsset<Item>("Assets/OuijaBoardScrapItem.asset"); if (storeEnabled) { Debug.Log((object)$"Ouija Board store enabled at {storeCost} credits"); Items.RegisterShopItem(val5, storeCost); } if (scrapEnabled) { Debug.Log((object)$"Ouija Board scrap spawn enabled at {scrapRarity} rarity weight"); Items.RegisterScrap(val6, scrapRarity, (LevelTypes)510); } NetcodeWeaver(); harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"OuijaBoard loaded!"); } private static void NetcodeWeaver() { Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array = types; foreach (Type type in array) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array2 = methods; foreach (MethodInfo methodInfo in array2) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } } } } namespace LCOuijaBoard.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { ResourceManager resourceManager = new ResourceManager("LCOuijaBoard.Properties.Resources", typeof(Resources).Assembly); resourceMan = resourceManager; } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] fullboard { get { object @object = ResourceManager.GetObject("fullboard", resourceCulture); return (byte[])@object; } } internal Resources() { } } }
plugins/LethalLib.dll
Decompiled a year 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.Logging; using DunGen; using DunGen.Graph; using LethalLib.Extras; using LethalLib.Modules; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using On; 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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalLib")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Mod for Lethal Company")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+60d42612d19dbe329175a80dfc41bc601a0ec3eb")] [assembly: AssemblyProduct("LethalLib")] [assembly: AssemblyTitle("LethalLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] 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.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.9.0")] public class Plugin : BaseUnityPlugin { public const string ModGUID = "evaisa.lethallib"; public const string ModName = "LethalLib"; public const string ModVersion = "0.9.0"; public static AssetBundle MainAssets; public static ManualLogSource logger; private void Awake() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) logger = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalLib loaded!!"); 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(); NetworkPrefabs.Init(); } private void IlHook(ILContext il) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown ILCursor val = new ILCursor(il); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public)) }); 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(); } } } namespace LethalLib.Modules { 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 hook_Start <2>__StartOfRound_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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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; object obj3 = <>O.<2>__StartOfRound_Start; if (obj3 == null) { hook_Start val3 = StartOfRound_Start; <>O.<2>__StartOfRound_Start = val3; obj3 = (object)val3; } StartOfRound.Start += (hook_Start)obj3; } private static void StartOfRound_Start(orig_Start orig, StartOfRound self) { //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Expected O, but got Unknown foreach (CustomDungeon dungeon in customDungeons) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = dungeon.LevelTypes.HasFlag(Levels.LevelTypes.All) || (dungeon.levelOverrides != null && dungeon.levelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag) { Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if ((flag || dungeon.LevelTypes.HasFlag(levelTypes)) && !val.dungeonFlowTypes.Any((IntWithRarity rarityInt) => rarityInt.id == dungeon.dungeonIndex)) { List<IntWithRarity> list = val.dungeonFlowTypes.ToList(); list.Add(new IntWithRarity { id = dungeon.dungeonIndex, rarity = dungeon.rarity }); val.dungeonFlowTypes = list.ToArray(); } } } } Plugin.logger.LogInfo((object)"Added custom dungeons to levels"); orig.Invoke(self); } private static void RoundManager_Start(orig_Start orig, RoundManager self) { foreach (CustomDungeon customDungeon in customDungeons) { if (self.dungeonFlowTypes.Contains(customDungeon.dungeonFlow)) { continue; } List<DungeonFlow> list = self.dungeonFlowTypes.ToList(); list.Add(customDungeon.dungeonFlow); self.dungeonFlowTypes = list.ToArray(); int dungeonIndex = self.dungeonFlowTypes.Length - 1; customDungeon.dungeonIndex = dungeonIndex; List<AudioClip> list2 = self.firstTimeDungeonAudios.ToList(); if (list2.Count != self.dungeonFlowTypes.Length - 1) { while (list2.Count < self.dungeonFlowTypes.Length - 1) { list2.Add(null); } } list2.Add(customDungeon.firstTimeDungeonAudio); self.firstTimeDungeonAudios = list2.ToArray(); } 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); 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); 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>(); RandomMapObject[] array2 = array; foreach (RandomMapObject val2 in array2) { for (int j = 0; j < val2.spawnablePrefabs.Count; j++) { string prefabName = ((Object)val2.spawnablePrefabs[j]).name; NetworkPrefab val3 = val.NetworkConfig.Prefabs.m_Prefabs.First((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName); if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j]) { val2.spawnablePrefabs[j] = val3.Prefab; } } } } 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 enum SpawnType { Default, Daytime, Outside } public class SpawnableEnemy { public EnemyType enemy; public int rarity; public Levels.LevelTypes spawnLevels; public SpawnType spawnType; public TerminalNode terminalNode; public TerminalKeyword infoKeyword; public string modName; public string[] spawnLevelOverrides; public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null) { this.enemy = enemy; this.rarity = rarity; this.spawnLevels = spawnLevels; this.spawnType = spawnType; this.spawnLevelOverrides = spawnLevelOverrides; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__RegisterLevelEnemies; public static hook_Start <1>__Terminal_Start; } public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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; } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Expected O, but got Unknown 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); spawnableEnemy.enemy.enemyPrefab.GetComponentInChildren<ScanNodeProperties>().creatureScanID = spawnableEnemy.terminalNode.creatureFileID; } orig.Invoke(self); } private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self) { //IL_011b: 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_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown orig.Invoke(self); foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = spawnableEnemy.spawnLevels.HasFlag(Levels.LevelTypes.All) || (spawnableEnemy.spawnLevelOverrides != null && spawnableEnemy.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); 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 && !spawnableEnemy.spawnLevels.HasFlag(levelTypes)) { continue; } SpawnableEnemyWithRarity item2 = new SpawnableEnemyWithRarity { enemyType = spawnableEnemy.enemy, rarity = spawnableEnemy.rarity }; switch (spawnableEnemy.spawnType) { case SpawnType.Default: if (!val.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.Enemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Default]")); } break; case SpawnType.Daytime: if (!val.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.DaytimeEnemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Daytime]")); } break; case SpawnType.Outside: if (!val.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.OutsideEnemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Outside]")); } break; } } } } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default)); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default), spawnLevelOverrides); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } } public class Items { public class ScrapItem { public Item item; public int rarity; public Levels.LevelTypes spawnLevels; public string[] spawnLevelOverrides; public string modName; public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null) { this.item = item; this.rarity = rarity; this.spawnLevels = spawnLevels; } } public class PlainItem { public Item item; public string modName; public PlainItem(Item item) { this.item = item; } } public class ShopItem { public Item item; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public int price; public string modName; public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0) { 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_Awake <0>__StartOfRound_Awake; public static hook_Awake <1>__Terminal_Awake; } 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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>__Terminal_Awake; if (obj2 == null) { hook_Awake val2 = Terminal_Awake; <>O.<1>__Terminal_Awake = val2; obj2 = (object)val2; } Terminal.Awake += (hook_Awake)obj2; } private static void Terminal_Awake(orig_Awake orig, Terminal self) { //IL_02fe: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Expected O, but got Unknown //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_037d: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Expected O, but got Unknown //IL_03e9: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_03f6: Unknown result type (might be due to invalid IL or missing references) //IL_0403: Expected O, but got Unknown //IL_0497: Unknown result type (might be due to invalid IL or missing references) //IL_049c: Unknown result type (might be due to invalid IL or missing references) //IL_04a4: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Expected O, but got Unknown List<Item> list = self.buyableItemsList.ToList(); TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val2 = 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)) { Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping")); continue; } if (item.price == -1) { item.price = item.item.creditsWorth; } else { item.item.creditsWorth = item.price; } list.Add(item.item); string itemName = item.item.itemName; char c = itemName[itemName.Length - 1]; string text = itemName; TerminalNode val3 = item.buyNode2; if ((Object)(object)val3 == (Object)null) { val3 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val3).name = itemName.Replace(" ", "-") + "BuyNode2"; val3.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"; val3.clearPreviousText = true; val3.maxCharactersToType = 15; } val3.buyItemIndex = list.Count - 1; val3.isConfirmationNode = false; val3.itemCost = item.price; val3.playSyncedClip = 0; TerminalNode val4 = item.buyNode1; if ((Object)(object)val4 == (Object)null) { val4 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val4).name = itemName.Replace(" ", "-") + "BuyNode1"; val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val4.clearPreviousText = true; val4.maxCharactersToType = 35; } val4.buyItemIndex = list.Count - 1; val4.isConfirmationNode = true; val4.overrideOptions = true; val4.itemCost = item.price; val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val3 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; TerminalKeyword val5 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val); List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(val5); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = val5, result = val4 }); val.compatibleNouns = list3.ToArray(); TerminalNode val6 = item.itemInfo; if ((Object)(object)val6 == (Object)null) { val6 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val6).name = itemName.Replace(" ", "-") + "InfoNode"; val6.displayText = "[No information about this object was found.]\n\n"; val6.clearPreviousText = true; val6.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val2.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = val5, result = val6 }); val2.compatibleNouns = list4.ToArray(); Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.item.itemName)); } self.buyableItemsList = list.ToArray(); orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Expected O, but got Unknown orig.Invoke(self); foreach (ScrapItem scrapItem in scrapItems) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = scrapItem.spawnLevels.HasFlag(Levels.LevelTypes.All) || (scrapItem.spawnLevelOverrides != null && scrapItem.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); 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 || scrapItem.spawnLevels.HasFlag(levelTypes)) { SpawnableItemWithRarity item2 = new SpawnableItemWithRarity { spawnableItem = scrapItem.item, rarity = scrapItem.rarity }; if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item)) { val.spawnableScrap.Add(item2); } } } } foreach (ScrapItem scrapItem2 in scrapItems) { if (!self.allItemsList.itemsList.Contains(scrapItem2.item)) { Plugin.logger.LogInfo((object)(scrapItem2.modName + " registered item: " + scrapItem2.item.itemName)); self.allItemsList.itemsList.Add(scrapItem2.item); } } foreach (ShopItem shopItem in shopItems) { if (!self.allItemsList.itemsList.Contains(shopItem.item)) { Plugin.logger.LogInfo((object)(shopItem.modName + " registered item: " + shopItem.item.itemName)); self.allItemsList.itemsList.Add(shopItem.item); } } foreach (PlainItem plainItem in plainItems) { if (!self.allItemsList.itemsList.Contains(plainItem.item)) { Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName)); self.allItemsList.itemsList.Add(plainItem.item); } } } public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags) { ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.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) { ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags, levelOverrides); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.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); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.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); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; shopItem2.modName = name; shopItems.Add(shopItem2); } public static void RegisterItem(Item plainItem) { PlainItem plainItem2 = new PlainItem(plainItem); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; plainItem2.modName = name; plainItems.Add(plainItem2); } } 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, Vanilla = 0x3FC, All = -1 } } 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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>(); RandomMapObject[] array2 = array; foreach (RandomMapObject val in array2) { 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) { 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 (!(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 mapObject2 = mapObject.mapObject; if (mapObject.spawnRateFunction != null) { mapObject2.numberToSpawn = mapObject.spawnRateFunction(val); } List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList(); list2.Add(mapObject2); val.spawnableMapObjects = list2.ToArray(); Plugin.logger.LogInfo((object)("Added " + ((Object)mapObject2.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 outsideObject = mapObject.outsideObject; if (mapObject.spawnRateFunction != null) { outsideObject.randomAmount = mapObject.spawnRateFunction(val); } List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList(); list4.Add(outsideObject); val.spawnableOutsideObjects = list4.ToArray(); Plugin.logger.LogInfo((object)("Added " + ((Object)outsideObject.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 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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) { _networkPrefabs.Add(prefab); } private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self) { orig.Invoke(self); foreach (GameObject networkPrefab in _networkPrefabs) { ((Component)self).GetComponent<NetworkManager>().AddNetworkPrefab(networkPrefab); } } } public class Shaders { public static void FixShaders(GameObject gameObject) { Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>(); foreach (Renderer val in componentsInChildren) { Material[] materials = val.materials; foreach (Material val2 in materials) { if (((Object)val2.shader).name.Contains("Standard")) { val2.shader = Shader.Find("HDRP/Lit"); } } } } } public class TerminalUtils { public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false) { TerminalKeyword val = ScriptableObject.CreateInstance<TerminalKeyword>(); ((Object)val).name = word; val.word = word; val.isVerb = isVerb; val.compatibleNouns = compatibleNouns; val.specialKeywordResult = specialKeywordResult; val.defaultVerb = defaultVerb; val.accessTerminalObjects = accessTerminalObjects; return val; } } public enum StoreType { None, ShipUpgrade, Decor } public class Unlockables { public class RegisteredUnlockable { public UnlockableItem unlockable; public StoreType StoreType; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public int price; public string modName; public RegisteredUnlockable(UnlockableItem unlockable, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { this.unlockable = unlockable; this.buyNode1 = buyNode1; this.buyNode2 = buyNode2; this.itemInfo = itemInfo; this.price = price; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_Start <1>__Terminal_Start; public static hook_TextPostProcess <2>__Terminal_TextPostProcess; } public static List<RegisteredUnlockable> registeredUnlockables = new List<RegisteredUnlockable>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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>__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>__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) { if (modifiedDisplayText.Contains("[buyableItemsList]") && modifiedDisplayText.Contains("[unlockablesSelectionList]")) { int num = modifiedDisplayText.IndexOf(":"); foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables) { if (registeredUnlockable.StoreType == StoreType.ShipUpgrade) { string unlockableName = registeredUnlockable.unlockable.unlockableName; int price = registeredUnlockable.price; string value = $"\n* {unlockableName} // Price: ${price}"; modifiedDisplayText = modifiedDisplayText.Insert(num + 1, value); } } } return orig.Invoke(self, modifiedDisplayText, node); } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0390: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) //IL_03d3: Expected O, but got Unknown //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Expected O, but got Unknown //IL_049e: Unknown result type (might be due to invalid IL or missing references) //IL_04a3: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04bd: Expected O, but got Unknown //IL_0551: Unknown result type (might be due to invalid IL or missing references) //IL_0556: Unknown result type (might be due to invalid IL or missing references) //IL_0563: Unknown result type (might be due to invalid IL or missing references) //IL_0570: Expected O, but got Unknown TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); List<RegisteredUnlockable> list = registeredUnlockables.FindAll((RegisteredUnlockable unlockable) => unlockable.price != -1).ToList(); Plugin.logger.LogInfo((object)$"Adding {list.Count} items to terminal"); foreach (RegisteredUnlockable item in list) { string unlockableName = item.unlockable.unlockableName; TerminalKeyword keyword3 = TerminalUtils.CreateTerminalKeyword(unlockableName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val); if (self.terminalNodes.allKeywords.Any((TerminalKeyword kw) => kw.word == keyword3.word)) { Plugin.logger.LogInfo((object)("Keyword " + keyword3.word + " already registed, skipping.")); continue; } int shipUnlockableID = StartOfRound.Instance.unlockablesList.unlockables.FindIndex((UnlockableItem unlockable) => unlockable.unlockableName == item.unlockable.unlockableName); StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { Debug.Log((object)"STARTOFROUND INSTANCE NOT FOUND"); } if (item.price == -1 && (Object)(object)item.buyNode1 != (Object)null) { item.price = item.buyNode1.itemCost; } char c = unlockableName[unlockableName.Length - 1]; string text = unlockableName; TerminalNode val3 = item.buyNode2; if ((Object)(object)val3 == (Object)null) { val3 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val3).name = unlockableName.Replace(" ", "-") + "BuyNode2"; val3.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"; val3.clearPreviousText = true; val3.maxCharactersToType = 15; } val3.buyItemIndex = -1; val3.shipUnlockableID = shipUnlockableID; val3.buyUnlockable = true; val3.creatureName = unlockableName; val3.isConfirmationNode = false; val3.itemCost = item.price; val3.playSyncedClip = 0; TerminalNode val4 = item.buyNode1; if ((Object)(object)val4 == (Object)null) { val4 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val4).name = unlockableName.Replace(" ", "-") + "BuyNode1"; val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val4.clearPreviousText = true; val4.maxCharactersToType = 35; } val4.buyItemIndex = -1; val4.shipUnlockableID = shipUnlockableID; val4.creatureName = unlockableName; val4.isConfirmationNode = true; val4.overrideOptions = true; val4.itemCost = item.price; val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val3 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; if (item.StoreType == StoreType.Decor) { item.unlockable.shopSelectionNode = val4; } else { item.unlockable.shopSelectionNode = null; } List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(keyword3); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = keyword3, result = val4 }); val.compatibleNouns = list3.ToArray(); TerminalNode val5 = item.itemInfo; if ((Object)(object)val5 == (Object)null) { val5 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val5).name = unlockableName.Replace(" ", "-") + "InfoNode"; val5.displayText = "[No information about this object was found.]\n\n"; val5.clearPreviousText = true; val5.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val2.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = keyword3, result = val5 }); val2.compatibleNouns = list4.ToArray(); Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.unlockable.unlockableName)); } orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { orig.Invoke(self); Plugin.logger.LogInfo((object)$"Adding {registeredUnlockables.Count} unlockables to unlockables list"); foreach (RegisteredUnlockable unlockable in registeredUnlockables) { if (self.unlockablesList.unlockables.Any((UnlockableItem x) => x.unlockableName == unlockable.unlockable.unlockableName)) { Plugin.logger.LogInfo((object)("Unlockable " + unlockable.unlockable.unlockableName + " already exists in unlockables list, skipping")); continue; } if ((Object)(object)unlockable.unlockable.prefabObject != (Object)null) { PlaceableShipObject componentInChildren = unlockable.unlockable.prefabObject.GetComponentInChildren<PlaceableShipObject>(); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.unlockableID = self.unlockablesList.unlockables.Count; } } self.unlockablesList.unlockables.Add(unlockable.unlockable); } } public static void RegisterUnlockable(UnlockableItemDef unlockable, int price = -1, StoreType storeType = StoreType.None) { RegisterUnlockable(unlockable.unlockable, storeType, null, null, null, price); } public static void RegisterUnlockable(UnlockableItem unlockable, int price = -1, StoreType storeType = StoreType.None) { RegisterUnlockable(unlockable, storeType, null, null, null, price); } public static void RegisterUnlockable(UnlockableItemDef unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { RegisterUnlockable(unlockable.unlockable, storeType, buyNode1, buyNode2, itemInfo, price); } public static void RegisterUnlockable(UnlockableItem unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { RegisteredUnlockable registeredUnlockable = new RegisteredUnlockable(unlockable, buyNode1, buyNode2, itemInfo, price); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; registeredUnlockable.modName = name; registeredUnlockable.StoreType = storeType; registeredUnlockables.Add(registeredUnlockable); } } public class Weathers { public class CustomWeather { public string name; public int weatherVariable1; public int weatherVariable2; public WeatherEffect weatherEffect; public Levels.LevelTypes levels; public string[] spawnLevelOverrides; public CustomWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null, int weatherVariable1 = 0, int weatherVariable2 = 0) { this.name = name; this.weatherVariable1 = weatherVariable1; this.weatherVariable2 = weatherVariable2; this.weatherEffect = weatherEffect; this.levels = levels; this.spawnLevelOverrides = spawnLevelOverrides; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__TimeOfDay_Awake; public static hook_Awake <1>__StartOfRound_Awake; } public static Dictionary<int, CustomWeather> customWeathers = new Dictionary<int, CustomWeather>(); public static int numCustomWeathers = 0; public static void Init() { //IL_002f: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //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_0071: Expected O, but got Unknown new Hook((MethodBase)typeof(Enum).GetMethod("ToString", new Type[0]), typeof(Weathers).GetMethod("ToStringHook")); object obj = <>O.<0>__TimeOfDay_Awake; if (obj == null) { hook_Awake val = TimeOfDay_Awake; <>O.<0>__TimeOfDay_Awake = val; obj = (object)val; } TimeOfDay.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__StartOfRound_Awake; if (obj2 == null) { hook_Awake val2 = StartOfRound_Awake; <>O.<1>__StartOfRound_Awake = val2; obj2 = (object)val2; } StartOfRound.Awake += (hook_Awake)obj2; } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { //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_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Expected O, but got Unknown foreach (KeyValuePair<int, CustomWeather> customWeather in customWeathers) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = customWeather.Value.levels.HasFlag(Levels.LevelTypes.All) || (customWeather.Value.spawnLevelOverrides != null && customWeather.Value.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag) { Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); List<RandomWeatherWithVariables> list = val.randomWeathers.ToList(); if (flag || customWeather.Value.levels.HasFlag(levelTypes)) { list.Add(new RandomWeatherWithVariables { weatherType = (LevelWeatherType)customWeather.Key, weatherVariable = customWeather.Value.weatherVariable1, weatherVariable2 = customWeather.Value.weatherVariable2 }); Plugin.logger.LogInfo((object)$"Added weather {customWeather.Value.name} to level {((Object)val).name} at weather index: {customWeather.Key}"); } val.randomWeathers = list.ToArray(); } } } orig.Invoke(self); } private static void TimeOfDay_Awake(orig_Awake orig, TimeOfDay self) { List<WeatherEffect> list = self.effects.ToList(); int num = 0; foreach (KeyValuePair<int, CustomWeather> customWeather in customWeathers) { if (customWeather.Key > num) { num = customWeather.Key; } } while (list.Count <= num) { list.Add(null); } foreach (KeyValuePair<int, CustomWeather> customWeather2 in customWeathers) { list[customWeather2.Key] = customWeather2.Value.weatherEffect; } self.effects = list.ToArray(); orig.Invoke(self); } public static string ToStringHook(Func<Enum, string> orig, Enum self) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected I4, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected I4, but got Unknown if (self.GetType() == typeof(LevelWeatherType) && customWeathers.ContainsKey((int)(LevelWeatherType)(object)self)) { return customWeathers[(int)(LevelWeatherType)(object)self].name; } return orig(self); } public static void RegisterWeather(WeatherDef weather) { RegisterWeather(weather.weatherName, weather.weatherEffect, weather.levels, weather.levelOverrides, weather.weatherVariable1, weather.weatherVariable2); } public static void RegisterWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, int weatherVariable1 = 0, int weatherVariable2 = 0) { Array values = Enum.GetValues(typeof(LevelWeatherType)); int num = values.Length - 1; num += numCustomWeathers; numCustomWeathers++; Plugin.logger.LogInfo((object)$"Registering weather {name} at index {num - 1}"); customWeathers.Add(num, new CustomWeather(name, weatherEffect, levels, null, weatherVariable1, weatherVariable2)); } public static void RegisterWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null, int weatherVariable1 = 0, int weatherVariable2 = 0) { Array values = Enum.GetValues(typeof(LevelWeatherType)); int num = values.Length - 1; num += numCustomWeathers; numCustomWeathers++; Plugin.logger.LogInfo((object)$"Registering weather {name} at index {num - 1}"); customWeathers.Add(num, new CustomWeather(name, weatherEffect, levels, spawnLevelOverrides, weatherVariable1, weatherVariable2)); } } } namespace LethalLib.Extras { [CreateAssetMenu(menuName = "ScriptableObjects/DungeonDef")] public class DungeonDef : ScriptableObject { public DungeonFlow dungeonFlow; [Range(0f, 300f)] public int rarity; public AudioClip firstTimeDungeonAudio; } [CreateAssetMenu(menuName = "ScriptableObjects/DungeonGraphLine")] public class DungeonGraphLineDef : ScriptableObject { public GraphLine graphLine; } [CreateAssetMenu(menuName = "ScriptableObjects/GameObjectChance")] public class GameObjectChanceDef : ScriptableObject { public GameObjectChance gameObjectChance; } [CreateAssetMenu(menuName = "ScriptableObjects/SpawnableMapObject")] public class SpawnableMapObjectDef : ScriptableObject { public SpawnableMapObject spawnableMapObject; } [CreateAssetMenu(menuName = "ScriptableObjects/SpawnableOutsideObject")] public class SpawnableOutsideObjectDef : ScriptableObject { public SpawnableOutsideObjectWithRarity spawnableMapObject; } [CreateAssetMenu(menuName = "ScriptableObjects/UnlockableItem")] public class UnlockableItemDef : ScriptableObject { public StoreType storeType = StoreType.None; public UnlockableItem unlockable; } [CreateAssetMenu(menuName = "ScriptableObjects/WeatherDef")] public class WeatherDef : ScriptableObject { public string weatherName; public Levels.LevelTypes levels = Levels.LevelTypes.None; public string[] levelOverrides; public int weatherVariable1; public int weatherVariable2; public WeatherEffect weatherEffect; } }
plugins/LethalLib/LethalLib.dll
Decompiled a year 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.Logging; using DunGen; using DunGen.Graph; using LethalLib.Extras; using LethalLib.Modules; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using On; 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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalLib")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Mod for Lethal Company")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+60d42612d19dbe329175a80dfc41bc601a0ec3eb")] [assembly: AssemblyProduct("LethalLib")] [assembly: AssemblyTitle("LethalLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] 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.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.9.0")] public class Plugin : BaseUnityPlugin { public const string ModGUID = "evaisa.lethallib"; public const string ModName = "LethalLib"; public const string ModVersion = "0.9.0"; public static AssetBundle MainAssets; public static ManualLogSource logger; private void Awake() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) logger = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalLib loaded!!"); 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(); NetworkPrefabs.Init(); } private void IlHook(ILContext il) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown ILCursor val = new ILCursor(il); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public)) }); 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(); } } } namespace LethalLib.Modules { 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 hook_Start <2>__StartOfRound_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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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; object obj3 = <>O.<2>__StartOfRound_Start; if (obj3 == null) { hook_Start val3 = StartOfRound_Start; <>O.<2>__StartOfRound_Start = val3; obj3 = (object)val3; } StartOfRound.Start += (hook_Start)obj3; } private static void StartOfRound_Start(orig_Start orig, StartOfRound self) { //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Expected O, but got Unknown foreach (CustomDungeon dungeon in customDungeons) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = dungeon.LevelTypes.HasFlag(Levels.LevelTypes.All) || (dungeon.levelOverrides != null && dungeon.levelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag) { Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if ((flag || dungeon.LevelTypes.HasFlag(levelTypes)) && !val.dungeonFlowTypes.Any((IntWithRarity rarityInt) => rarityInt.id == dungeon.dungeonIndex)) { List<IntWithRarity> list = val.dungeonFlowTypes.ToList(); list.Add(new IntWithRarity { id = dungeon.dungeonIndex, rarity = dungeon.rarity }); val.dungeonFlowTypes = list.ToArray(); } } } } Plugin.logger.LogInfo((object)"Added custom dungeons to levels"); orig.Invoke(self); } private static void RoundManager_Start(orig_Start orig, RoundManager self) { foreach (CustomDungeon customDungeon in customDungeons) { if (self.dungeonFlowTypes.Contains(customDungeon.dungeonFlow)) { continue; } List<DungeonFlow> list = self.dungeonFlowTypes.ToList(); list.Add(customDungeon.dungeonFlow); self.dungeonFlowTypes = list.ToArray(); int dungeonIndex = self.dungeonFlowTypes.Length - 1; customDungeon.dungeonIndex = dungeonIndex; List<AudioClip> list2 = self.firstTimeDungeonAudios.ToList(); if (list2.Count != self.dungeonFlowTypes.Length - 1) { while (list2.Count < self.dungeonFlowTypes.Length - 1) { list2.Add(null); } } list2.Add(customDungeon.firstTimeDungeonAudio); self.firstTimeDungeonAudios = list2.ToArray(); } 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); 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); 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>(); RandomMapObject[] array2 = array; foreach (RandomMapObject val2 in array2) { for (int j = 0; j < val2.spawnablePrefabs.Count; j++) { string prefabName = ((Object)val2.spawnablePrefabs[j]).name; NetworkPrefab val3 = val.NetworkConfig.Prefabs.m_Prefabs.First((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName); if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j]) { val2.spawnablePrefabs[j] = val3.Prefab; } } } } 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 enum SpawnType { Default, Daytime, Outside } public class SpawnableEnemy { public EnemyType enemy; public int rarity; public Levels.LevelTypes spawnLevels; public SpawnType spawnType; public TerminalNode terminalNode; public TerminalKeyword infoKeyword; public string modName; public string[] spawnLevelOverrides; public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null) { this.enemy = enemy; this.rarity = rarity; this.spawnLevels = spawnLevels; this.spawnType = spawnType; this.spawnLevelOverrides = spawnLevelOverrides; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__RegisterLevelEnemies; public static hook_Start <1>__Terminal_Start; } public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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; } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Expected O, but got Unknown 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); spawnableEnemy.enemy.enemyPrefab.GetComponentInChildren<ScanNodeProperties>().creatureScanID = spawnableEnemy.terminalNode.creatureFileID; } orig.Invoke(self); } private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self) { //IL_011b: 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_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown orig.Invoke(self); foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = spawnableEnemy.spawnLevels.HasFlag(Levels.LevelTypes.All) || (spawnableEnemy.spawnLevelOverrides != null && spawnableEnemy.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); 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 && !spawnableEnemy.spawnLevels.HasFlag(levelTypes)) { continue; } SpawnableEnemyWithRarity item2 = new SpawnableEnemyWithRarity { enemyType = spawnableEnemy.enemy, rarity = spawnableEnemy.rarity }; switch (spawnableEnemy.spawnType) { case SpawnType.Default: if (!val.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.Enemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Default]")); } break; case SpawnType.Daytime: if (!val.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.DaytimeEnemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Daytime]")); } break; case SpawnType.Outside: if (!val.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.OutsideEnemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Outside]")); } break; } } } } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default)); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default), spawnLevelOverrides); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } } public class Items { public class ScrapItem { public Item item; public int rarity; public Levels.LevelTypes spawnLevels; public string[] spawnLevelOverrides; public string modName; public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null) { this.item = item; this.rarity = rarity; this.spawnLevels = spawnLevels; } } public class PlainItem { public Item item; public string modName; public PlainItem(Item item) { this.item = item; } } public class ShopItem { public Item item; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public int price; public string modName; public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0) { 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_Awake <0>__StartOfRound_Awake; public static hook_Awake <1>__Terminal_Awake; } 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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>__Terminal_Awake; if (obj2 == null) { hook_Awake val2 = Terminal_Awake; <>O.<1>__Terminal_Awake = val2; obj2 = (object)val2; } Terminal.Awake += (hook_Awake)obj2; } private static void Terminal_Awake(orig_Awake orig, Terminal self) { //IL_02fe: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Expected O, but got Unknown //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_037d: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Expected O, but got Unknown //IL_03e9: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_03f6: Unknown result type (might be due to invalid IL or missing references) //IL_0403: Expected O, but got Unknown //IL_0497: Unknown result type (might be due to invalid IL or missing references) //IL_049c: Unknown result type (might be due to invalid IL or missing references) //IL_04a4: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Expected O, but got Unknown List<Item> list = self.buyableItemsList.ToList(); TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val2 = 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)) { Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping")); continue; } if (item.price == -1) { item.price = item.item.creditsWorth; } else { item.item.creditsWorth = item.price; } list.Add(item.item); string itemName = item.item.itemName; char c = itemName[itemName.Length - 1]; string text = itemName; TerminalNode val3 = item.buyNode2; if ((Object)(object)val3 == (Object)null) { val3 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val3).name = itemName.Replace(" ", "-") + "BuyNode2"; val3.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"; val3.clearPreviousText = true; val3.maxCharactersToType = 15; } val3.buyItemIndex = list.Count - 1; val3.isConfirmationNode = false; val3.itemCost = item.price; val3.playSyncedClip = 0; TerminalNode val4 = item.buyNode1; if ((Object)(object)val4 == (Object)null) { val4 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val4).name = itemName.Replace(" ", "-") + "BuyNode1"; val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val4.clearPreviousText = true; val4.maxCharactersToType = 35; } val4.buyItemIndex = list.Count - 1; val4.isConfirmationNode = true; val4.overrideOptions = true; val4.itemCost = item.price; val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val3 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; TerminalKeyword val5 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val); List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(val5); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = val5, result = val4 }); val.compatibleNouns = list3.ToArray(); TerminalNode val6 = item.itemInfo; if ((Object)(object)val6 == (Object)null) { val6 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val6).name = itemName.Replace(" ", "-") + "InfoNode"; val6.displayText = "[No information about this object was found.]\n\n"; val6.clearPreviousText = true; val6.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val2.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = val5, result = val6 }); val2.compatibleNouns = list4.ToArray(); Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.item.itemName)); } self.buyableItemsList = list.ToArray(); orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Expected O, but got Unknown orig.Invoke(self); foreach (ScrapItem scrapItem in scrapItems) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = scrapItem.spawnLevels.HasFlag(Levels.LevelTypes.All) || (scrapItem.spawnLevelOverrides != null && scrapItem.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); 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 || scrapItem.spawnLevels.HasFlag(levelTypes)) { SpawnableItemWithRarity item2 = new SpawnableItemWithRarity { spawnableItem = scrapItem.item, rarity = scrapItem.rarity }; if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item)) { val.spawnableScrap.Add(item2); } } } } foreach (ScrapItem scrapItem2 in scrapItems) { if (!self.allItemsList.itemsList.Contains(scrapItem2.item)) { Plugin.logger.LogInfo((object)(scrapItem2.modName + " registered item: " + scrapItem2.item.itemName)); self.allItemsList.itemsList.Add(scrapItem2.item); } } foreach (ShopItem shopItem in shopItems) { if (!self.allItemsList.itemsList.Contains(shopItem.item)) { Plugin.logger.LogInfo((object)(shopItem.modName + " registered item: " + shopItem.item.itemName)); self.allItemsList.itemsList.Add(shopItem.item); } } foreach (PlainItem plainItem in plainItems) { if (!self.allItemsList.itemsList.Contains(plainItem.item)) { Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName)); self.allItemsList.itemsList.Add(plainItem.item); } } } public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags) { ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.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) { ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags, levelOverrides); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.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); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.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); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; shopItem2.modName = name; shopItems.Add(shopItem2); } public static void RegisterItem(Item plainItem) { PlainItem plainItem2 = new PlainItem(plainItem); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; plainItem2.modName = name; plainItems.Add(plainItem2); } } 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, Vanilla = 0x3FC, All = -1 } } 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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>(); RandomMapObject[] array2 = array; foreach (RandomMapObject val in array2) { 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) { 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 (!(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 mapObject2 = mapObject.mapObject; if (mapObject.spawnRateFunction != null) { mapObject2.numberToSpawn = mapObject.spawnRateFunction(val); } List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList(); list2.Add(mapObject2); val.spawnableMapObjects = list2.ToArray(); Plugin.logger.LogInfo((object)("Added " + ((Object)mapObject2.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 outsideObject = mapObject.outsideObject; if (mapObject.spawnRateFunction != null) { outsideObject.randomAmount = mapObject.spawnRateFunction(val); } List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList(); list4.Add(outsideObject); val.spawnableOutsideObjects = list4.ToArray(); Plugin.logger.LogInfo((object)("Added " + ((Object)outsideObject.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 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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) { _networkPrefabs.Add(prefab); } private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self) { orig.Invoke(self); foreach (GameObject networkPrefab in _networkPrefabs) { ((Component)self).GetComponent<NetworkManager>().AddNetworkPrefab(networkPrefab); } } } public class Shaders { public static void FixShaders(GameObject gameObject) { Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>(); foreach (Renderer val in componentsInChildren) { Material[] materials = val.materials; foreach (Material val2 in materials) { if (((Object)val2.shader).name.Contains("Standard")) { val2.shader = Shader.Find("HDRP/Lit"); } } } } } public class TerminalUtils { public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false) { TerminalKeyword val = ScriptableObject.CreateInstance<TerminalKeyword>(); ((Object)val).name = word; val.word = word; val.isVerb = isVerb; val.compatibleNouns = compatibleNouns; val.specialKeywordResult = specialKeywordResult; val.defaultVerb = defaultVerb; val.accessTerminalObjects = accessTerminalObjects; return val; } } public enum StoreType { None, ShipUpgrade, Decor } public class Unlockables { public class RegisteredUnlockable { public UnlockableItem unlockable; public StoreType StoreType; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public int price; public string modName; public RegisteredUnlockable(UnlockableItem unlockable, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { this.unlockable = unlockable; this.buyNode1 = buyNode1; this.buyNode2 = buyNode2; this.itemInfo = itemInfo; this.price = price; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_Start <1>__Terminal_Start; public static hook_TextPostProcess <2>__Terminal_TextPostProcess; } public static List<RegisteredUnlockable> registeredUnlockables = new List<RegisteredUnlockable>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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>__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>__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) { if (modifiedDisplayText.Contains("[buyableItemsList]") && modifiedDisplayText.Contains("[unlockablesSelectionList]")) { int num = modifiedDisplayText.IndexOf(":"); foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables) { if (registeredUnlockable.StoreType == StoreType.ShipUpgrade) { string unlockableName = registeredUnlockable.unlockable.unlockableName; int price = registeredUnlockable.price; string value = $"\n* {unlockableName} // Price: ${price}"; modifiedDisplayText = modifiedDisplayText.Insert(num + 1, value); } } } return orig.Invoke(self, modifiedDisplayText, node); } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0390: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) //IL_03d3: Expected O, but got Unknown //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Expected O, but got Unknown //IL_049e: Unknown result type (might be due to invalid IL or missing references) //IL_04a3: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04bd: Expected O, but got Unknown //IL_0551: Unknown result type (might be due to invalid IL or missing references) //IL_0556: Unknown result type (might be due to invalid IL or missing references) //IL_0563: Unknown result type (might be due to invalid IL or missing references) //IL_0570: Expected O, but got Unknown TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); List<RegisteredUnlockable> list = registeredUnlockables.FindAll((RegisteredUnlockable unlockable) => unlockable.price != -1).ToList(); Plugin.logger.LogInfo((object)$"Adding {list.Count} items to terminal"); foreach (RegisteredUnlockable item in list) { string unlockableName = item.unlockable.unlockableName; TerminalKeyword keyword3 = TerminalUtils.CreateTerminalKeyword(unlockableName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val); if (self.terminalNodes.allKeywords.Any((TerminalKeyword kw) => kw.word == keyword3.word)) { Plugin.logger.LogInfo((object)("Keyword " + keyword3.word + " already registed, skipping.")); continue; } int shipUnlockableID = StartOfRound.Instance.unlockablesList.unlockables.FindIndex((UnlockableItem unlockable) => unlockable.unlockableName == item.unlockable.unlockableName); StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { Debug.Log((object)"STARTOFROUND INSTANCE NOT FOUND"); } if (item.price == -1 && (Object)(object)item.buyNode1 != (Object)null) { item.price = item.buyNode1.itemCost; } char c = unlockableName[unlockableName.Length - 1]; string text = unlockableName; TerminalNode val3 = item.buyNode2; if ((Object)(object)val3 == (Object)null) { val3 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val3).name = unlockableName.Replace(" ", "-") + "BuyNode2"; val3.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"; val3.clearPreviousText = true; val3.maxCharactersToType = 15; } val3.buyItemIndex = -1; val3.shipUnlockableID = shipUnlockableID; val3.buyUnlockable = true; val3.creatureName = unlockableName; val3.isConfirmationNode = false; val3.itemCost = item.price; val3.playSyncedClip = 0; TerminalNode val4 = item.buyNode1; if ((Object)(object)val4 == (Object)null) { val4 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val4).name = unlockableName.Replace(" ", "-") + "BuyNode1"; val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val4.clearPreviousText = true; val4.maxCharactersToType = 35; } val4.buyItemIndex = -1; val4.shipUnlockableID = shipUnlockableID; val4.creatureName = unlockableName; val4.isConfirmationNode = true; val4.overrideOptions = true; val4.itemCost = item.price; val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val3 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; if (item.StoreType == StoreType.Decor) { item.unlockable.shopSelectionNode = val4; } else { item.unlockable.shopSelectionNode = null; } List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(keyword3); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = keyword3, result = val4 }); val.compatibleNouns = list3.ToArray(); TerminalNode val5 = item.itemInfo; if ((Object)(object)val5 == (Object)null) { val5 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val5).name = unlockableName.Replace(" ", "-") + "InfoNode"; val5.displayText = "[No information about this object was found.]\n\n"; val5.clearPreviousText = true; val5.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val2.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = keyword3, result = val5 }); val2.compatibleNouns = list4.ToArray(); Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.unlockable.unlockableName)); } orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { orig.Invoke(self); Plugin.logger.LogInfo((object)$"Adding {registeredUnlockables.Count} unlockables to unlockables list"); foreach (RegisteredUnlockable unlockable in registeredUnlockables) { if (self.unlockablesList.unlockables.Any((UnlockableItem x) => x.unlockableName == unlockable.unlockable.unlockableName)) { Plugin.logger.LogInfo((object)("Unlockable " + unlockable.unlockable.unlockableName + " already exists in unlockables list, skipping")); continue; } if ((Object)(object)unlockable.unlockable.prefabObject != (Object)null) { PlaceableShipObject componentInChildren = unlockable.unlockable.prefabObject.GetComponentInChildren<PlaceableShipObject>(); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.unlockableID = self.unlockablesList.unlockables.Count; } } self.unlockablesList.unlockables.Add(unlockable.unlockable); } } public static void RegisterUnlockable(UnlockableItemDef unlockable, int price = -1, StoreType storeType = StoreType.None) { RegisterUnlockable(unlockable.unlockable, storeType, null, null, null, price); } public static void RegisterUnlockable(UnlockableItem unlockable, int price = -1, StoreType storeType = StoreType.None) { RegisterUnlockable(unlockable, storeType, null, null, null, price); } public static void RegisterUnlockable(UnlockableItemDef unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { RegisterUnlockable(unlockable.unlockable, storeType, buyNode1, buyNode2, itemInfo, price); } public static void RegisterUnlockable(UnlockableItem unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { RegisteredUnlockable registeredUnlockable = new RegisteredUnlockable(unlockable, buyNode1, buyNode2, itemInfo, price); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; registeredUnlockable.modName = name; registeredUnlockable.StoreType = storeType; registeredUnlockables.Add(registeredUnlockable); } } public class Weathers { public class CustomWeather { public string name; public int weatherVariable1; public int weatherVariable2; public WeatherEffect weatherEffect; public Levels.LevelTypes levels; public string[] spawnLevelOverrides; public CustomWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null, int weatherVariable1 = 0, int weatherVariable2 = 0) { this.name = name; this.weatherVariable1 = weatherVariable1; this.weatherVariable2 = weatherVariable2; this.weatherEffect = weatherEffect; this.levels = levels; this.spawnLevelOverrides = spawnLevelOverrides; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__TimeOfDay_Awake; public static hook_Awake <1>__StartOfRound_Awake; } public static Dictionary<int, CustomWeather> customWeathers = new Dictionary<int, CustomWeather>(); public static int numCustomWeathers = 0; public static void Init() { //IL_002f: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //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_0071: Expected O, but got Unknown new Hook((MethodBase)typeof(Enum).GetMethod("ToString", new Type[0]), typeof(Weathers).GetMethod("ToStringHook")); object obj = <>O.<0>__TimeOfDay_Awake; if (obj == null) { hook_Awake val = TimeOfDay_Awake; <>O.<0>__TimeOfDay_Awake = val; obj = (object)val; } TimeOfDay.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__StartOfRound_Awake; if (obj2 == null) { hook_Awake val2 = StartOfRound_Awake; <>O.<1>__StartOfRound_Awake = val2; obj2 = (object)val2; } StartOfRound.Awake += (hook_Awake)obj2; } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { //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_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Expected O, but got Unknown foreach (KeyValuePair<int, CustomWeather> customWeather in customWeathers) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = customWeather.Value.levels.HasFlag(Levels.LevelTypes.All) || (customWeather.Value.spawnLevelOverrides != null && customWeather.Value.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag) { Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); List<RandomWeatherWithVariables> list = val.randomWeathers.ToList(); if (flag || customWeather.Value.levels.HasFlag(levelTypes)) { list.Add(new RandomWeatherWithVariables { weatherType = (LevelWeatherType)customWeather.Key, weatherVariable = customWeather.Value.weatherVariable1, weatherVariable2 = customWeather.Value.weatherVariable2 }); Plugin.logger.LogInfo((object)$"Added weather {customWeather.Value.name} to level {((Object)val).name} at weather index: {customWeather.Key}"); } val.randomWeathers = list.ToArray(); } } } orig.Invoke(self); } private static void TimeOfDay_Awake(orig_Awake orig, TimeOfDay self) { List<WeatherEffect> list = self.effects.ToList(); int num = 0; foreach (KeyValuePair<int, CustomWeather> customWeather in customWeathers) { if (customWeather.Key > num) { num = customWeather.Key; } } while (list.Count <= num) { list.Add(null); } foreach (KeyValuePair<int, CustomWeather> customWeather2 in customWeathers) { list[customWeather2.Key] = customWeather2.Value.weatherEffect; } self.effects = list.ToArray(); orig.Invoke(self); } public static string ToStringHook(Func<Enum, string> orig, Enum self) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected I4, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected I4, but got Unknown if (self.GetType() == typeof(LevelWeatherType) && customWeathers.ContainsKey((int)(LevelWeatherType)(object)self)) { return customWeathers[(int)(LevelWeatherType)(object)self].name; } return orig(self); } public static void RegisterWeather(WeatherDef weather) { RegisterWeather(weather.weatherName, weather.weatherEffect, weather.levels, weather.levelOverrides, weather.weatherVariable1, weather.weatherVariable2); } public static void RegisterWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, int weatherVariable1 = 0, int weatherVariable2 = 0) { Array values = Enum.GetValues(typeof(LevelWeatherType)); int num = values.Length - 1; num += numCustomWeathers; numCustomWeathers++; Plugin.logger.LogInfo((object)$"Registering weather {name} at index {num - 1}"); customWeathers.Add(num, new CustomWeather(name, weatherEffect, levels, null, weatherVariable1, weatherVariable2)); } public static void RegisterWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null, int weatherVariable1 = 0, int weatherVariable2 = 0) { Array values = Enum.GetValues(typeof(LevelWeatherType)); int num = values.Length - 1; num += numCustomWeathers; numCustomWeathers++; Plugin.logger.LogInfo((object)$"Registering weather {name} at index {num - 1}"); customWeathers.Add(num, new CustomWeather(name, weatherEffect, levels, spawnLevelOverrides, weatherVariable1, weatherVariable2)); } } } namespace LethalLib.Extras { [CreateAssetMenu(menuName = "ScriptableObjects/DungeonDef")] public class DungeonDef : ScriptableObject { public DungeonFlow dungeonFlow; [Range(0f, 300f)] public int rarity; public AudioClip firstTimeDungeonAudio; } [CreateAssetMenu(menuName = "ScriptableObjects/DungeonGraphLine")] public class DungeonGraphLineDef : ScriptableObject { public GraphLine graphLine; } [CreateAssetMenu(menuName = "ScriptableObjects/GameObjectChance")] public class GameObjectChanceDef : ScriptableObject { public GameObjectChance gameObjectChance; } [CreateAssetMenu(menuName = "ScriptableObjects/SpawnableMapObject")] public class SpawnableMapObjectDef : ScriptableObject { public SpawnableMapObject spawnableMapObject; } [CreateAssetMenu(menuName = "ScriptableObjects/SpawnableOutsideObject")] public class SpawnableOutsideObjectDef : ScriptableObject { public SpawnableOutsideObjectWithRarity spawnableMapObject; } [CreateAssetMenu(menuName = "ScriptableObjects/UnlockableItem")] public class UnlockableItemDef : ScriptableObject { public StoreType storeType = StoreType.None; public UnlockableItem unlockable; } [CreateAssetMenu(menuName = "ScriptableObjects/WeatherDef")] public class WeatherDef : ScriptableObject { public string weatherName; public Levels.LevelTypes levels = Levels.LevelTypes.None; public string[] levelOverrides; public int weatherVariable1; public int weatherVariable2; public WeatherEffect weatherEffect; } }
plugins/LethalPresents.dll
Decompiled a year 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.Logging; using Microsoft.CodeAnalysis; using On; 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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalPresents")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("LethalPresents mod")] [assembly: AssemblyFileVersion("1.0.4.0")] [assembly: AssemblyInformationalVersion("1.0.4")] [assembly: AssemblyProduct("LethalPresents")] [assembly: AssemblyTitle("LethalPresents")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.4.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 LethalPresents { [BepInPlugin("LethalPresents", "LethalPresents", "1.0.4")] public class LethalPresentsPlugin : BaseUnityPlugin { public static ManualLogSource mls; private static int spawnChance = 5; private static string[] disabledEnemies = new string[0]; private static bool IsAllowlist = false; private static bool ShouldSpawnMines = false; private static bool ShouldSpawnTurrets = false; private static bool ShouldSpawnBees = false; private static bool isHost => ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost; private static SelectableLevel currentLevel => RoundManager.Instance.currentLevel; internal static T GetPrivateField<T>(object instance, string fieldName) { FieldInfo field = instance.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic); return (T)field.GetValue(instance); } private void Awake() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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 mls = Logger.CreateLogSource("LethalPresents"); mls.LogInfo((object)"Plugin LethalPresents is loaded!"); loadConfig(); RoundManager.AdvanceHourAndSpawnNewBatchOfEnemies += new hook_AdvanceHourAndSpawnNewBatchOfEnemies(updateCurrentLevelInfo); GiftBoxItem.OpenGiftBoxServerRpc += new hook_OpenGiftBoxServerRpc(spawnRandomEntity); } private void updateCurrentLevelInfo(orig_AdvanceHourAndSpawnNewBatchOfEnemies orig, RoundManager self) { orig.Invoke(self); mls.LogInfo((object)"List of spawnable enemies (inside):"); currentLevel.Enemies.ForEach(delegate(SpawnableEnemyWithRarity e) { mls.LogInfo((object)((Object)e.enemyType).name); }); mls.LogInfo((object)"List of spawnable enemies (outside):"); currentLevel.OutsideEnemies.ForEach(delegate(SpawnableEnemyWithRarity e) { mls.LogInfo((object)((Object)e.enemyType).name); }); } private void loadConfig() { spawnChance = ((BaseUnityPlugin)this).Config.Bind<int>("General", "SpawnChance", 5, "Chance of spawning an enemy when opening a present [0-100]").Value; disabledEnemies = ((BaseUnityPlugin)this).Config.Bind<string>("General", "EnemyBlocklist", "", "Enemy blocklist separated by , and without whitespaces").Value.Split(","); IsAllowlist = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "IsAllowlist", false, "Turns blocklist into allowlist, blocklist must contain at least one inside and one outside enemy, use at your own risk").Value; ShouldSpawnMines = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShouldSpawnMines", true, "Add mines to the spawn pool").Value; ShouldSpawnTurrets = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShouldSpawnTurrets", true, "Add turrets to the spawn pool").Value; if (IsAllowlist) { mls.LogInfo((object)"Only following enemies can spawn from the gift:"); } else { mls.LogInfo((object)"Following enemies wont be spawned from the gift:"); } string[] array = disabledEnemies; foreach (string text in array) { mls.LogInfo((object)text); } } private void spawnRandomEntity(orig_OpenGiftBoxServerRpc orig, GiftBoxItem self) { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)self).NetworkManager; if (networkManager == null || !networkManager.IsListening) { orig.Invoke(self); return; } int privateField = GetPrivateField<int>(self, "__rpc_exec_stage"); mls.LogInfo((object)("IsServer:" + networkManager.IsServer + " IsHost:" + networkManager.IsHost + " __rpc_exec_stage:" + privateField)); if (privateField != 1 || !isHost) { orig.Invoke(self); return; } int num = Random.Range(1, 100); mls.LogInfo((object)("Player's fortune:" + num)); if (num >= spawnChance) { orig.Invoke(self); return; } chooseAndSpawnEnemy(((GrabbableObject)self).isInFactory, ((Component)self).transform.position, ((Component)self.previousPlayerHeldBy).transform.position); orig.Invoke(self); } private static void chooseAndSpawnEnemy(bool inside, Vector3 pos, Vector3 player_pos) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_013f: 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_014a: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_036e: 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_038a: Unknown result type (might be due to invalid IL or missing references) ManualLogSource obj = mls; Vector3 val = player_pos; obj.LogInfo((object)("Player pos " + ((object)(Vector3)(ref val)).ToString())); List<SpawnableEnemyWithRarity> list = currentLevel.Enemies.Where((SpawnableEnemyWithRarity e) => disabledEnemies.Contains(((Object)e.enemyType).name) ? IsAllowlist : (!IsAllowlist)).ToList(); List<SpawnableEnemyWithRarity> list2 = currentLevel.OutsideEnemies.Where((SpawnableEnemyWithRarity e) => disabledEnemies.Contains(((Object)e.enemyType).name) ? IsAllowlist : (!IsAllowlist)).ToList(); int num = Random.Range(1, 2 + (list2.Count + list.Count) / 2); if (num == 2 && !ShouldSpawnMines) { num = 1; } if (num == 1 && !ShouldSpawnTurrets) { num = 2; } if (num == 2 && !ShouldSpawnMines) { num = 3; } switch (num) { case 1: { SpawnableMapObject[] spawnableMapObjects2 = currentLevel.spawnableMapObjects; foreach (SpawnableMapObject val4 in spawnableMapObjects2) { if (!((Object)(object)val4.prefabToSpawn.GetComponentInChildren<Turret>() == (Object)null)) { pos -= Vector3.up * 1.8f; GameObject val5 = Object.Instantiate<GameObject>(val4.prefabToSpawn, pos, Quaternion.identity); val5.transform.position = pos; Transform transform = val5.transform; val = player_pos - pos; transform.forward = ((Vector3)(ref val)).normalized; val5.GetComponent<NetworkObject>().Spawn(true); ManualLogSource obj3 = mls; val = pos; obj3.LogInfo((object)("Tried spawning a turret at " + ((object)(Vector3)(ref val)).ToString())); break; } } return; } case 2: { SpawnableMapObject[] spawnableMapObjects = currentLevel.spawnableMapObjects; foreach (SpawnableMapObject val2 in spawnableMapObjects) { if (!((Object)(object)val2.prefabToSpawn.GetComponentInChildren<Landmine>() == (Object)null)) { pos -= Vector3.up * 1.8f; GameObject val3 = Object.Instantiate<GameObject>(val2.prefabToSpawn, pos, Quaternion.identity); val3.transform.position = pos; val3.transform.forward = new Vector3(1f, 0f, 0f); val3.GetComponent<NetworkObject>().Spawn(true); ManualLogSource obj2 = mls; val = pos; obj2.LogInfo((object)("Tried spawning a mine at " + ((object)(Vector3)(ref val)).ToString())); break; } } return; } } SpawnableEnemyWithRarity val6; if (inside) { if (list.Count < 1) { mls.LogInfo((object)"Cant spawn enemy - no other enemies present to copy from"); return; } val6 = list[Random.Range(0, list.Count - 1)]; } else { if (list2.Count < 1) { mls.LogInfo((object)"Cant spawn enemy - no other enemies present to copy from"); return; } val6 = list2[Random.Range(0, list2.Count - 1)]; } pos += Vector3.up * 0.25f; ManualLogSource obj4 = mls; string enemyName = val6.enemyType.enemyName; val = pos; obj4.LogInfo((object)("Spawning " + enemyName + " at " + ((object)(Vector3)(ref val)).ToString())); SpawnEnemy(val6, pos, 0f); } private static void SpawnEnemy(SpawnableEnemyWithRarity enemy, Vector3 pos, float rot) { //IL_0006: 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) RoundManager.Instance.SpawnEnemyGameObject(pos, rot, -1, enemy.enemyType); } } public static class PluginInfo { public const string PLUGIN_GUID = "LethalPresents"; public const string PLUGIN_NAME = "LethalPresents"; public const string PLUGIN_VERSION = "1.0.4"; } }
plugins/MaskedEnemyRework.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; 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.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using MaskedEnemyRework.Patches; using Microsoft.CodeAnalysis; using MoreCompany; using MoreCompany.Cosmetics; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyCompany("MaskedEnemyRework")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("2.4.0.0")] [assembly: AssemblyInformationalVersion("2.4.0")] [assembly: AssemblyProduct("MaskedEnemyRework")] [assembly: AssemblyTitle("MaskedEnemyRework")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.4.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace MaskedEnemyRework { [BepInPlugin("MaskedEnemyRework", "MaskedEnemyRework", "2.4.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("MaskedEnemyRework"); private static Plugin Instance; internal ManualLogSource logger; public static List<int> PlayerMimicList; public static int PlayerMimicIndex; private ConfigEntry<bool> RemoveMasksConfig; private ConfigEntry<bool> RevealMasksConfig; private ConfigEntry<bool> RemoveZombieArmsConfig; private ConfigEntry<bool> UseSpawnRarityConfig; private ConfigEntry<int> SpawnRarityConfig; private ConfigEntry<bool> CanSpawnOutsideConfig; private ConfigEntry<int> MaxSpawnCountConfig; private ConfigEntry<bool> ZombieApocalypeModeConfig; private ConfigEntry<bool> UseVanillaSpawnsConfig; private ConfigEntry<int> ZombieApocalypeRandomChanceConfig; private ConfigEntry<float> InsideEnemySpawnCurveConfig; private ConfigEntry<float> MiddayInsideEnemySpawnCurveConfig; private ConfigEntry<float> StartOutsideEnemySpawnCurveConfig; private ConfigEntry<float> MidOutsideEnemySpawnCurveConfig; private ConfigEntry<float> EndOutsideEnemySpawnCurveConfig; public static bool RemoveMasks; public static bool RevealMasks; public static bool RemoveZombieArms; public static bool UseSpawnRarity; public static int SpawnRarity; public static bool CanSpawnOutside; public static int MaxSpawnCount; public static bool ZombieApocalypseMode; public static bool UseVanillaSpawns; public static int RandomChanceZombieApocalypse; public static float InsideEnemySpawnCurve; public static float MiddayInsideEnemySpawnCurve; public static float StartOutsideEnemySpawnCurve; public static float MidOutsideEnemySpawnCurve; public static float EndOutsideEnemySpawnCurve; public static int InitialPlayerCount; public static SpawnableEnemyWithRarity maskedPrefab; public static SpawnableEnemyWithRarity flowerPrefab; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } PlayerMimicList = new List<int>(); PlayerMimicIndex = 0; InitialPlayerCount = 0; RemoveMasksConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Remove Mask From Masked Enemy", true, "Whether or not the Masked Enemy has a mask on."); RevealMasksConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Reveal Mask When Attacking", false, "The enemy would reveal their mask permanently after trying to attack someone. Mask would be off until the attempt to attack is made"); RemoveZombieArmsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Remove Zombie Arms", true, "Remove the animation where the Masked raise arms like a zombie."); UseVanillaSpawnsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Use Vanilla Spawns", false, "Ignores anything else in this mod. Only uses the above settings from this config. Will not spawn on all moons. will ignore EVERYTHING in the config below this point."); UseSpawnRarityConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawns", "Use Spawn Rarity", false, "Use custom spawn rate from config. If this is false, the masked spawns at the same rate as the Bracken. If true, will spawn at whatever rarity is given in Spawn Rarity config option"); SpawnRarityConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Spawns", "Spawn Rarity", 15, "The rarity for the Masked Enemy to spawn. The higher the number, the more likely to spawn. Can go to 1000000000, any higher will break. Use Spawn Rarity must be set to True"); CanSpawnOutsideConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawns", "Allow Masked To Spawn Outside", false, "Whether the Masked Enemy can spawn outside the building"); MaxSpawnCountConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Spawns", "Max Number of Masked", 2, "Max Number of possible masked to spawn in one level"); ZombieApocalypeModeConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Zombie Apocalypse Mode", "Zombie Apocalype Mode", false, "Only spawns Masked! Make sure to crank up the Max Spawn Count in this config! Would also recommend bringing a gun (mod), a shovel works fine too though.... This mode does not play nice with other mods that affect spawn rates. Disable those before playing for best results"); ZombieApocalypeRandomChanceConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Zombie Apocalypse Mode", "Random Zombie Apocalype Mode", -1, "[Must Be Whole Number] The percent chance from 1 to 100 that a day could contain a zombie apocalypse. Put at -1 to never have the chance arise and don't have Only Spawn Masked turned on"); InsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "StartOfDay Inside Masked Spawn Curve", 0.1f, "Spawn curve for masked inside, start of the day. Crank this way up for immediate action. More info in the readme"); MiddayInsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "Midday Inside Masked Spawn Curve", 500f, "Spawn curve for masked inside, midday."); StartOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "StartOfDay Masked Outside Spawn Curve", -30f, "Spawn curve for outside masked, start of the day."); MidOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "Midday Outside Masked Spawn Curve", -30f, "Spawn curve for outside masked, midday."); EndOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "EOD Outside Masked Spawn Curve", 10f, "Spawn curve for outside masked, end of day"); RemoveMasks = RemoveMasksConfig.Value; RevealMasks = RevealMasksConfig.Value; UseVanillaSpawns = UseVanillaSpawnsConfig.Value; RemoveZombieArms = RemoveZombieArmsConfig.Value; UseSpawnRarity = UseSpawnRarityConfig.Value; CanSpawnOutside = CanSpawnOutsideConfig.Value; MaxSpawnCount = MaxSpawnCountConfig.Value; SpawnRarity = SpawnRarityConfig.Value; ZombieApocalypseMode = ZombieApocalypeModeConfig.Value; InsideEnemySpawnCurve = InsideEnemySpawnCurveConfig.Value; MiddayInsideEnemySpawnCurve = MiddayInsideEnemySpawnCurveConfig.Value; StartOutsideEnemySpawnCurve = StartOutsideEnemySpawnCurveConfig.Value; MidOutsideEnemySpawnCurve = MaxSpawnCountConfig.Value; EndOutsideEnemySpawnCurve = EndOutsideEnemySpawnCurveConfig.Value; RandomChanceZombieApocalypse = ZombieApocalypeRandomChanceConfig.Value; logger = Logger.CreateLogSource("MaskedEnemyRework"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MaskedEnemyRework is loaded! Woohoo!"); harmony.PatchAll(typeof(Plugin)); harmony.PatchAll(typeof(GetMaskedPrefabForLaterUse)); harmony.PatchAll(typeof(MaskedVisualRework)); harmony.PatchAll(typeof(MaskedSpawnSettings)); } } public static class PluginInfo { public const string PLUGIN_GUID = "MaskedEnemyRework"; public const string PLUGIN_NAME = "MaskedEnemyRework"; public const string PLUGIN_VERSION = "2.4.0"; } } namespace MaskedEnemyRework.Patches { [HarmonyPatch(typeof(Terminal))] internal class GetMaskedPrefabForLaterUse { [HarmonyPatch("Start")] [HarmonyPostfix] private static void SavesPrefabForLaterUse(ref SelectableLevel[] ___moonsCatalogueList) { ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework"); SelectableLevel[] array = ___moonsCatalogueList; foreach (SelectableLevel val2 in array) { foreach (SpawnableEnemyWithRarity enemy in val2.Enemies) { if (enemy.enemyType.enemyName == "Masked") { val.LogInfo((object)"Found Masked!"); Plugin.maskedPrefab = enemy; } else if (enemy.enemyType.enemyName == "Flowerman") { Plugin.flowerPrefab = enemy; val.LogInfo((object)"Found Flowerman!"); } } } } } [HarmonyPatch(typeof(RoundManager))] internal class MaskedSpawnSettings { [HarmonyPatch("BeginEnemySpawning")] [HarmonyPrefix] private static void UpdateSpawnRates(ref SelectableLevel ___currentLevel) { //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_024f: 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_0263: Expected O, but got Unknown //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Expected O, but got Unknown //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Expected O, but got Unknown if (Plugin.UseVanillaSpawns) { return; } ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework"); val.LogInfo((object)"Starting Round Manager"); SpawnableEnemyWithRarity maskedPrefab = Plugin.maskedPrefab; SpawnableEnemyWithRarity val2 = Plugin.flowerPrefab; SelectableLevel obj = ___currentLevel; obj.maxEnemyPowerCount += maskedPrefab.enemyType.MaxCount; SelectableLevel obj2 = ___currentLevel; obj2.maxDaytimeEnemyPowerCount += maskedPrefab.enemyType.MaxCount; SelectableLevel obj3 = ___currentLevel; obj3.maxOutsideEnemyPowerCount += maskedPrefab.enemyType.MaxCount; List<SpawnableEnemyWithRarity> enemies = ___currentLevel.Enemies; for (int i = 0; i < ___currentLevel.Enemies.Count; i++) { SpawnableEnemyWithRarity val3 = ___currentLevel.Enemies[i]; if (val3.enemyType.enemyName == "Masked") { enemies.Remove(val3); } if (val3.enemyType.enemyName == "Flowerman") { val2 = val3; } } ___currentLevel.Enemies = enemies; maskedPrefab.enemyType.PowerLevel = 1; maskedPrefab.enemyType.probabilityCurve = val2.enemyType.probabilityCurve; if (Plugin.UseSpawnRarity) { maskedPrefab.rarity = Plugin.SpawnRarity; } else { maskedPrefab.rarity = val2.rarity; } maskedPrefab.enemyType.MaxCount = Plugin.MaxSpawnCount; maskedPrefab.enemyType.isOutsideEnemy = Plugin.CanSpawnOutside; int num = 0; num = ((StartOfRound.Instance.randomMapSeed.ToString().Length >= 3) ? int.Parse(StartOfRound.Instance.randomMapSeed.ToString().Substring(1, 2)) : 0); val.LogInfo((object)("Map seed " + num + " random chance " + Plugin.RandomChanceZombieApocalypse)); num = Mathf.Clamp(num, 0, 100); if (Plugin.ZombieApocalypseMode || (num <= Plugin.RandomChanceZombieApocalypse && Plugin.RandomChanceZombieApocalypse >= 0)) { val.LogInfo((object)"ZOMBIE APOCALYPSE"); ___currentLevel.enemySpawnChanceThroughoutDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2] { new Keyframe(0f, Plugin.InsideEnemySpawnCurve), new Keyframe(0.5f, Plugin.MiddayInsideEnemySpawnCurve) }); ___currentLevel.daytimeEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2] { new Keyframe(0f, 7f), new Keyframe(0.5f, 7f) }); ___currentLevel.outsideEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[3] { new Keyframe(0f, Plugin.StartOutsideEnemySpawnCurve), new Keyframe(20f, Plugin.MidOutsideEnemySpawnCurve), new Keyframe(21f, Plugin.EndOutsideEnemySpawnCurve) }); ___currentLevel.DaytimeEnemies.Clear(); ___currentLevel.OutsideEnemies.Clear(); maskedPrefab.rarity = 1000000000; foreach (SpawnableEnemyWithRarity enemy in ___currentLevel.Enemies) { enemy.rarity = 0; } if (Plugin.CanSpawnOutside) { maskedPrefab.enemyType.isOutsideEnemy = true; ___currentLevel.OutsideEnemies.Add(maskedPrefab); ___currentLevel.DaytimeEnemies.Add(maskedPrefab); } } else { val.LogInfo((object)"no zombies :("); } ___currentLevel.Enemies.Add(maskedPrefab); } } [HarmonyPatch(typeof(MaskedPlayerEnemy))] internal class MaskedVisualRework { private static int randomPlayerIndex; private static IEnumerator coroutine; [HarmonyPatch("Start")] [HarmonyPostfix] private static void ReformVisuals(ref MaskedPlayerEnemy __instance) { //IL_0067: 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_00a4: Unknown result type (might be due to invalid IL or missing references) ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework"); PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; int num = StartOfRound.Instance.ClientPlayerList.Count; if (num == 0) { num = 1; val.LogInfo((object)"Player count was zero"); } if (Plugin.PlayerMimicList.Count <= 1 || Plugin.InitialPlayerCount != num) { Plugin.InitialPlayerCount = num; State state = Random.state; Random.InitState(1234); for (int i = 0; i < 50; i++) { Plugin.PlayerMimicList.Add(Random.Range(0, num)); } Random.state = state; } randomPlayerIndex = Plugin.PlayerMimicList[Plugin.PlayerMimicIndex % 50]; randomPlayerIndex = Mathf.Clamp(randomPlayerIndex, 0, num); Plugin.PlayerMimicIndex++; if ((Object)(object)__instance.mimickingPlayer == (Object)null) { __instance.mimickingPlayer = allPlayerScripts[randomPlayerIndex]; } __instance.SetSuit(__instance.mimickingPlayer.currentSuitID); if (Plugin.RemoveMasks || Plugin.RevealMasks) { ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject.SetActive(false); ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskTragedy")).gameObject.SetActive(false); } if (Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany")) { MoreCompanyPatch.ApplyCosmetics(__instance); } } [HarmonyPatch("SetHandsOutClientRpc")] [HarmonyPrefix] private static void MaskAndArmsReveal(ref bool setOut, ref MaskedPlayerEnemy __instance) { GameObject gameObject = ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject; if (Plugin.RevealMasks && !gameObject.activeSelf && ((EnemyAI)__instance).currentBehaviourStateIndex == 1) { IEnumerator enumerator = fadeInAndOut(gameObject, fadeIn: true, 1f); ((MonoBehaviour)__instance).StartCoroutine(enumerator); } if (Plugin.RemoveZombieArms) { setOut = false; } } [HarmonyPatch("SetEnemyOutside")] [HarmonyPostfix] [HarmonyPriority(300)] private static void HideCosmeticsIfMarked(ref MaskedPlayerEnemy __instance) { if (Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany")) { MoreCompanyPatch.ApplyCosmetics(__instance); } } private static IEnumerator fadeInAndOut(GameObject mask, bool fadeIn, float duration) { float counter = 0f; mask.SetActive(true); float startLoc; float endLoc; if (fadeIn) { startLoc = 0.095f; endLoc = 0.215f; } else { startLoc = 0.215f; endLoc = 0.095f; } while (counter < duration) { counter += Time.deltaTime; float loc = Mathf.Lerp(startLoc, endLoc, counter / duration); mask.transform.localPosition = new Vector3(-0.009f, 0.143f, loc); yield return null; } if (!fadeIn) { mask.SetActive(false); } } } internal class MoreCompanyPatch { public static void ApplyCosmetics(MaskedPlayerEnemy masked) { //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) Transform val = ((Component)masked).transform.Find("ScavengerModel").Find("metarig"); CosmeticApplication component = ((Component)val).GetComponent<CosmeticApplication>(); if (Object.op_Implicit((Object)(object)component)) { component.ClearCosmetics(); Object.Destroy((Object)(object)component); } if (!MainClass.showCosmetics) { return; } List<string> list = MainClass.playerIdsAndCosmetics[(int)masked.mimickingPlayer.playerClientId]; component = ((Component)val).gameObject.AddComponent<CosmeticApplication>(); foreach (string item in list) { component.ApplyCosmetic(item, true); } foreach (CosmeticInstance spawnedCosmetic in component.spawnedCosmetics) { Transform transform = ((Component)spawnedCosmetic).transform; transform.localScale *= 0.38f; } } } internal class RemoveZombieArms { [HarmonyPatch(typeof(MaskedPlayerEnemy), "SetHandsOutClientRpc")] [HarmonyPrefix] private static void RemoveArms(ref bool setOut) { if (Plugin.RemoveZombieArms) { setOut = false; } } } }
plugins/MaskTheDead.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; 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 BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using MaskTheDead.Components; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("MaskTheDead")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("If a dead body is next to a mask there's a chance that the body is possesed")] [assembly: AssemblyFileVersion("1.0.3.0")] [assembly: AssemblyInformationalVersion("1.0.3")] [assembly: AssemblyProduct("MaskTheDead")] [assembly: AssemblyTitle("MaskTheDead")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.3.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 MaskTheDead { public class Configuration { private ConfigEntry<float> configPossessionChance; private ConfigEntry<int> configRetryPossesionTime; private ConfigEntry<int> configMaskPossessionRange; private ConfigFile File; public float PossesionChance => configPossessionChance.Value; public int RetryPossesionTime => configRetryPossesionTime.Value; public int MaskPossessionRange => configMaskPossessionRange.Value; public int RetryPossesionMinTime => 10000; public Configuration(ConfigFile config) { File = config; configPossessionChance = File.Bind<float>("General", "PossessionChance", 1f, "A number between 0 and 1 (included) representing the percentage of a body being possessed by a nearby mask"); configRetryPossesionTime = File.Bind<int>("General", "RetryPossesionTime", RetryPossesionMinTime, $"Time in milliseconds after which a mask will attempt to posses a nearby body again, less than {RetryPossesionMinTime} milliseconds is ignored"); configMaskPossessionRange = File.Bind<int>("General", "MaskPossessionRange", 10, "Range, in units, of the mask repossession trigger. Only bodies close enough will be considered for repossessions!"); } } [BepInPlugin("MaskTheDead", "MaskTheDead", "1.0.3")] public class Plugin : BaseUnityPlugin { public static ManualLogSource TheLogger; public static Configuration TheConfiguration; public Plugin() { TheConfiguration = new Configuration(((BaseUnityPlugin)this).Config); } private void Awake() { TheLogger = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MaskTheDead is loaded!"); Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null); } } public static class PluginInfo { public const string PLUGIN_GUID = "MaskTheDead"; public const string PLUGIN_NAME = "MaskTheDead"; public const string PLUGIN_VERSION = "1.0.3"; } } namespace MaskTheDead.Patchers { [HarmonyPatch] public class GrabbableObjectMaskPatcher { [HarmonyPrefix] [HarmonyPatch(typeof(GrabbableObject), "Start")] private static bool StartPatch(ref GrabbableObject __instance) { if ((Object)(object)__instance == (Object)null) { Plugin.TheLogger.LogFatal((object)"This instance is null, cannot patch item"); return true; } GrabbableObject obj = __instance; HauntedMaskItem val = (HauntedMaskItem)(object)((obj is HauntedMaskItem) ? obj : null); if ((Object)(object)val == (Object)null) { return true; } if (!GameNetworkManager.Instance.isHostingGame) { Plugin.TheLogger.LogInfo((object)"Avoding patch for non hosts"); return true; } Plugin.TheLogger.LogInfo((object)"Adding mask watcher to haunted mask!"); ((Component)val).gameObject.AddComponent<MaskTheDeadComponent>(); return true; } } } namespace MaskTheDead.Components { public class MaskTheDeadComponent : NetworkBehaviour { private readonly Dictionary<GameObject, Coroutine> _NearbyBodies = new Dictionary<GameObject, Coroutine>(); private HauntedMaskItem _MaskComponent; private SphereCollider _Collider; public bool PossessionChancePassed => Random.value < Plugin.TheConfiguration.PossesionChance; public bool CanRetryPossession => Plugin.TheConfiguration.RetryPossesionTime >= Plugin.TheConfiguration.RetryPossesionMinTime; private bool CanComponentUseRagdoll(RagdollGrabbableObject ragdoll) { if (((GrabbableObject)ragdoll).isHeld || ((GrabbableObject)ragdoll).isHeldByEnemy) { Plugin.TheLogger.LogInfo((object)"Cant attempt possession of held ragdoll..."); return false; } if (((GrabbableObject)ragdoll).isInShipRoom) { Plugin.TheLogger.LogInfo((object)"Cant attempt possession of body in ship"); return false; } return true; } private void Awake() { _MaskComponent = ((Component)this).gameObject.GetComponent<HauntedMaskItem>(); _Collider = ((Component)this).gameObject.AddComponent<SphereCollider>(); _Collider.radius = Plugin.TheConfiguration.MaskPossessionRange; ((Collider)_Collider).isTrigger = true; } private void Update() { if (ShouldDispose()) { Dispose(); return; } bool num = ((GrabbableObject)_MaskComponent).isHeldByEnemy || ((GrabbableObject)_MaskComponent).isHeld; bool isInShipRoom = ((GrabbableObject)_MaskComponent).isInShipRoom; bool isInElevator = ((GrabbableObject)_MaskComponent).isInElevator; if (num || isInShipRoom || isInElevator) { ((Collider)_Collider).enabled = false; CleanupCoroutines(); } else { ((Collider)_Collider).enabled = true; } } public override void OnDestroy() { Plugin.TheLogger.LogInfo((object)"Destroying repossession component!"); CleanupCoroutines(); ((NetworkBehaviour)this).OnDestroy(); } public override void OnNetworkDespawn() { Plugin.TheLogger.LogInfo((object)"Network despawn, cleaning repossession component!"); ((NetworkBehaviour)this).OnNetworkDespawn(); CleanupCoroutines(); } private void OnTriggerEnter(Collider other) { if (ShouldDispose()) { Dispose(); return; } RagdollGrabbableObject colliderRagdoll = GetColliderRagdoll(other); if ((Object)(object)colliderRagdoll == (Object)null) { Plugin.TheLogger.LogInfo((object)"Object in mask range is not ragdoll"); } else if (CanComponentUseRagdoll(colliderRagdoll) && !_NearbyBodies.ContainsKey(((Component)colliderRagdoll).gameObject)) { _NearbyBodies.Add(((Component)colliderRagdoll).gameObject, null); AttemptPossesion(colliderRagdoll); } } private void OnTriggerExit(Collider other) { Plugin.TheLogger.LogInfo((object)$"Something is leaving the mask range, i have {_NearbyBodies.Count} body nearby!"); RagdollGrabbableObject colliderRagdoll = GetColliderRagdoll(other); Coroutine value; if ((Object)(object)colliderRagdoll == (Object)null) { Plugin.TheLogger.LogInfo((object)"The collider leaving is not of a ragdoll"); } else if (_NearbyBodies.TryGetValue(((Component)colliderRagdoll).gameObject, out value)) { if (value != null) { Plugin.TheLogger.LogInfo((object)"Stopping coroutine for body leaving mask range"); ((MonoBehaviour)this).StopCoroutine(value); } _NearbyBodies.Remove(((Component)colliderRagdoll).gameObject); } else { Plugin.TheLogger.LogWarning((object)"Body leaving mask range was not in dicitonary of bodies!"); } } private RagdollGrabbableObject GetColliderRagdoll(Collider other) { RagdollGrabbableObject component = ((Component)other).gameObject.GetComponent<RagdollGrabbableObject>(); Plugin.TheLogger.LogInfo((object)$"Collided with {((Component)other).gameObject}"); if ((Object)(object)component != (Object)null && component.bodyID.Value >= 0) { Plugin.TheLogger.LogInfo((object)"Found ragdoll, lucky!"); return component; } if (!((Object)other).name.Contains(".L") && !((Object)other).name.Contains(".R")) { Plugin.TheLogger.LogInfo((object)"This is not a bone!"); return null; } Plugin.TheLogger.LogInfo((object)"Collided with a bone of a character, finding ragdoll on parents"); return ((Component)other).gameObject.GetComponentInParent<RagdollGrabbableObject>(); } private IEnumerator RepossessionCoroutine(object o) { yield return (object)new WaitForSeconds((float)(Plugin.TheConfiguration.RetryPossesionTime / 1000)); yield return (object)new WaitForEndOfFrame(); RagdollGrabbableObject val = (RagdollGrabbableObject)((o is RagdollGrabbableObject) ? o : null); if ((Object)(object)val != (Object)null && _NearbyBodies.TryGetValue(((Component)val).gameObject, out var _)) { Plugin.TheLogger.LogInfo((object)"Ragdoll timer elapsed, attempting possession!"); _NearbyBodies[((Component)val).gameObject] = null; AttemptPossesion(val); } else { Plugin.TheLogger.LogWarning((object)"Ragdoll was deleted, stopping repossession retry!"); } } private void CleanupCoroutines() { if (_NearbyBodies.Count == 0) { return; } Plugin.TheLogger.LogInfo((object)"Cleaning up all nearby bodies!"); foreach (KeyValuePair<GameObject, Coroutine> nearbyBody in _NearbyBodies) { if (nearbyBody.Value != null) { ((MonoBehaviour)this).StopCoroutine(nearbyBody.Value); } } _NearbyBodies.Clear(); } private void AttemptPossesion(RagdollGrabbableObject ragdoll) { if (!PossessionChancePassed) { Plugin.TheLogger.LogInfo((object)"Chance failed, will not possess body"); if (CanRetryPossession) { Plugin.TheLogger.LogInfo((object)"Starting coroutine for repossession"); if (_NearbyBodies[((Component)ragdoll).gameObject] != null) { ((MonoBehaviour)this).StopCoroutine(_NearbyBodies[((Component)ragdoll).gameObject]); } Coroutine value = ((MonoBehaviour)this).StartCoroutine("RepossessionCoroutine", (object)ragdoll); _NearbyBodies[((Component)ragdoll).gameObject] = value; } } else { Plugin.TheLogger.LogInfo((object)"Chance for possession OK"); BeginPossession(ragdoll); } } private void BeginPossession(RagdollGrabbableObject ragdoll) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) Plugin.TheLogger.LogInfo((object)"!!POSSESSING DEAD BODY!!"); HauntedMaskItem component = ((Component)this).gameObject.GetComponent<HauntedMaskItem>(); if ((Object)(object)component == (Object)null) { Plugin.TheLogger.LogFatal((object)"Could not find mask item component, aborting possession!"); return; } Plugin.TheLogger.LogInfo((object)"Spawning mimic"); if ((Object)(object)ragdoll.ragdoll.playerScript == (Object)null) { Plugin.TheLogger.LogFatal((object)"Ragdoll's player script is null, aborting mimic spawn!"); return; } ((NetworkBehaviour)component).NetworkObject.RemoveOwnership(); ((NetworkBehaviour)ragdoll).NetworkObject.RemoveOwnership(); SetPreviouslyHeldByOf(component, ragdoll.ragdoll.playerScript); component.CreateMimicServerRpc(((GrabbableObject)ragdoll).isInFactory, ((Component)ragdoll.ragdoll).transform.position); if ((Object)(object)component != (Object)null) { ((NetworkBehaviour)component).NetworkObject.Despawn(true); Object.Destroy((Object)(object)component); if ((Object)(object)((GrabbableObject)component).radarIcon != (Object)null && (Object)(object)((Component)((GrabbableObject)component).radarIcon).gameObject != (Object)null) { Object.Destroy((Object)(object)((Component)((GrabbableObject)component).radarIcon).gameObject); } } if ((Object)(object)ragdoll != (Object)null) { ((NetworkBehaviour)ragdoll).NetworkObject.Despawn(true); Object.Destroy((Object)(object)ragdoll); } } private void SetPreviouslyHeldByOf(HauntedMaskItem item, PlayerControllerB c) { ((object)item).GetType().GetField("previousPlayerHeldBy", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(item, c); Plugin.TheLogger.LogInfo((object)"Set private field previousPlayerHeldBy"); } private bool HasFinishedAttaching(HauntedMaskItem item) { return (bool)((object)item).GetType().GetField("finishedAttaching", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(item); } private bool ShouldDispose() { if (HasFinishedAttaching(_MaskComponent)) { Plugin.TheLogger.LogInfo((object)">> MASK HAS ATTACHED ITSELF TO SOMEONE <<"); Plugin.TheLogger.LogInfo((object)">> KILLING MASKTHEDEAD COMPONENT <<"); return true; } if ((Object)(object)_MaskComponent == (Object)null || (Object)(object)_Collider == (Object)null) { Plugin.TheLogger.LogWarning((object)">> MASK OR COLLIDER IS NULL <<"); Plugin.TheLogger.LogInfo((object)">> KILLING MASKTHEDEAD COMPONENT <<"); return true; } return false; } private void Dispose() { Plugin.TheLogger.LogInfo((object)">> DISPOSING <<"); Object.Destroy((Object)(object)this); } } }
plugins/MaxwellScrap.dll
Decompiled a year 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/Mimics.dll
Decompiled a year agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using DunGen; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyMimics.Properties; using Unity.Netcode; using UnityEngine; using UnityEngine.Events; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("Mimics")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("A mod that adds mimics to Lethal Company")] [assembly: AssemblyFileVersion("2.2.1.0")] [assembly: AssemblyInformationalVersion("2.2.1")] [assembly: AssemblyProduct("Mimics")] [assembly: AssemblyTitle("Mimics")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.2.1.0")] [module: UnverifiableCode] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>(); } } namespace LethalCompanyMimics.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { ResourceManager resourceManager = new ResourceManager("LethalCompanyMimics.Properties.Resources", typeof(Resources).Assembly); resourceMan = resourceManager; } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] mimicdoor { get { object @object = ResourceManager.GetObject("mimicdoor", resourceCulture); return (byte[])@object; } } internal Resources() { } } } namespace Mimics { [BepInPlugin("x753.Mimics", "Mimics", "2.2.1")] public class Mimics : BaseUnityPlugin { [HarmonyPatch(typeof(GameNetworkManager))] internal class GameNetworkManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch() { ((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(MimicNetworkerPrefab); } } [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch(ref StartOfRound __instance) { if (((NetworkBehaviour)__instance).IsServer && (Object)(object)MimicNetworker.Instance == (Object)null) { GameObject val = Object.Instantiate<GameObject>(MimicNetworkerPrefab); val.GetComponent<NetworkObject>().Spawn(true); MimicNetworker.SpawnWeight0.Value = SpawnRates[0]; MimicNetworker.SpawnWeight1.Value = SpawnRates[1]; MimicNetworker.SpawnWeight2.Value = SpawnRates[2]; MimicNetworker.SpawnWeight3.Value = SpawnRates[3]; MimicNetworker.SpawnWeight4.Value = SpawnRates[4]; MimicNetworker.SpawnWeightMax.Value = SpawnRates[5]; MimicNetworker.SpawnRateDynamic.Value = DynamicSpawnRate; } } } [HarmonyPatch(typeof(RoundManager))] internal class RoundManagerPatch { [HarmonyPatch("SetExitIDs")] [HarmonyPostfix] private static void SetExitIDsPatch(ref RoundManager __instance, Vector3 mainEntrancePosition) { //IL_0528: Unknown result type (might be due to invalid IL or missing references) //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_053e: Unknown result type (might be due to invalid IL or missing references) //IL_0543: Unknown result type (might be due to invalid IL or missing references) //IL_0548: 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_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0288: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0299: 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_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_055c: Unknown result type (might be due to invalid IL or missing references) //IL_055e: Unknown result type (might be due to invalid IL or missing references) //IL_0560: Unknown result type (might be due to invalid IL or missing references) //IL_0595: Unknown result type (might be due to invalid IL or missing references) //IL_05d6: 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_0675: Unknown result type (might be due to invalid IL or missing references) //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_068a: Unknown result type (might be due to invalid IL or missing references) //IL_068e: Unknown result type (might be due to invalid IL or missing references) //IL_0693: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_034a: Unknown result type (might be due to invalid IL or missing references) //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0363: Unknown result type (might be due to invalid IL or missing references) //IL_0369: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Unknown result type (might be due to invalid IL or missing references) //IL_037a: Unknown result type (might be due to invalid IL or missing references) //IL_0384: Unknown result type (might be due to invalid IL or missing references) //IL_0406: Unknown result type (might be due to invalid IL or missing references) //IL_040e: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Unknown result type (might be due to invalid IL or missing references) //IL_0421: Unknown result type (might be due to invalid IL or missing references) //IL_0783: Unknown result type (might be due to invalid IL or missing references) //IL_078d: Expected O, but got Unknown //IL_085c: Unknown result type (might be due to invalid IL or missing references) //IL_0883: Unknown result type (might be due to invalid IL or missing references) //IL_07fd: Unknown result type (might be due to invalid IL or missing references) //IL_0824: Unknown result type (might be due to invalid IL or missing references) //IL_0937: Unknown result type (might be due to invalid IL or missing references) //IL_095e: Unknown result type (might be due to invalid IL or missing references) MimicDoor.allMimics = new List<MimicDoor>(); int num = 0; Dungeon currentDungeon = __instance.dungeonGenerator.Generator.CurrentDungeon; if (!((Object)currentDungeon.DungeonFlow).name.StartsWith("Level1") && !((Object)currentDungeon.DungeonFlow).name.StartsWith("Level2")) { return; } int num2 = 0; int[] array = new int[6] { MimicNetworker.SpawnWeight0.Value, MimicNetworker.SpawnWeight1.Value, MimicNetworker.SpawnWeight2.Value, MimicNetworker.SpawnWeight3.Value, MimicNetworker.SpawnWeight4.Value, MimicNetworker.SpawnWeightMax.Value }; int num3 = 0; int[] array2 = array; foreach (int num4 in array2) { num3 += num4; } Random random = new Random(StartOfRound.Instance.randomMapSeed + 753); int num5 = random.Next(0, num3); int num6 = 0; for (int j = 0; j < array.Length; j++) { if (num5 < array[j] + num6) { num2 = j; break; } num6 += array[j]; } if (num2 == 5) { num2 = 999; } EntranceTeleport[] array3 = Object.FindObjectsOfType<EntranceTeleport>(false); int num7 = (array3.Length - 2) / 2; if (MimicNetworker.SpawnRateDynamic.Value && num2 < num7 && num7 > 1) { num2 += random.Next(0, 2); } if (MimicNetworker.SpawnRateDynamic.Value && currentDungeon.AllTiles.Count > 100) { num2 += random.Next(0, 2); } List<Doorway> list = new List<Doorway>(); Bounds val2 = default(Bounds); foreach (Tile allTile in currentDungeon.AllTiles) { foreach (Doorway unusedDoorway in allTile.UnusedDoorways) { if (unusedDoorway.HasDoorPrefabInstance || (Object)(object)((Component)unusedDoorway).GetComponentInChildren<SpawnSyncedObject>(true) == (Object)null) { continue; } GameObject gameObject = ((Component)((Component)((Component)unusedDoorway).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject; if (!((Object)gameObject).name.StartsWith("AlleyExitDoorContainer") || gameObject.activeSelf) { continue; } bool flag = false; Matrix4x4 val = Matrix4x4.TRS(((Component)unusedDoorway).transform.position, ((Component)unusedDoorway).transform.rotation, new Vector3(1f, 1f, 1f)); ((Bounds)(ref val2))..ctor(new Vector3(0f, 1.5f, 5.5f), new Vector3(2f, 6f, 8f)); ((Bounds)(ref val2)).center = ((Matrix4x4)(ref val)).MultiplyPoint3x4(((Bounds)(ref val2)).center); Collider[] array4 = Physics.OverlapBox(((Bounds)(ref val2)).center, ((Bounds)(ref val2)).extents, ((Component)unusedDoorway).transform.rotation, LayerMask.GetMask(new string[3] { "Room", "Railing", "MapHazards" })); Collider[] array5 = array4; int num8 = 0; if (num8 < array5.Length) { Collider val3 = array5[num8]; flag = true; } if (flag) { continue; } foreach (Tile allTile2 in currentDungeon.AllTiles) { if (!((Object)(object)allTile == (Object)(object)allTile2)) { Vector3 origin = ((Component)unusedDoorway).transform.position + 5f * ((Component)unusedDoorway).transform.forward; Bounds val4 = UnityUtil.CalculateProxyBounds(((Component)allTile2).gameObject, true, Vector3.up); Ray val5 = default(Ray); ((Ray)(ref val5)).origin = origin; ((Ray)(ref val5)).direction = Vector3.up; if (((Bounds)(ref val4)).IntersectRay(val5) && (((Object)allTile2).name.Contains("Catwalk") || ((Object)allTile2).name.Contains("LargeForkTile") || ((Object)allTile2).name.Contains("4x4BigStair") || ((Object)allTile2).name.Contains("ElevatorConnector") || (((Object)allTile2).name.Contains("StartRoom") && !((Object)allTile2).name.Contains("Manor")))) { flag = true; } val5 = default(Ray); ((Ray)(ref val5)).origin = origin; ((Ray)(ref val5)).direction = Vector3.down; if (((Bounds)(ref val4)).IntersectRay(val5) && (((Object)allTile2).name.Contains("MediumRoomHallway1B") || ((Object)allTile2).name.Contains("LargeForkTile") || ((Object)allTile2).name.Contains("4x4BigStair") || ((Object)allTile2).name.Contains("ElevatorConnector") || ((Object)allTile2).name.Contains("StartRoom"))) { flag = true; } } } if (!flag) { list.Add(unusedDoorway); } } } Shuffle(list, StartOfRound.Instance.randomMapSeed); List<Vector3> list2 = new List<Vector3>(); foreach (Doorway item in list) { if (num >= num2) { break; } bool flag2 = false; Vector3 val6 = ((Component)item).transform.position + 5f * ((Component)item).transform.forward; foreach (Vector3 item2 in list2) { if (Vector3.Distance(val6, item2) < 4f) { flag2 = true; break; } } if (flag2) { continue; } list2.Add(val6); GameObject gameObject2 = ((Component)((Component)((Component)item).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject; GameObject val7 = Object.Instantiate<GameObject>(MimicPrefab, ((Component)item).transform); val7.transform.position = gameObject2.transform.position; MimicDoor component = val7.GetComponent<MimicDoor>(); AudioSource[] componentsInChildren = val7.GetComponentsInChildren<AudioSource>(true); foreach (AudioSource val8 in componentsInChildren) { val8.volume = MimicVolume / 100f; val8.outputAudioMixerGroup = StartOfRound.Instance.ship3DAudio.outputAudioMixerGroup; } MimicDoor.allMimics.Add(component); component.mimicIndex = num; num++; GameObject gameObject3 = ((Component)((Component)item).transform.GetChild(0)).gameObject; gameObject3.SetActive(false); Bounds bounds = ((Collider)component.frameBox).bounds; Vector3 center = ((Bounds)(ref bounds)).center; bounds = ((Collider)component.frameBox).bounds; Collider[] array6 = Physics.OverlapBox(center, ((Bounds)(ref bounds)).extents, Quaternion.identity); foreach (Collider val9 in array6) { if (((Object)((Component)val9).gameObject).name.Contains("Shelf")) { ((Component)val9).gameObject.SetActive(false); } } Light componentInChildren = gameObject2.GetComponentInChildren<Light>(true); ((Component)componentInChildren).transform.parent.SetParent(val7.transform); MeshRenderer[] componentsInChildren2 = val7.GetComponentsInChildren<MeshRenderer>(); MeshRenderer[] array7 = componentsInChildren2; foreach (MeshRenderer val10 in array7) { Material[] materials = ((Renderer)val10).materials; foreach (Material val11 in materials) { val11.shader = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.shader; val11.renderQueue = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.renderQueue; } } component.interactTrigger.onInteract = new InteractEvent(); ((UnityEvent<PlayerControllerB>)(object)component.interactTrigger.onInteract).AddListener((UnityAction<PlayerControllerB>)component.TouchMimic); if (MimicPerfection) { continue; } component.interactTrigger.timeToHold = 0.9f; if (!ColorBlindMode) { if ((StartOfRound.Instance.randomMapSeed + num) % 2 == 0) { ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.490566f, 0.1226415f, 0.1302275f); ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.4339623f, 0.1043965f, 0.1150277f); componentInChildren.colorTemperature = 1250f; } else { ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.5f, 0.1580188f, 0.1657038f); ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(43f / 106f, 0.1358579f, 0.1393619f); componentInChildren.colorTemperature = 1300f; } } else if ((StartOfRound.Instance.randomMapSeed + num) % 2 == 0) { component.interactTrigger.timeToHold = 1.1f; } else { component.interactTrigger.timeToHold = 1f; } if (!EasyMode) { continue; } Random random2 = new Random(StartOfRound.Instance.randomMapSeed + num); switch (random2.Next(0, 4)) { case 0: if (!ColorBlindMode) { ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f); ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f); } else { component.interactTrigger.timeToHold = 1.5f; } break; case 1: component.interactTrigger.hoverTip = "Feed : [LMB]"; component.interactTrigger.holdTip = "Feed : [LMB]"; break; case 2: component.interactTrigger.hoverIcon = component.LostFingersIcon; break; case 3: component.interactTrigger.holdTip = "DIE : [LMB]"; component.interactTrigger.timeToHold = 0.5f; break; default: component.interactTrigger.hoverTip = "BUG, REPORT TO DEVELOPER"; break; } } } } [HarmonyPatch(typeof(SprayPaintItem))] internal class SprayPaintItemPatch { private static FieldInfo SprayHit = typeof(SprayPaintItem).GetField("sprayHit", BindingFlags.Instance | BindingFlags.NonPublic); [HarmonyPatch("SprayPaintClientRpc")] [HarmonyPostfix] private static void SprayPaintClientRpcPatch(SprayPaintItem __instance, Vector3 sprayPos, Vector3 sprayRot) { //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) RaycastHit val = (RaycastHit)SprayHit.GetValue(__instance); if ((Object)(object)((RaycastHit)(ref val)).collider != (Object)null && ((Object)((RaycastHit)(ref val)).collider).name == "MimicSprayCollider") { MimicDoor component = ((Component)((Component)((RaycastHit)(ref val)).collider).transform.parent.parent).GetComponent<MimicDoor>(); component.sprayCount++; if (component.sprayCount > 9) { MimicNetworker.Instance.MimicAddAnger(1, component.mimicIndex); } } } } private const string modGUID = "x753.Mimics"; private const string modName = "Mimics"; private const string modVersion = "2.2.1"; private readonly Harmony harmony = new Harmony("x753.Mimics"); private static Mimics Instance; public static GameObject MimicPrefab; public static GameObject MimicNetworkerPrefab; public static int[] SpawnRates; public static bool MimicPerfection; public static bool EasyMode; public static bool ColorBlindMode; public static float MimicVolume; public static bool DynamicSpawnRate; private void Awake() { AssetBundle val = AssetBundle.LoadFromMemory(Resources.mimicdoor); MimicPrefab = val.LoadAsset<GameObject>("Assets/MimicDoor.prefab"); MimicNetworkerPrefab = val.LoadAsset<GameObject>("Assets/MimicNetworker.prefab"); if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Mimics is loaded!"); SpawnRates = new int[6] { ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Zero Mimics", 23, "Weight of zero mimics spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "One Mimic", 69, "Weight of one mimic spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Two Mimics", 7, "Weight of two mimics spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Three Mimics", 1, "Weight of three mimics spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Four Mimics", 0, "Weight of four mimics spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Maximum Mimics", 0, "Weight of maximum mimics spawning").Value }; DynamicSpawnRate = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawn Rate", "Dynamic Spawn Rate", true, "Increases mimic spawn rate based on dungeon size and the number of instances of the real thing.").Value; MimicPerfection = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Perfect Mimics", false, "Select this if you want mimics to be the exact same color as the real thing. Overrides all difficulty settings.").Value; EasyMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Easy Mode", false, "Each mimic will have one of several possible imperfections to help you tell if it's a mimic.").Value; ColorBlindMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Color Blind Mode", false, "Replaces all color differences with another way to differentiate mimics.").Value; MimicVolume = ((BaseUnityPlugin)this).Config.Bind<int>("General", "SFX Volume", 100, "Volume of the mimic's SFX (0-100)").Value; if (MimicVolume < 0f) { MimicVolume = 0f; } if (MimicVolume > 100f) { MimicVolume = 100f; } ((BaseUnityPlugin)this).Config.Bind<int>("Difficulty", "Difficulty Level", 0, "This is an old setting, ignore it."); ((BaseUnityPlugin)this).Config.Remove(((BaseUnityPlugin)this).Config["Difficulty", "Difficulty Level"].Definition); ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Five Mimics", 0, "This is an old setting, ignore it."); ((BaseUnityPlugin)this).Config.Remove(((BaseUnityPlugin)this).Config["Spawn Rate", "Five Mimics"].Definition); ((BaseUnityPlugin)this).Config.Save(); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array = types; foreach (Type type in array) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array2 = methods; foreach (MethodInfo methodInfo in array2) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } } public static void Shuffle<T>(IList<T> list, int seed) { Random random = new Random(seed); int num = list.Count; while (num > 1) { num--; int index = random.Next(num + 1); T value = list[index]; list[index] = list[num]; list[num] = value; } } } public class MimicNetworker : NetworkBehaviour { public static MimicNetworker Instance; public static NetworkVariable<int> SpawnWeight0 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeight1 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeight2 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeight3 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeight4 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeightMax = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<bool> SpawnRateDynamic = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private void Awake() { Instance = this; } public void MimicAttack(int playerId, int mimicIndex, bool ownerOnly = false) { if (((NetworkBehaviour)this).IsOwner) { Instance.MimicAttackClientRpc(playerId, mimicIndex); } else if (!ownerOnly) { Instance.MimicAttackServerRpc(playerId, mimicIndex); } } [ClientRpc] public void MimicAttackClientRpc(int playerId, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_007e: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2885019175u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2885019175u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { ((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].Attack(playerId)); } } } [ServerRpc(RequireOwnership = false)] public void MimicAttackServerRpc(int playerId, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_007e: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1024971481u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1024971481u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Instance.MimicAttackClientRpc(playerId, mimicIndex); } } } public void MimicAddAnger(int amount, int mimicIndex) { if (((NetworkBehaviour)this).IsOwner) { Instance.MimicAddAngerClientRpc(amount, mimicIndex); } else { Instance.MimicAddAngerServerRpc(amount, mimicIndex); } } [ClientRpc] public void MimicAddAngerClientRpc(int amount, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_007e: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1137632670u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, amount); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1137632670u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { ((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].AddAnger(amount)); } } } [ServerRpc(RequireOwnership = false)] public void MimicAddAngerServerRpc(int amount, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_007e: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(669208889u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, amount); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 669208889u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Instance.MimicAddAngerClientRpc(amount, mimicIndex); } } } protected override void __initializeVariables() { if (SpawnWeight0 == null) { throw new Exception("MimicNetworker.SpawnWeight0 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight0).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight0, "SpawnWeight0"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight0); if (SpawnWeight1 == null) { throw new Exception("MimicNetworker.SpawnWeight1 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight1).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight1, "SpawnWeight1"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight1); if (SpawnWeight2 == null) { throw new Exception("MimicNetworker.SpawnWeight2 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight2).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight2, "SpawnWeight2"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight2); if (SpawnWeight3 == null) { throw new Exception("MimicNetworker.SpawnWeight3 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight3).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight3, "SpawnWeight3"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight3); if (SpawnWeight4 == null) { throw new Exception("MimicNetworker.SpawnWeight4 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight4).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight4, "SpawnWeight4"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight4); if (SpawnWeightMax == null) { throw new Exception("MimicNetworker.SpawnWeightMax cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeightMax).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeightMax, "SpawnWeightMax"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeightMax); if (SpawnRateDynamic == null) { throw new Exception("MimicNetworker.SpawnRateDynamic cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnRateDynamic).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnRateDynamic, "SpawnRateDynamic"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnRateDynamic); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_MimicNetworker() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(2885019175u, new RpcReceiveHandler(__rpc_handler_2885019175)); NetworkManager.__rpc_func_table.Add(1024971481u, new RpcReceiveHandler(__rpc_handler_1024971481)); NetworkManager.__rpc_func_table.Add(1137632670u, new RpcReceiveHandler(__rpc_handler_1137632670)); NetworkManager.__rpc_func_table.Add(669208889u, new RpcReceiveHandler(__rpc_handler_669208889)); } private static void __rpc_handler_2885019175(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int playerId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)2; ((MimicNetworker)(object)target).MimicAttackClientRpc(playerId, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1024971481(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int playerId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)1; ((MimicNetworker)(object)target).MimicAttackServerRpc(playerId, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1137632670(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int amount = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref amount); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)2; ((MimicNetworker)(object)target).MimicAddAngerClientRpc(amount, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_669208889(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int amount = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref amount); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)1; ((MimicNetworker)(object)target).MimicAddAngerServerRpc(amount, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "MimicNetworker"; } } public class MimicDoor : MonoBehaviour { public GameObject playerTarget; public BoxCollider frameBox; public Sprite LostFingersIcon; public Animator mimicAnimator; public GameObject grabPoint; public InteractTrigger interactTrigger; public int anger; public bool angering; public int sprayCount; private bool attacking; public static List<MimicDoor> allMimics; public int mimicIndex; public void TouchMimic(PlayerControllerB player) { if (!attacking) { MimicNetworker.Instance.MimicAttack((int)player.playerClientId, mimicIndex); } } public IEnumerator Attack(int playerId) { attacking = true; interactTrigger.interactable = false; PlayerControllerB player = StartOfRound.Instance.allPlayerScripts[playerId]; mimicAnimator.SetTrigger("Attack"); playerTarget.transform.position = ((Component)player).transform.position; yield return (object)new WaitForSeconds(0.1f); playerTarget.transform.position = ((Component)player).transform.position; yield return (object)new WaitForSeconds(0.1f); playerTarget.transform.position = ((Component)player).transform.position; yield return (object)new WaitForSeconds(0.1f); playerTarget.transform.position = ((Component)player).transform.position; yield return (object)new WaitForSeconds(0.1f); float num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)frameBox).transform.position); if (num < 8f) { HUDManager.Instance.ShakeCamera((ScreenShakeType)1); } else if (num < 14f) { HUDManager.Instance.ShakeCamera((ScreenShakeType)0); } yield return (object)new WaitForSeconds(0.2f); if (((NetworkBehaviour)player).IsOwner && Vector3.Distance(((Component)player).transform.position, ((Component)this).transform.position) < 8.75f) { player.KillPlayer(Vector3.zero, true, (CauseOfDeath)0, 0); } float startTime = Time.timeSinceLevelLoad; yield return (object)new WaitUntil((Func<bool>)(() => (Object)(object)player.deadBody != (Object)null || Time.timeSinceLevelLoad - startTime > 4f)); if ((Object)(object)player.deadBody != (Object)null) { player.deadBody.attachedTo = grabPoint.transform; player.deadBody.attachedLimb = player.deadBody.bodyParts[5]; player.deadBody.matchPositionExactly = true; for (int i = 0; i < player.deadBody.bodyParts.Length; i++) { ((Component)player.deadBody.bodyParts[i]).GetComponent<Collider>().excludeLayers = LayerMask.op_Implicit(-1); } } yield return (object)new WaitForSeconds(2f); if ((Object)(object)player.deadBody != (Object)null) { player.deadBody.attachedTo = null; player.deadBody.attachedLimb = null; player.deadBody.matchPositionExactly = false; ((Component)((Component)player.deadBody).transform.GetChild(0)).gameObject.SetActive(false); player.deadBody = null; } yield return (object)new WaitForSeconds(4.5f); attacking = false; interactTrigger.interactable = true; } public IEnumerator AddAnger(int amount) { if (angering || attacking) { yield break; } angering = true; anger += amount; if (anger == 1) { Sprite oldIcon2 = interactTrigger.hoverIcon; interactTrigger.hoverIcon = LostFingersIcon; mimicAnimator.SetTrigger("Growl"); yield return (object)new WaitForSeconds(2.75f); interactTrigger.hoverIcon = oldIcon2; sprayCount = 0; angering = false; yield break; } if (anger == 2) { interactTrigger.holdTip = "DIE : [LMB]"; interactTrigger.timeToHold = 0.25f; Sprite oldIcon2 = interactTrigger.hoverIcon; interactTrigger.hoverIcon = LostFingersIcon; mimicAnimator.SetTrigger("Growl"); yield return (object)new WaitForSeconds(2.75f); interactTrigger.hoverIcon = oldIcon2; sprayCount = 0; angering = false; yield break; } if (anger > 2) { PlayerControllerB val = null; float num = 9999f; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts) { float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val2).transform.position); if (num2 < num) { num = num2; val = val2; } } if ((Object)(object)val != (Object)null) { MimicNetworker.Instance.MimicAttackClientRpc((int)val.playerClientId, mimicIndex); } } sprayCount = 0; angering = false; } } public class MimicCollider : MonoBehaviour, IHittable { public MimicDoor mimic; void IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit = null, bool playHitSFX = false) { MimicNetworker.Instance.MimicAddAnger(force, mimic.mimicIndex); } } public class MimicListener : MonoBehaviour, INoiseListener { public MimicDoor mimic; private int tolerance = 100; void INoiseListener.DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID) { //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) if ((noiseLoudness >= 0.9f || noiseID == 101158) && Vector3.Distance(noisePosition, ((Component)mimic).transform.position) < 5f) { switch (noiseID) { case 75: tolerance--; break; case 5: tolerance -= 15; break; case 101158: tolerance -= 35; break; default: tolerance -= 30; break; } if (tolerance <= 0) { tolerance = 100; MimicNetworker.Instance.MimicAddAnger(1, mimic.mimicIndex); } } } } }
plugins/MolesterLootBug.dll
Decompiled a year agousing System; 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.Logging; using GameNetcodeStuff; 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("MolesterLootBug")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("A Mod for Lethal Company")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyProduct("MolesterLootBug")] [assembly: AssemblyTitle("MolesterLootBug")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LethalCompanyTemplate { public static class PluginInfo { public const string PLUGIN_GUID = "MolesterLootBug"; public const string PLUGIN_NAME = "MolesterLootBug"; public const string PLUGIN_VERSION = "1.0.1"; } } namespace MolesterLootBug { [BepInPlugin("EvilLootBugByOwen.1.10", "Molester Loot Bug", "0.2")] public class Plugin : BaseUnityPlugin { public class BeingHeldData : MonoBehaviour { public bool isHeld = false; public HoarderBugAI HoarderInstance = null; public PlayerControllerB player = null; public float holdTimeRemaining = bugHoldTime; } public class HoldingData : MonoBehaviour { public bool isHoldingPlayer = false; public PlayerControllerB HeldPlayer = null; public float CanHoldTime = bugHoldTime; } private const string PLUGIN_GUID = "EvilLootBugByOwen.1.10"; private const string PLUGIN_NAME = "Molester Loot Bug"; private const string PLUGIN_VERSION = "0.2"; private readonly Harmony harmony = new Harmony("EvilLootBugByOwen.1.10"); private static Plugin Instance; internal static ManualLogSource mls; internal static Random random = new Random(); private static float bugHoldTime = 8f; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("EvilLootBugByOwen.1.10"); mls.LogInfo((object)"Mod Awake OWEN GOATED"); harmony.PatchAll(typeof(Plugin)); } [HarmonyPatch(typeof(PlayerControllerB), "Awake")] [HarmonyPostfix] private static void AwakeUpdate(PlayerControllerB __instance) { mls.LogInfo((object)"Attempting to Load instance Data, Player Awake Patch"); ((Component)__instance).gameObject.AddComponent<BeingHeldData>(); BeingHeldData component = ((Component)__instance).gameObject.GetComponent<BeingHeldData>(); component.player = __instance; mls.LogInfo((object)$"Is Being Held ON AWAKE? {component.isHeld}"); } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] private static void PlayerUpdate(PlayerControllerB __instance, ref Vector3 ___serverPlayerPosition, ref bool ___snapToServerPosition) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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_003f: 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_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0084: 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) BeingHeldData component = ((Component)__instance).gameObject.GetComponent<BeingHeldData>(); if (!component.isHeld) { return; } Vector3 serverPosition = ((EnemyAI)component.HoarderInstance).serverPosition; Vector3 position = ((Component)__instance).gameObject.transform.position; Vector3 val = serverPosition - position; __instance.thisController.SimpleMove(val * 6f); mls.LogInfo((object)$"PlayerServer Pos at {__instance.serverPlayerPosition}"); mls.LogInfo((object)$"Local Pos at {__instance.serverPlayerPosition}"); mls.LogInfo((object)$"Loot Pos at {((EnemyAI)component.HoarderInstance).serverPosition}"); mls.LogInfo((object)$"Bug Holding Player. Time left: {component.holdTimeRemaining}"); component.holdTimeRemaining -= Time.deltaTime; mls.LogInfo((object)$"Is Being Held? {component.isHeld}"); if (component.holdTimeRemaining <= 0f || __instance.isPlayerDead || ((EnemyAI)component.HoarderInstance).isEnemyDead) { component.isHeld = false; component.holdTimeRemaining = bugHoldTime; ((Component)component.HoarderInstance).gameObject.GetComponent<HoldingData>().CanHoldTime = bugHoldTime; HoldingData component2 = ((Component)component.HoarderInstance).gameObject.GetComponent<HoldingData>(); if ((Object)(object)component2 != (Object)null) { component2.isHoldingPlayer = false; } } } [HarmonyPatch(typeof(HoarderBugAI), "Start")] [HarmonyPostfix] private static void BugStart(HoarderBugAI __instance) { ((Component)__instance).gameObject.AddComponent<HoldingData>(); } [HarmonyPatch(typeof(HoarderBugAI), "OnCollideWithPlayer")] [HarmonyPostfix] private static void BugOnCollide(HoarderBugAI __instance, Collider other) { HoldingData component = ((Component)__instance).gameObject.GetComponent<HoldingData>(); if (!component.isHoldingPlayer && random.Next(0, 2) == 0 && !((EnemyAI)__instance).isEnemyDead && component.CanHoldTime <= 0f) { PlayerControllerB component2 = ((Component)other).GetComponent<PlayerControllerB>(); if ((Object)(object)component2 != (Object)null) { ((Component)component2).gameObject.GetComponent<BeingHeldData>().isHeld = true; ((Component)component2).gameObject.GetComponent<BeingHeldData>().HoarderInstance = __instance; ((Component)__instance).gameObject.GetComponent<HoldingData>().isHoldingPlayer = true; ((Component)__instance).gameObject.GetComponent<HoldingData>().HeldPlayer = component2; } } } [HarmonyPatch(typeof(HoarderBugAI), "Update")] [HarmonyPostfix] private static void BugUpdate(HoarderBugAI __instance) { HoldingData component = ((Component)__instance).gameObject.GetComponent<HoldingData>(); if (component.isHoldingPlayer) { mls.LogInfo((object)"Bug Holding Player."); __instance.angryTimer -= 2f * Time.deltaTime; __instance.angryAtPlayer = null; __instance.timeSinceHittingPlayer = -5f; if (((EnemyAI)__instance).isEnemyDead) { component.isHoldingPlayer = false; BeingHeldData component2 = ((Component)component.HeldPlayer).gameObject.GetComponent<BeingHeldData>(); component2.isHeld = false; } } else { component.CanHoldTime -= Time.deltaTime; } } } } namespace MolesterLootBug.Patches { [HarmonyPatch(typeof(HoarderBugAI))] internal class LootBugPatch { } internal class PlayerControllerBPatch { } }
plugins/MonstersPlus2.0.0.dll
Decompiled a year agousing System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; 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 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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalCompanyTemplate")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("A template for Lethal Company")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("LethalCompanyTemplate")] [assembly: AssemblyTitle("LethalCompanyTemplate")] [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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LethalCompanyTemplate { public static class MyPluginInfo { public const string PLUGIN_GUID = "LethalCompanyTemplate"; public const string PLUGIN_NAME = "LethalCompanyTemplate"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace LethalCompanyTemplate.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { ResourceManager resourceManager = new ResourceManager("LethalCompanyTemplate.Properties.Resources", typeof(Resources).Assembly); resourceMan = resourceManager; } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal Resources() { } } } namespace Zero { public static class PluginInfo { public const string PLUGIN_GUID = "Zero.MonstersPlus"; public const string PLUGIN_NAME = "MonstersPlus"; public const string PLUGIN_VERSION = "2.0.0"; } [BepInPlugin("Zero.MonstersPlus", "MonstersPlus", "2.0.0")] public class Plugin : BaseUnityPlugin { private static ConfigEntry<int> BaseSpawnChance; private static int baseSpawnChance; private static int spawnChance; private static ConfigEntry<int> EnemyMax; private static ConfigEntry<int> StartSpawnTime; private static ConfigEntry<int> MinSpawnInterval; private static ConfigEntry<int> MaxSpawnInterval; private static int minSpawnInterval; private static int maxSpawnInterval; private static int startSpawnTime; private static int enemyMax; private static int enemyCount; private static int spawnInterval; private static float spawnTime; private static int lootbug; private static int lizard; private static int flea; private static int spider; private static int slime; private static int thumper; private static int coil; private static int girl; private static int bracken; private static int jester; public static ManualLogSource log; private Harmony harmony = new Harmony("Zero.MonstersPlus"); internal static bool isHost; private static RoundManager roundManager; private void Awake() { log = Logger.CreateLogSource("Zero.MonstersPlus"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"[Z] Plugin: Zero.MonstersPlus"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"[Z] Name: MonstersPlus"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"[Z] Version: 2.0.0"); harmony.PatchAll(typeof(Plugin)); SetBindings(); } private void SetBindings() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown BaseSpawnChance = ((BaseUnityPlugin)this).Config.Bind<int>("Base Spawn Chance", "<1-100> Chance to Spawn", 30, new ConfigDescription("Base chance for an enemy to spawn.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); EnemyMax = ((BaseUnityPlugin)this).Config.Bind<int>("Enemy Limit", "Max <n> of enemies", 8, new ConfigDescription("Max number of enemies that can spawn", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 16), Array.Empty<object>())); StartSpawnTime = ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Delay", "Start spawning enemies after <n> seconds", 60, new ConfigDescription("Number of seconds to wait before spawning in enemies every <n> seconds interval.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(60, 360), Array.Empty<object>())); MinSpawnInterval = ((BaseUnityPlugin)this).Config.Bind<int>("Min Spawn Interval", "Spawn enemy within <min> seconds", 30, new ConfigDescription("Minimum seconds before a new enemy can spawn.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(30, 360), Array.Empty<object>())); MaxSpawnInterval = ((BaseUnityPlugin)this).Config.Bind<int>("Max Spawn Interval", "Spawn enemy within <max> seconds", 60, new ConfigDescription("Maximum seconds before a new enemy can spawn.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(30, 360), Array.Empty<object>())); baseSpawnChance = BaseSpawnChance.Value; startSpawnTime = StartSpawnTime.Value; minSpawnInterval = MinSpawnInterval.Value; maxSpawnInterval = MaxSpawnInterval.Value; enemyMax = EnemyMax.Value; } [HarmonyPatch(typeof(RoundManager), "Start")] [HarmonyPostfix] public static void StartPatch() { if (minSpawnInterval > maxSpawnInterval) { minSpawnInterval = maxSpawnInterval; } roundManager = RoundManager.Instance; isHost = ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost; } [HarmonyPatch(typeof(RoundManager), "LoadNewLevel")] [HarmonyPostfix] private static void NewLevel(ref SelectableLevel newLevel) { List<SpawnableEnemyWithRarity> enemies = newLevel.Enemies; lootbug = (lizard = (flea = (slime = (thumper = (coil = (girl = (bracken = (jester = -1)))))))); for (int i = 0; i < newLevel.Enemies.Count; i++) { if (enemies[i].enemyType.enemyName.ToLower().Contains("hoarding")) { lootbug = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("puffer")) { lizard = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("centipede")) { flea = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("spider")) { spider = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("blob")) { slime = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("crawler")) { thumper = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("coil")) { coil = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("girl")) { girl = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("flowerman")) { bracken = i; } else if (enemies[i].enemyType.enemyName.ToLower().Contains("jester")) { jester = i; } } spawnTime = roundManager.timeScript.currentDayTime + (float)startSpawnTime; spawnInterval = Random.Range(minSpawnInterval, maxSpawnInterval + 1); spawnChance = baseSpawnChance; enemyCount = 0; } [HarmonyPatch(typeof(RoundManager), "SpawnInsideEnemiesFromVentsIfReady")] [HarmonyPostfix] public static void SpawnInsideEnemiesFromVentsIfReadyPatch() { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_0393: Unknown result type (might be due to invalid IL or missing references) if (!isHost) { return; } roundManager.currentLevel.maxEnemyPowerCount = 250; if (enemyCount >= enemyMax || !(roundManager.timeScript.currentDayTime > spawnTime) || roundManager.allEnemyVents.Length == 0) { return; } int num = Random.Range(0, roundManager.allEnemyVents.Length); Vector3 position = roundManager.allEnemyVents[num].floorNode.position; float y = roundManager.allEnemyVents[num].floorNode.eulerAngles.y; int num2 = Random.Range(1, 101); int num3 = 0; int num4 = Random.Range(0, 100); int num5 = Mathf.FloorToInt(roundManager.timeScript.currentDayTime / 60f); if (num5 >= 1 && num5 <= 4) { spawnChance = baseSpawnChance + num5 * 5; } else if (num5 >= 5) { spawnChance = baseSpawnChance + 20 + (num5 - 4) * 10; } if (spawnChance > 100) { spawnChance = 100; } if (num4 >= 1 && num4 <= spawnChance) { if (num2 >= 1 && num2 <= 10) { if (lootbug != -1) { num3 = lootbug; } } else if (num2 >= 11 && num2 <= 15) { if (lizard != -1) { num3 = lizard; } } else if (num2 >= 16 && num2 <= 35) { if (flea != -1) { num3 = flea; } } else if (num2 >= 36 && num2 <= 50) { if (spider != -1) { num3 = spider; } } else if (num2 >= 51 && num2 <= 65) { if (slime != -1) { num3 = slime; } } else if (num2 >= 66 && num2 <= 80) { if (thumper != -1) { num3 = thumper; } } else if (num2 >= 81 && num2 <= 85) { if (coil != -1) { num3 = coil; } } else if (num2 >= 86 && num2 <= 90) { if (girl != -1) { num3 = girl; } } else if (num2 >= 91 && num2 <= 95) { if (bracken != -1) { num3 = bracken; } } else if (num2 >= 96 && num2 <= 100 && jester != -1) { num3 = jester; } roundManager.SpawnEnemyOnServer(position, y, num3); enemyCount++; } spawnInterval = Random.Range(minSpawnInterval, maxSpawnInterval + 1); spawnTime = roundManager.timeScript.currentDayTime + (float)spawnInterval; log.LogInfo((object)("[Z] Spawned: <" + num3 + "> : " + roundManager.currentLevel.Enemies[num3].enemyType.enemyName)); log.LogInfo((object)($"[Z] Time: {roundManager.timeScript.currentDayTime} | Spawning @ " + spawnTime)); log.LogInfo((object)("[Z] Enemy Count: " + enemyCount)); } } }
plugins/MoreSuits.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("MoreSuits")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("A mod that adds more suit options to Lethal Company")] [assembly: AssemblyFileVersion("1.4.1.0")] [assembly: AssemblyInformationalVersion("1.4.1")] [assembly: AssemblyProduct("MoreSuits")] [assembly: AssemblyTitle("MoreSuits")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.4.1.0")] [module: UnverifiableCode] namespace MoreSuits; [BepInPlugin("x753.More_Suits", "More Suits", "1.4.1")] public class MoreSuitsMod : BaseUnityPlugin { [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { [HarmonyPatch("Start")] [HarmonyPrefix] private static void StartPatch(ref StartOfRound __instance) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_067c: Unknown result type (might be due to invalid IL or missing references) //IL_0681: Unknown result type (might be due to invalid IL or missing references) //IL_0687: Unknown result type (might be due to invalid IL or missing references) //IL_068c: Unknown result type (might be due to invalid IL or missing references) //IL_03f9: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Expected O, but got Unknown //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Expected O, but got Unknown //IL_0598: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Expected O, but got Unknown try { if (SuitsAdded) { return; } int count = __instance.unlockablesList.unlockables.Count; UnlockableItem val = new UnlockableItem(); int num = 0; for (int i = 0; i < __instance.unlockablesList.unlockables.Count; i++) { UnlockableItem val2 = __instance.unlockablesList.unlockables[i]; if (!((Object)(object)val2.suitMaterial != (Object)null) || !val2.alreadyUnlocked) { continue; } val = val2; List<string> list = Directory.GetDirectories(Paths.PluginPath, "moresuits", SearchOption.AllDirectories).ToList(); List<string> list2 = new List<string>(); List<string> list3 = new List<string>(); List<string> list4 = DisabledSuits.ToLower().Replace(".png", "").Split(',') .ToList(); List<string> list5 = new List<string>(); if (!LoadAllSuits) { foreach (string item2 in list) { if (File.Exists(Path.Combine(item2, "!less-suits.txt"))) { string[] collection = new string[9] { "glow", "kirby", "knuckles", "luigi", "mario", "minion", "skeleton", "slayer", "smile" }; list5.AddRange(collection); break; } } } foreach (string item3 in list) { if (item3 != "") { string[] files = Directory.GetFiles(item3, "*.png"); string[] files2 = Directory.GetFiles(item3, "*.matbundle"); list2.AddRange(files); list3.AddRange(files2); } } list3.Sort(); list2.Sort(); try { foreach (string item4 in list3) { Object[] array = AssetBundle.LoadFromFile(item4).LoadAllAssets(); foreach (Object val3 in array) { if (val3 is Material) { Material item = (Material)val3; customMaterials.Add(item); } } } } catch (Exception ex) { Debug.Log((object)("Something went wrong with More Suits! Could not load materials from asset bundle(s). Error: " + ex)); } foreach (string item5 in list2) { if (list4.Contains(Path.GetFileNameWithoutExtension(item5).ToLower())) { continue; } string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (list5.Contains(Path.GetFileNameWithoutExtension(item5).ToLower()) && item5.Contains(directoryName)) { continue; } UnlockableItem val4; Material val5; if (Path.GetFileNameWithoutExtension(item5).ToLower() == "default") { val4 = val; val5 = val4.suitMaterial; } else { val4 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val)); val5 = Object.Instantiate<Material>(val4.suitMaterial); } byte[] array2 = File.ReadAllBytes(item5); Texture2D val6 = new Texture2D(2, 2); ImageConversion.LoadImage(val6, array2); val5.mainTexture = (Texture)(object)val6; val4.unlockableName = Path.GetFileNameWithoutExtension(item5); try { string path = Path.Combine(Path.GetDirectoryName(item5), "advanced", val4.unlockableName + ".json"); if (File.Exists(path)) { string[] array3 = File.ReadAllLines(path); for (int j = 0; j < array3.Length; j++) { string[] array4 = array3[j].Trim().Split(':'); if (array4.Length != 2) { continue; } string text = array4[0].Trim('"', ' ', ','); string text2 = array4[1].Trim('"', ' ', ','); if (text2.Contains(".png")) { byte[] array5 = File.ReadAllBytes(Path.Combine(Path.GetDirectoryName(item5), "advanced", text2)); Texture2D val7 = new Texture2D(2, 2); ImageConversion.LoadImage(val7, array5); val5.SetTexture(text, (Texture)(object)val7); continue; } if (text == "PRICE" && int.TryParse(text2, out var result)) { try { val4 = AddToRotatingShop(val4, result, __instance.unlockablesList.unlockables.Count); } catch (Exception ex2) { Debug.Log((object)("Something went wrong with More Suits! Could not add a suit to the rotating shop. Error: " + ex2)); } continue; } switch (text2) { case "KEYWORD": val5.EnableKeyword(text); continue; case "DISABLEKEYWORD": val5.DisableKeyword(text); continue; case "SHADERPASS": val5.SetShaderPassEnabled(text, true); continue; case "DISABLESHADERPASS": val5.SetShaderPassEnabled(text, false); continue; } float result2; Vector4 vector; if (text == "SHADER") { Shader shader = Shader.Find(text2); val5.shader = shader; } else if (text == "MATERIAL") { foreach (Material customMaterial in customMaterials) { if (((Object)customMaterial).name == text2) { val5 = Object.Instantiate<Material>(customMaterial); val5.mainTexture = (Texture)(object)val6; break; } } } else if (float.TryParse(text2, out result2)) { val5.SetFloat(text, result2); } else if (TryParseVector4(text2, out vector)) { val5.SetVector(text, vector); } } } } catch (Exception ex3) { Debug.Log((object)("Something went wrong with More Suits! Error: " + ex3)); } val4.suitMaterial = val5; if (val4.unlockableName.ToLower() != "default") { if (num == MaxSuits) { Debug.Log((object)"Attempted to add a suit, but you've already reached the max number of suits! Modify the config if you want more."); continue; } __instance.unlockablesList.unlockables.Add(val4); num++; } } SuitsAdded = true; break; } UnlockableItem val8 = JsonUtility.FromJson<UnlockableItem>(JsonUtility.ToJson((object)val)); val8.alreadyUnlocked = false; val8.hasBeenMoved = false; val8.placedPosition = Vector3.zero; val8.placedRotation = Vector3.zero; val8.unlockableType = 753; while (__instance.unlockablesList.unlockables.Count < count + MaxSuits) { __instance.unlockablesList.unlockables.Add(val8); } } catch (Exception ex4) { Debug.Log((object)("Something went wrong with More Suits! Error: " + ex4)); } } [HarmonyPatch("PositionSuitsOnRack")] [HarmonyPrefix] private static bool PositionSuitsOnRackPatch(ref StartOfRound __instance) { //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: 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_00b8: 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) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) List<UnlockableSuit> source = Object.FindObjectsOfType<UnlockableSuit>().ToList(); source = source.OrderBy((UnlockableSuit suit) => suit.syncedSuitID.Value).ToList(); int num = 0; foreach (UnlockableSuit item in source) { AutoParentToShip component = ((Component)item).gameObject.GetComponent<AutoParentToShip>(); component.overrideOffset = true; float num2 = 0.18f; if (MakeSuitsFitOnRack && source.Count > 13) { num2 /= (float)Math.Min(source.Count, 20) / 12f; } component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + __instance.rightmostSuitPosition.forward * num2 * (float)num; component.rotationOffset = new Vector3(0f, 90f, 0f); num++; } return false; } } private const string modGUID = "x753.More_Suits"; private const string modName = "More Suits"; private const string modVersion = "1.4.1"; private readonly Harmony harmony = new Harmony("x753.More_Suits"); private static MoreSuitsMod Instance; public static bool SuitsAdded = false; public static string DisabledSuits; public static bool LoadAllSuits; public static bool MakeSuitsFitOnRack; public static int MaxSuits; public static List<Material> customMaterials = new List<Material>(); private static TerminalNode cancelPurchase; private static TerminalKeyword buyKeyword; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } DisabledSuits = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Disabled Suit List", "UglySuit751.png,UglySuit752.png,UglySuit753.png", "Comma-separated list of suits that shouldn't be loaded").Value; LoadAllSuits = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Ignore !less-suits.txt", false, "If true, ignores the !less-suits.txt file and will attempt to load every suit, except those in the disabled list. This should be true if you're not worried about having too many suits.").Value; MakeSuitsFitOnRack = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Make Suits Fit on Rack", true, "If true, squishes the suits together so more can fit on the rack.").Value; MaxSuits = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Max Suits", 100, "The maximum number of suits to load. If you have more, some will be ignored.").Value; harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin More Suits is loaded!"); } private static UnlockableItem AddToRotatingShop(UnlockableItem newSuit, int price, int unlockableID) { //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_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Expected O, but got Unknown //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_029f: Expected O, but got Unknown Terminal val = Object.FindObjectOfType<Terminal>(); for (int i = 0; i < val.terminalNodes.allKeywords.Length; i++) { if (((Object)val.terminalNodes.allKeywords[i]).name == "Buy") { buyKeyword = val.terminalNodes.allKeywords[i]; break; } } newSuit.alreadyUnlocked = false; newSuit.hasBeenMoved = false; newSuit.placedPosition = Vector3.zero; newSuit.placedRotation = Vector3.zero; newSuit.shopSelectionNode = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)newSuit.shopSelectionNode).name = newSuit.unlockableName + "SuitBuy1"; newSuit.shopSelectionNode.creatureName = newSuit.unlockableName + " suit"; newSuit.shopSelectionNode.displayText = "You have requested to order " + newSuit.unlockableName + " suits.\nTotal cost of item: [totalCost].\n\nPlease CONFIRM or DENY.\n\n"; newSuit.shopSelectionNode.clearPreviousText = true; newSuit.shopSelectionNode.shipUnlockableID = unlockableID; newSuit.shopSelectionNode.itemCost = price; newSuit.shopSelectionNode.overrideOptions = true; CompatibleNoun val2 = new CompatibleNoun(); val2.noun = ScriptableObject.CreateInstance<TerminalKeyword>(); val2.noun.word = "confirm"; val2.noun.isVerb = true; val2.result = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val2.result).name = newSuit.unlockableName + "SuitBuyConfirm"; val2.result.creatureName = ""; val2.result.displayText = "Ordered " + newSuit.unlockableName + " suits! Your new balance is [playerCredits].\n\n"; val2.result.clearPreviousText = true; val2.result.shipUnlockableID = unlockableID; val2.result.buyUnlockable = true; val2.result.itemCost = price; val2.result.terminalEvent = ""; CompatibleNoun val3 = new CompatibleNoun(); val3.noun = ScriptableObject.CreateInstance<TerminalKeyword>(); val3.noun.word = "deny"; val3.noun.isVerb = true; if ((Object)(object)cancelPurchase == (Object)null) { cancelPurchase = ScriptableObject.CreateInstance<TerminalNode>(); } val3.result = cancelPurchase; ((Object)val3.result).name = "MoreSuitsCancelPurchase"; val3.result.displayText = "Cancelled order.\n"; newSuit.shopSelectionNode.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { val2, val3 }; TerminalKeyword val4 = ScriptableObject.CreateInstance<TerminalKeyword>(); ((Object)val4).name = newSuit.unlockableName + "Suit"; val4.word = newSuit.unlockableName.ToLower() + " suit"; val4.defaultVerb = buyKeyword; CompatibleNoun val5 = new CompatibleNoun(); val5.noun = val4; val5.result = newSuit.shopSelectionNode; List<CompatibleNoun> list = buyKeyword.compatibleNouns.ToList(); list.Add(val5); buyKeyword.compatibleNouns = list.ToArray(); List<TerminalKeyword> list2 = val.terminalNodes.allKeywords.ToList(); list2.Add(val4); list2.Add(val2.noun); list2.Add(val3.noun); val.terminalNodes.allKeywords = list2.ToArray(); return newSuit; } public static bool TryParseVector4(string input, out Vector4 vector) { //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_0051: 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) vector = Vector4.zero; string[] array = input.Split(','); if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4)) { vector = new Vector4(result, result2, result3, result4); return true; } return false; } }
plugins/NeedyCats.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using 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 BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Unity.Netcode; using Unity.Netcode.Samples; using UnityEngine; using UnityEngine.AI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("NeedyCats")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NeedyCats")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("c7d3e258-85ed-4246-9766-b0915f7aec88")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] internal class <Module> { static <Module>() { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } } namespace NeedyCats { public class NeedyCatProp : PhysicsProp, INoiseListener { [Space(3f)] public Animator animator; public AudioSource audioSource; public SkinnedMeshRenderer skinnedMeshRenderer; [Space(3f)] public Vector2 IntervalMeow; public Vector2 IntervalMove; public Vector2 IntervalSitAnimChange; public Vector2 IntervalIdleAnimChange; public float WalkingSpeed = 1f; public float RunningSpeed = 8f; private (int, float)[] placeableMeowInterval; [HideInInspector] public (string, int)[] CatNames; private float timeBeforeNextMove = 1f; private float timeBeforeNextMeow = 1f; private float timeBeforeNextSitAnim = 1f; private int sitAnimationsLength = 3; private float timeBeforeNextIdleAnim = 1f; private int idleAnimationsLength = 4; private bool isSitting; private int materialIndex; private int nameIndex; private bool hasLoadedSave; private HoarderBugItem hoarderBugItem; [Space(3f)] public AudioClip[] noiseSFX; public AudioClip[] fleeSFX; public AudioClip[] calmSFX; [Space(3f)] public float noiseRange = 65f; public float maxLoudness = 1f; public float minLoudness = 0.95f; public float minPitch = 0.9f; public float maxPitch = 1f; private NavMeshAgent agent; private Random random; [Space(3f)] public Vector3 destination; private GameObject[] allAINodes; private NavMeshPath navmeshPath; private float velX; private float velY; private Vector3 previousPosition; private Vector3 agentLocalVelocity; private ClientNetworkTransform clientNetworkTransform; private bool isBeingHoarded { get { //IL_000e: 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) if (hoarderBugItem != null) { return Vector3.Distance(((Component)this).transform.position, hoarderBugItem.itemNestPosition) < 2f; } return false; } } public void Awake() { } public override void Start() { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: 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_00c8: Expected O, but got Unknown ((GrabbableObject)this).Start(); try { if ((Object)(object)agent == (Object)null) { agent = ((Component)this).GetComponent<NavMeshAgent>(); } if ((Object)(object)animator == (Object)null) { animator = ((Component)this).GetComponentInChildren<Animator>(); } if ((Object)(object)skinnedMeshRenderer == (Object)null) { skinnedMeshRenderer = ((Component)this).GetComponentInChildren<SkinnedMeshRenderer>(); } clientNetworkTransform = ((Component)this).GetComponent<ClientNetworkTransform>(); random = new Random(StartOfRound.Instance.randomMapSeed + 85); GameObject[] first = GameObject.FindGameObjectsWithTag("AINode"); GameObject[] second = GameObject.FindGameObjectsWithTag("OutsideAINode"); allAINodes = first.Concat(second).ToArray(); agent.updatePosition = false; destination = ((Component)this).transform.position; navmeshPath = new NavMeshPath(); ((NetworkBehaviour)this).NetworkManager.OnClientConnectedCallback += NetworkManager_OnClientConnectedCallback; placeableMeowInterval = new(int, float)[3] { (22, 10f), (21, 2f), (4, 6f) }; } catch (Exception arg) { Debug.LogError((object)$"Error when initializing variables for {((Object)((Component)this).gameObject).name} : {arg}"); } if (((NetworkBehaviour)this).IsServer && !hasLoadedSave) { nameIndex = Random.Range(0, CatNames.Length); SetCatNameServerRpc(CatNames[nameIndex].Item1); if (CatNames[nameIndex].Item2 != -1) { materialIndex = CatNames[nameIndex].Item2; } else { materialIndex = Random.Range(0, ((GrabbableObject)this).itemProperties.materialVariants.Length); } SetCatMaterialServerRpc(materialIndex); } } public override void OnDestroy() { ((NetworkBehaviour)this).OnDestroy(); ((NetworkBehaviour)this).NetworkManager.OnClientConnectedCallback -= NetworkManager_OnClientConnectedCallback; } private void NetworkManager_OnClientConnectedCallback(ulong obj) { if (((NetworkBehaviour)this).IsServer) { SetCatMaterialServerRpc(materialIndex); SetCatNameServerRpc(CatNames[nameIndex].Item1); if (isSitting) { MakeCatSitServerRpc(sit: true); } } } public override void LoadItemSaveData(int saveData) { ((MonoBehaviour)this).StartCoroutine(NetworkSafeLoadItemSaveData(saveData)); } private IEnumerator NetworkSafeLoadItemSaveData(int saveData) { yield return ((NetworkBehaviour)this).IsSpawned; if (((NetworkBehaviour)this).IsServer) { <>n__0(saveData); int catMaterialServerRpc = (saveData >> 16) & 0xFFFF; int num = saveData & 0xFFFF; if (num > CatNames.Length) { num = Random.Range(0, CatNames.Length); } SetCatNameServerRpc(CatNames[num].Item1); if (CatNames[num].Item2 != -1) { catMaterialServerRpc = CatNames[num].Item2; } SetCatMaterialServerRpc(catMaterialServerRpc); materialIndex = catMaterialServerRpc; nameIndex = num; hasLoadedSave = true; } } public override int GetItemDataToSave() { return (materialIndex << 16) | nameIndex; } private void SynchronizeAnimator(float maxSpeed = 4f) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) agentLocalVelocity = ((Component)animator).transform.InverseTransformDirection(Vector3.ClampMagnitude(((Component)this).transform.position - previousPosition, 1f) / (Time.deltaTime * 2f)); animator.SetBool("move", ((Vector3)(ref agentLocalVelocity)).magnitude > 0.05f); velX = Mathf.Lerp(velX, agentLocalVelocity.x, 10f * Time.deltaTime); animator.SetFloat("velx", Mathf.Clamp(velX, 0f - maxSpeed, maxSpeed)); velY = Mathf.Lerp(velY, agentLocalVelocity.z, 10f * Time.deltaTime); animator.SetFloat("vely", Mathf.Clamp(velY, 0f - maxSpeed, maxSpeed)); previousPosition = ((Component)this).transform.position; } public override void GrabItem() { animator.SetBool("move", false); animator.SetFloat("velx", 0f); animator.SetFloat("vely", 0f); animator.SetBool("held", true); isSitting = false; ((GrabbableObject)this).GrabItem(); if (((NetworkBehaviour)this).IsOwner) { HUDManager.Instance.DisplayTip("Cat Facts", "Too noisy? Give your cat a pet to quiet it down for a bit!", false, true, "LC_NeedyCatsTip"); } } public override void DiscardItem() { animator.SetBool("held", false); ((GrabbableObject)this).DiscardItem(); } public override void GrabItemFromEnemy(EnemyAI enemy) { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown ((GrabbableObject)this).isHeldByEnemy = true; animator.SetBool("move", false); animator.SetFloat("velx", 0f); animator.SetFloat("vely", 0f); animator.SetBool("held", true); ((GrabbableObject)this).GrabItemFromEnemy(enemy); if (((NetworkBehaviour)this).IsServer && enemy is HoarderBugAI) { HoarderBugAI val = (HoarderBugAI)enemy; hoarderBugItem = (((Object)(object)val.heldItem.itemGrabbableObject == (Object)(object)this) ? val.heldItem : null); } } public override void DiscardItemFromEnemy() { ((GrabbableObject)this).isHeldByEnemy = false; animator.SetBool("held", false); ((GrabbableObject)this).DiscardItemFromEnemy(); } public override void Update() { //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) //IL_00cc: 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_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: Unknown result type (might be due to invalid IL or missing references) ((Behaviour)clientNetworkTransform).enabled = !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy; if (((NetworkBehaviour)this).IsServer && !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && !((NetworkBehaviour)this).IsOwner) { ((Component)this).GetComponent<NetworkObject>().RemoveOwnership(); } if (!((GrabbableObject)this).isInElevator && StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap) { ((Behaviour)agent).enabled = !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && ((GrabbableObject)this).reachedFloorTarget && !(((GrabbableObject)this).fallTime < 1f); if (((GrabbableObject)this).fallTime >= 1f && !((GrabbableObject)this).reachedFloorTarget) { ((GrabbableObject)this).targetFloorPosition = ((Component)this).transform.position; destination = ((Component)this).transform.position; previousPosition = ((Component)this).transform.position; ((Behaviour)agent).enabled = true; } } if (((GrabbableObject)this).fallTime >= 1f && !((GrabbableObject)this).reachedFloorTarget && animator.GetBool("held")) { animator.SetBool("held", false); } if (((GrabbableObject)this).isHeld || ((GrabbableObject)this).isHeldByEnemy || !((GrabbableObject)this).reachedFloorTarget || ((GrabbableObject)this).fallTime < 1f || ((GrabbableObject)this).isInElevator) { ((GrabbableObject)this).Update(); } if (((NetworkBehaviour)this).IsServer && !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && (((GrabbableObject)this).isInElevator || isBeingHoarded) && !isSitting) { MakeCatSitServerRpc(sit: true); } else if (((NetworkBehaviour)this).IsServer && !((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && !((GrabbableObject)this).isInElevator && !isBeingHoarded && isSitting && StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap) { MakeCatSitServerRpc(sit: false); } if (((NetworkBehaviour)this).IsServer) { if (isSitting) { if (timeBeforeNextSitAnim <= 0f) { SetCatSitAnimationServerRpc(Random.Range(0, sitAnimationsLength)); timeBeforeNextSitAnim = Random.Range(IntervalSitAnimChange.x, IntervalSitAnimChange.y); } timeBeforeNextSitAnim -= Time.deltaTime; } else { if (timeBeforeNextIdleAnim <= 0f) { SetCatIdleAnimationServerRpc(Random.Range(0, idleAnimationsLength)); timeBeforeNextIdleAnim = Random.Range(IntervalIdleAnimChange.x, IntervalIdleAnimChange.y); } timeBeforeNextIdleAnim -= Time.deltaTime; } if (timeBeforeNextMeow <= 0f) { MakeCatMeowServerRpc(); float num = 0f; if (((GrabbableObject)this).isInElevator) { PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (val.isInElevator) { num += 2f; break; } } (int, float)[] array = placeableMeowInterval; for (int j = 0; j < array.Length; j++) { (int, float) tuple = array[j]; if (StartOfRound.Instance.SpawnedShipUnlockables.ContainsKey(tuple.Item1)) { num += tuple.Item2; } } } timeBeforeNextMeow = Random.Range(IntervalMeow.x + num, IntervalMeow.y + num); } timeBeforeNextMeow -= Time.deltaTime; if (!((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy && !((GrabbableObject)this).isInElevator && !isBeingHoarded && StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap) { if (timeBeforeNextMove <= 0f) { SetRandomDestination(); timeBeforeNextMove = Random.Range(IntervalMove.x, IntervalMove.y); } timeBeforeNextMove -= Time.deltaTime; ((Component)this).transform.position = agent.nextPosition; } } if (!((GrabbableObject)this).isHeld && !((GrabbableObject)this).isHeldByEnemy) { SynchronizeAnimator(); } } public void SetDestinationToPosition(Vector3 position, bool checkForPath = false) { //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: 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_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0034: 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_0081: 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_0092: Unknown result type (might be due to invalid IL or missing references) if (checkForPath) { position = RoundManager.Instance.GetNavMeshPosition(position, RoundManager.Instance.navHit, 1.75f, -1); navmeshPath = new NavMeshPath(); if (!agent.CalculatePath(position, navmeshPath)) { Debug.Log((object)(((Object)((Component)this).gameObject).name + " calculatepath returned false.")); return; } if (Vector3.Distance(navmeshPath.corners[navmeshPath.corners.Length - 1], RoundManager.Instance.GetNavMeshPosition(position, RoundManager.Instance.navHit, 2.7f, -1)) > 1.55f) { Debug.Log((object)(((Object)((Component)this).gameObject).name + " path calculation went wrong.")); return; } } destination = RoundManager.Instance.GetNavMeshPosition(position, RoundManager.Instance.navHit, -1f, -1); agent.SetDestination(destination); } public override void ItemActivate(bool used, bool buttonDown = true) { ((GrabbableObject)this).ItemActivate(used, buttonDown); if (((NetworkBehaviour)this).IsOwner) { MakeCatCalmServerRpc(); } } public void SetRandomDestination() { //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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)this).transform.position + Random.insideUnitSphere * 5f; agent.speed = WalkingSpeed; SetDestinationToPosition(position); } private void PlayCatNoise(AudioClip[] array, bool audible = true) { //IL_00ca: Unknown result type (might be due to invalid IL or missing references) int num = random.Next(0, array.Length); float num2 = (float)random.Next((int)(minLoudness * 100f), (int)(maxLoudness * 100f)) / 100f; float pitch = (float)random.Next((int)(minPitch * 100f), (int)(maxPitch * 100f)) / 100f; audioSource.pitch = pitch; audioSource.PlayOneShot(array[num], num2); WalkieTalkie.TransmitOneShotAudio(audioSource, array[num], num2 - 0.4f); if (audible) { noiseRange = (((GrabbableObject)this).isInElevator ? (noiseRange - 2.5f) : noiseRange); RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, noiseRange, num2, 0, ((GrabbableObject)this).isInElevator && StartOfRound.Instance.hangarDoorsClosed, 8881); } } [ServerRpc(RequireOwnership = false)] public void MakeCatMeowServerRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3454429685u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3454429685u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { MakeCatMeowClientRpc(); } } } [ClientRpc] public void MakeCatMeowClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1946573138u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1946573138u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { PlayCatNoise(noiseSFX); animator.SetTrigger("meow"); } } } [ServerRpc] public void MakeCatCalmServerRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Invalid comparison between Unknown and I4 //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2784153610u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2784153610u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } float num = 0f; if (((GrabbableObject)this).isInElevator) { PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val3 in allPlayerScripts) { if (val3.isInElevator) { num += 2f; break; } } (int, float)[] array = placeableMeowInterval; for (int j = 0; j < array.Length; j++) { (int, float) tuple = array[j]; if (StartOfRound.Instance.SpawnedShipUnlockables.ContainsKey(tuple.Item1)) { num += tuple.Item2; } } } timeBeforeNextMeow = Random.Range(IntervalMeow.x + num + 3f, IntervalMeow.y + num + 6f); MakeCatCalmClientRpc(); } [ClientRpc] public void MakeCatCalmClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2302897036u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2302897036u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { ((GrabbableObject)this).playerHeldBy.doingUpperBodyEmote = 1.16f; ((GrabbableObject)this).playerHeldBy.playerBodyAnimator.SetTrigger("PullGrenadePin2"); ((MonoBehaviour)this).StartCoroutine(PlayCatCalmNoiseDelayed()); } } } private IEnumerator PlayCatCalmNoiseDelayed() { yield return (object)new WaitForSeconds(0.5f); PlayCatNoise(calmSFX, audible: false); } [ServerRpc] public void MakeCatSitServerRpc(bool sit) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Invalid comparison between Unknown and I4 //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2411027775u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref sit, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2411027775u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { MakeCatSitClientRpc(sit); } } [ClientRpc] public void MakeCatSitClientRpc(bool sit) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0083: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3921800473u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref sit, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3921800473u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { animator.SetBool("sit", sit); isSitting = sit; } } } [ServerRpc(RequireOwnership = false)] public void SetCatMaterialServerRpc(int index) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2046492207u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, index); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2046492207u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { SetCatMaterialClientRpc(index); } } } [ClientRpc] public void SetCatMaterialClientRpc(int index) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3875721248u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, index); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3875721248u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && (Object)(object)skinnedMeshRenderer != (Object)null) { ((Renderer)skinnedMeshRenderer).sharedMaterial = ((GrabbableObject)this).itemProperties.materialVariants[index]; } } } [ServerRpc(RequireOwnership = false)] public void SetCatNameServerRpc(string name) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3049925245u, val, (RpcDelivery)0); bool flag = name != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(name, false); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3049925245u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { SetCatNameClientRpc(name); } } [ClientRpc] public void SetCatNameClientRpc(string name) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1321450034u, val, (RpcDelivery)0); bool flag = name != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(name, false); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1321450034u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { ((Component)this).GetComponentInChildren<ScanNodeProperties>().headerText = "Cat (" + name + ")"; } } [ServerRpc(RequireOwnership = false)] public void SetCatIdleAnimationServerRpc(int index) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1770904636u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, index); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1770904636u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { SetCatIdleAnimationClientRpc(index); } } } [ClientRpc] public void SetCatIdleAnimationClientRpc(int index) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(283245169u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, index); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 283245169u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { animator.SetInteger("idleAnimation", index); } } } [ServerRpc(RequireOwnership = false)] public void SetCatSitAnimationServerRpc(int index) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1062797608u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, index); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1062797608u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { SetCatSitAnimationClientRpc(index); } } } [ClientRpc] public void SetCatSitAnimationClientRpc(int index) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4162097660u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, index); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4162097660u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { animator.SetInteger("sitAnimation", index); } } } public virtual void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) if (((GrabbableObject)this).isHeld || ((GrabbableObject)this).isHeldByEnemy || noiseID == 8881 || noiseID == 75 || ((GrabbableObject)this).isInShipRoom || !StartOfRound.Instance.currentLevel.spawnEnemiesAndScrap) { return; } Vector3 val = noisePosition - ((Component)this).transform.position; if (!(((Vector3)(ref val)).magnitude < 5f) || !(noiseLoudness > 0.8f)) { return; } PlayCatNoise(fleeSFX); if (((NetworkBehaviour)this).IsServer) { Vector3 position = ((Component)this).transform.position - ((Vector3)(ref val)).normalized * 20f; GameObject[] array = allAINodes.OrderBy((GameObject x) => Vector3.Distance(position, x.transform.position)).ToArray(); SetDestinationToPosition(array[0].transform.position); agent.speed = RunningSpeed; timeBeforeNextMove = Random.Range(IntervalMove.x + 1f, IntervalMove.y + 2f); } } [CompilerGenerated] [DebuggerHidden] private void <>n__0(int saveData) { ((GrabbableObject)this).LoadItemSaveData(saveData); } protected override void __initializeVariables() { ((PhysicsProp)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_NeedyCatProp() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Expected O, but got Unknown //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Expected O, but got Unknown //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(3454429685u, new RpcReceiveHandler(__rpc_handler_3454429685)); NetworkManager.__rpc_func_table.Add(1946573138u, new RpcReceiveHandler(__rpc_handler_1946573138)); NetworkManager.__rpc_func_table.Add(2784153610u, new RpcReceiveHandler(__rpc_handler_2784153610)); NetworkManager.__rpc_func_table.Add(2302897036u, new RpcReceiveHandler(__rpc_handler_2302897036)); NetworkManager.__rpc_func_table.Add(2411027775u, new RpcReceiveHandler(__rpc_handler_2411027775)); NetworkManager.__rpc_func_table.Add(3921800473u, new RpcReceiveHandler(__rpc_handler_3921800473)); NetworkManager.__rpc_func_table.Add(2046492207u, new RpcReceiveHandler(__rpc_handler_2046492207)); NetworkManager.__rpc_func_table.Add(3875721248u, new RpcReceiveHandler(__rpc_handler_3875721248)); NetworkManager.__rpc_func_table.Add(3049925245u, new RpcReceiveHandler(__rpc_handler_3049925245)); NetworkManager.__rpc_func_table.Add(1321450034u, new RpcReceiveHandler(__rpc_handler_1321450034)); NetworkManager.__rpc_func_table.Add(1770904636u, new RpcReceiveHandler(__rpc_handler_1770904636)); NetworkManager.__rpc_func_table.Add(283245169u, new RpcReceiveHandler(__rpc_handler_283245169)); NetworkManager.__rpc_func_table.Add(1062797608u, new RpcReceiveHandler(__rpc_handler_1062797608)); NetworkManager.__rpc_func_table.Add(4162097660u, new RpcReceiveHandler(__rpc_handler_4162097660)); } private static void __rpc_handler_3454429685(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)1; ((NeedyCatProp)(object)target).MakeCatMeowServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1946573138(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)2; ((NeedyCatProp)(object)target).MakeCatMeowClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2784153610(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between Unknown and I4 NetworkManager networkManager = target.NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } } else { target.__rpc_exec_stage = (__RpcExecStage)1; ((NeedyCatProp)(object)target).MakeCatCalmServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2302897036(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)2; ((NeedyCatProp)(object)target).MakeCatCalmClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2411027775(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between Unknown and I4 NetworkManager networkManager = target.NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } } else { bool sit = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref sit, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)1; ((NeedyCatProp)(object)target).MakeCatSitServerRpc(sit); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3921800473(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool sit = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref sit, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)2; ((NeedyCatProp)(object)target).MakeCatSitClientRpc(sit); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2046492207(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int catMaterialServerRpc = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref catMaterialServerRpc); target.__rpc_exec_stage = (__RpcExecStage)1; ((NeedyCatProp)(object)target).SetCatMaterialServerRpc(catMaterialServerRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3875721248(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int catMaterialClientRpc = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref catMaterialClientRpc); target.__rpc_exec_stage = (__RpcExecStage)2; ((NeedyCatProp)(object)target).SetCatMaterialClientRpc(catMaterialClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3049925245(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0061: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string catNameServerRpc = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref catNameServerRpc, false); } target.__rpc_exec_stage = (__RpcExecStage)1; ((NeedyCatProp)(object)target).SetCatNameServerRpc(catNameServerRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1321450034(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0061: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string catNameClientRpc = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref catNameClientRpc, false); } target.__rpc_exec_stage = (__RpcExecStage)2; ((NeedyCatProp)(object)target).SetCatNameClientRpc(catNameClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1770904636(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int catIdleAnimationServerRpc = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref catIdleAnimationServerRpc); target.__rpc_exec_stage = (__RpcExecStage)1; ((NeedyCatProp)(object)target).SetCatIdleAnimationServerRpc(catIdleAnimationServerRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_283245169(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int catIdleAnimationClientRpc = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref catIdleAnimationClientRpc); target.__rpc_exec_stage = (__RpcExecStage)2; ((NeedyCatProp)(object)target).SetCatIdleAnimationClientRpc(catIdleAnimationClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1062797608(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int catSitAnimationServerRpc = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref catSitAnimationServerRpc); target.__rpc_exec_stage = (__RpcExecStage)1; ((NeedyCatProp)(object)target).SetCatSitAnimationServerRpc(catSitAnimationServerRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_4162097660(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int catSitAnimationClientRpc = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref catSitAnimationClientRpc); target.__rpc_exec_stage = (__RpcExecStage)2; ((NeedyCatProp)(object)target).SetCatSitAnimationClientRpc(catSitAnimationClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "NeedyCatProp"; } } public class NoiseListenerRedirect : MonoBehaviour, INoiseListener { private INoiseListener target; public void Awake() { target = ((Component)((Component)this).transform.parent).GetComponent<INoiseListener>(); } public void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) INoiseListener obj = target; if (obj != null) { obj.DetectNoise(noisePosition, noiseLoudness, timesPlayedInOneSpot, noiseID); } } } [BepInPlugin("Jordo.NeedyCats", "Needy Cats", "1.1.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class NeedyCatsBase : BaseUnityPlugin { public static class Assets { public static string mainAssetBundleName = "needycats"; public static AssetBundle MainAssetBundle = null; private static string GetAssemblyName() { return Assembly.GetExecutingAssembly().FullName.Split(new char[1] { ',' })[0]; } public static void PopulateAssets() { if ((Object)(object)MainAssetBundle == (Object)null) { using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(GetAssemblyName() + "." + mainAssetBundleName)) { MainAssetBundle = AssetBundle.LoadFromStream(stream); } } } } private const string modGUID = "Jordo.NeedyCats"; private const string modName = "Needy Cats"; private const string modVersion = "1.1.1"; private readonly Harmony harmony = new Harmony("Jordo.NeedyCats"); public static NeedyCatsBase Instance; private static List<(string, int)> catNames = new List<(string, int)>(); private static ConfigEntry<int> spawnRate; private static ConfigEntry<string> catNamesConfig; internal static ManualLogSource mls; private string defaultCatNames = "One:Stripes,Bella,Tigger,Chloe,Shadow,Luna,Oreo,Oliver,Kitty,Lucy,Molly,Jasper,Smokey,Gizmo,Simba,Tiger,Charlie,Angel,Jack,Lily,Peanut,Toby,Baby,Loki,Midnight,Milo,Princess,Sophie,Harley,Max,Missy,Rocky,Zoe,CoCo,Misty,Nala,Oscar,Pepper,Sasha,Buddy,Pumpkin,Kiki,Mittens,Bailey,Callie,Lucky,Patches,Simon,Garfield:Orange,George,Maggie,Sammy,Sebastian,Boots,Cali,Felix,Lilly,Phoebe,Sassy,Tucker,Bandit,Dexter,Fiona,Jake,Precious,Romeo,Snickers,Socks,Daisy,Gracie,Lola,Sadie,Sox,Casper,Fluffy,Marley,Minnie,Sweetie,Ziggy,Belle,Blackie,Chester,Frankie,Ginger,Muffin,Murphy,Rusty,Scooter,Batman,Boo,Cleo,Izzy,Jasmine,Mimi,Sugar,Cupcake,Dusty,Leo,Noodle,Panda,Peaches"; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Jordo.NeedyCats"); PatchNetcode(); Assets.PopulateAssets(); spawnRate = ((BaseUnityPlugin)this).Config.Bind<int>("NeedyCats", "Spawn rate", 20, "Sets the cat's spawn rate (This affects all moons)."); catNamesConfig = ((BaseUnityPlugin)this).Config.Bind<string>("NeedyCats", "Cat names", defaultCatNames, "Possible cat names separated by a colon (,). If the cat's name is followed by ':', you can input a material that'll be forced for that name among the following: Black, White, Spots, Boots, Orange, Stripes. You can find an image showcasing each material on the mod's wiki on Thunderstore. This list must contain at least one name. Example string: 'Daisy,Garfield:Orange,Chloe'"); string[] array = catNamesConfig.Value.Split(new char[1] { ',' }); foreach (string text in array) { string[] array2 = text.Split(new char[1] { ':' }); catNames.Add((array2[0], (array2.Length > 1) ? GetMaterialID(array2[1]) : (-1))); } harmony.PatchAll(typeof(NeedyCatsBase)); mls.LogInfo((object)"Initialized Needy Cats"); } private int GetMaterialID(string name) { return name.ToLower() switch { "black" => 0, "white" => 1, "boots" => 2, "spots" => 3, "orange" => 4, "stripes" => 5, _ => -1, }; } private void PatchNetcode() { Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array = types; foreach (Type type in array) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array2 = methods; foreach (MethodInfo methodInfo in array2) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } } [HarmonyPatch(typeof(GameNetworkManager), "Start")] [HarmonyPostfix] private static void AddNeedyCatsToNetworkManager(GameNetworkManager __instance) { ((Component)__instance).GetComponent<NetworkManager>().AddNetworkPrefab(Assets.MainAssetBundle.LoadAsset<GameObject>("Cat.prefab")); mls.LogInfo((object)"Added Needy Cats prefab to Network Manager."); } [HarmonyPatch(typeof(StartOfRound), "Awake")] [HarmonyPostfix] private static void AddNeedyCatsToItems(StartOfRound __instance) { Item item = Assets.MainAssetBundle.LoadAsset<Item>("CatItem"); if (!__instance.allItemsList.itemsList.Contains(item)) { __instance.allItemsList.itemsList.Add(item); } mls.LogInfo((object)"Added Needy Cats to items list."); } [HarmonyPatch(typeof(StartOfRound), "Start")] [HarmonyPrefix] private static void AddNeedyCatsToAllLevels(StartOfRound __instance) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown Item item = Assets.MainAssetBundle.LoadAsset<Item>("CatItem"); SpawnableItemWithRarity val = new SpawnableItemWithRarity(); val.rarity = spawnRate.Value; val.spawnableItem = item; SelectableLevel[] levels = __instance.levels; foreach (SelectableLevel val2 in levels) { if (val2.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)item)) { return; } val2.spawnableScrap.Add(val); } mls.LogInfo((object)"Added Needy Cats to all levels."); } [HarmonyPatch(typeof(HoarderBugAI), "GrabTargetItemIfClose")] [HarmonyPrefix] private static bool GrabTargetItemIfClose(HoarderBugAI __instance) { //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_005b: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: 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) float num = ((__instance.targetItem is NeedyCatProp) ? 1f : 0.75f); if ((Object)(object)__instance.targetItem != (Object)null && __instance.heldItem == null && Vector3.Distance(((Component)__instance).transform.position, ((Component)__instance.targetItem).transform.position) < num) { if (!((EnemyAI)__instance).SetDestinationToPosition(__instance.nestPosition, true)) { __instance.nestPosition = ((EnemyAI)__instance).ChooseClosestNodeToPosition(((Component)__instance).transform.position, false, 0).position; ((EnemyAI)__instance).SetDestinationToPosition(__instance.nestPosition, false); } NetworkObject component = ((Component)__instance.targetItem).GetComponent<NetworkObject>(); ((EnemyAI)__instance).SwitchToBehaviourStateOnLocalClient(1); __instance.GrabItem(component); __instance.sendingGrabOrDropRPC = true; __instance.GrabItemServerRpc(NetworkObjectReference.op_Implicit(component)); return true; } return false; } [HarmonyPatch(typeof(NeedyCatProp), "Awake")] [HarmonyPrefix] private static void AddNeedyCatsNames(NeedyCatProp __instance) { __instance.CatNames = catNames.ToArray(); } } }
plugins/OctolarFirstMod.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using OctolarFirstMod.Patches; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("OctolarFirstMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OctolarFirstMod")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("a761e7d0-2e73-4d38-b7ad-3010bdcd4702")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace OctolarFirstMod { [BepInPlugin("Octolar.Healthstation", "Health Station mod", "1.0.0.1")] public class OctolarFirstMod : BaseUnityPlugin { private const string modGUID = "Octolar.Healthstation"; private const string modName = "Health Station mod"; private const string modVersion = "1.0.0.1"; private readonly Harmony harmony = new Harmony("Octolar.Healthstation"); private static OctolarFirstMod Instance; internal ManualLogSource mls; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Octolar.Healthstation"); mls.LogInfo((object)"Octolar HealthStation mod is now active"); harmony.PatchAll(typeof(OctolarFirstMod)); harmony.PatchAll(typeof(ItemChargerPatch)); } } } namespace OctolarFirstMod.Patches { [HarmonyPatch(typeof(PlayerControllerB))] [HarmonyPatch(typeof(ItemCharger))] internal class ItemChargerPatch { [HarmonyPatch("ChargeItem")] [HarmonyPostfix] private static void ChargerHealsPatch() { //IL_0014: 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) GameNetworkManager.Instance.localPlayerController.DamagePlayer(-100, false, true, (CauseOfDeath)0, 0, false, default(Vector3)); if (GameNetworkManager.Instance.localPlayerController.health >= 10 && GameNetworkManager.Instance.localPlayerController.criticallyInjured) { GameNetworkManager.Instance.localPlayerController.MakeCriticallyInjured(false); } } } }
plugins/PacManDog.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using PacManDog.Patches; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("PacManDog")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PacManDog")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("11ecdc4c-2730-4bd5-851e-e4abaaf2505f")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace PacManDog { [BepInPlugin("PacManDog", "Pac Man Dog", "1.2.3")] public class PacManDogBase : BaseUnityPlugin { private const string modGUID = "PacManDog"; private const string modName = "Pac Man Dog"; private const string modVersion = "1.2.3"; private readonly Harmony harmony = new Harmony("PacManDog"); private static PacManDogBase Instance; internal ManualLogSource mls; internal static AudioClip[] newScreamSFX; internal static AudioClip[] newKillPlayerSFX; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("PacManDog"); mls.LogInfo((object)"PacManDog is loading."); string location = ((BaseUnityPlugin)Instance).Info.Location; string text = "PacManDog.dll"; string text2 = location.TrimEnd(text.ToCharArray()); string text3 = text2 + "pacmansounds"; AssetBundle val = AssetBundle.LoadFromFile(text3); if ((Object)(object)val == (Object)null) { mls.LogError((object)"Failed to load audio assets!"); return; } newScreamSFX = val.LoadAssetWithSubAssets<AudioClip>("assets/pacmanchasingghosts.mp3"); newKillPlayerSFX = val.LoadAssetWithSubAssets<AudioClip>("assets/pacmandeath.mp3"); harmony.PatchAll(typeof(MouthDogAIPatch)); mls.LogInfo((object)"PacManDog is loaded."); } } } namespace PacManDog.Patches { [HarmonyPatch(typeof(MouthDogAI))] internal class MouthDogAIPatch { [HarmonyPatch("Start")] [HarmonyPostfix] public static void mouthDogAudioPatch(ref AudioClip ___screamSFX, ref AudioClip ___killPlayerSFX) { AudioClip val = PacManDogBase.newScreamSFX[0]; ___screamSFX = val; AudioClip val2 = PacManDogBase.newKillPlayerSFX[0]; ___killPlayerSFX = val2; } } }
plugins/PossessedMask.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; 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 BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using UnityEngine; using UnityEngine.InputSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("PossessedMask")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PossessedMask")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4F62CD59-C324-4153-BDDC-B58865CC6A5A")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [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 PossessedMask { [BepInPlugin("oe.tweaks.qol.possessedmask", "Possessed Mask", "1.0.0")] public class Plugin : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("oe.tweaks.qol.possessedmask"); private const string GUID = "oe.tweaks.qol.possessedmask"; private const string NAME = "Possessed Mask"; private const string VERSION = "1.0.0"; internal static Plugin Instance; internal static ManualLogSource Log; internal static ConfigEntry<bool> enableMaskPossessionMechanic; internal static ConfigEntry<bool> enableMaskSwitchSlotMechanic; internal static ConfigEntry<int> enableChangeMaskSpawnChance; internal static ConfigEntry<int> numberOfSlotsFilledToEnableDroppingMask; internal static ConfigEntry<float> timeToStartSwitchingSlots; internal static ConfigEntry<float> timeToStartPossession; internal static ConfigEntry<bool> twoHandedItemBehaviour; internal static ConfigEntry<int> maskRarity; internal static ConfigEntry<bool> maskRarityScaling; internal static ConfigEntry<float> maskRarityScalingMultiplier; internal static ConfigEntry<int> minMaskItemBaseValue; internal static ConfigEntry<int> maxMaskItemBaseValue; internal static ConfigEntry<float> minTimeToSwitchSlots; internal static ConfigEntry<float> maxTimeToSwitchSlots; internal static ConfigEntry<float> deltaTimeToSwitchSlots; internal static ConfigEntry<float> minSwitchingSlotTime; internal static ConfigEntry<float> minTimeToPossess; internal static ConfigEntry<float> maxTimeToPossess; internal static ConfigEntry<float> deltaTimeToPossess; internal static ConfigEntry<float> minPossessingTime; internal static ConfigEntry<float> minTimeToPossessPlayer; internal static ConfigEntry<float> maxTimeToPossessPlayer; internal static ConfigEntry<float> deltaTimeToPossessPlayer; internal static ConfigEntry<float> maxPossessingPlayerTime; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; Log.LogInfo((object)"'Possessed Mask' is loading..."); if ((Object)(object)Instance == (Object)null) { Instance = this; } enableMaskPossessionMechanic = ((BaseUnityPlugin)this).Config.Bind<bool>("Mechanics", "EnableMaskPossessionMechanic", true, "If true, mask possession mechanic will be enabled"); enableMaskSwitchSlotMechanic = ((BaseUnityPlugin)this).Config.Bind<bool>("Mechanics", "EnableMaskSwitchSlotMechanic", true, "If true, mask switching to your active slot mechanic will be enabled"); enableChangeMaskSpawnChance = ((BaseUnityPlugin)this).Config.Bind<int>("Mechanics", "EnableChangeMaskSpawnChance", 2, "If 0, will not override mask spawn chance, scrap value and available levels.\nIf 1, will override spawn chance, scrap value but not available levels.\nif 2 will override all of them."); numberOfSlotsFilledToEnableDroppingMask = ((BaseUnityPlugin)this).Config.Bind<int>("General", "NumberOfSlotsFilledToEnableDroppingMask", 3, "Number of inventory slots that need to be filled to enable dropping a mask"); timeToStartSwitchingSlots = ((BaseUnityPlugin)this).Config.Bind<float>("General", "TimeToStartSwitchingSlots", 5f, "After this much time with mask in inventory start switching slots"); timeToStartPossession = ((BaseUnityPlugin)this).Config.Bind<float>("General", "TimeToStartPossession", 10f, "After this much time with mask in inventory start possessions"); twoHandedItemBehaviour = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "TwoHandedItemBehaviour", true, "If true, 2 handed items will be dropped when switching slots"); maskRarity = ((BaseUnityPlugin)this).Config.Bind<int>("Mask Rarity", "MaskRarity", 35, "Rarity of mask item 0 - 100 (0 - doesn't spawn, 100 - spawns a lot)"); maskRarityScaling = ((BaseUnityPlugin)this).Config.Bind<bool>("Mask Rarity", "MaskRarityScaling", true, "If true, mask rarity will be scaled up by moon rank"); maskRarityScalingMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Mask Rarity", "MaskRarityScalingMultiplier", 0.5f, "Multiplier for mask rarity scaling"); minMaskItemBaseValue = ((BaseUnityPlugin)this).Config.Bind<int>("Mask Item Base Value", "MinMaskItemBaseValue", 100, "Minimum base value of mask item (affected by multipliers >1)"); maxMaskItemBaseValue = ((BaseUnityPlugin)this).Config.Bind<int>("Mask Item Base Value", "MaxMaskItemBaseValue", 150, "Maximum base value of mask item (affected by multipliers >1)"); minTimeToSwitchSlots = ((BaseUnityPlugin)this).Config.Bind<float>("Time To Switch Slots", "MinTimeToSwitchSlots", 12f, "Minimum time between switching slots"); maxTimeToSwitchSlots = ((BaseUnityPlugin)this).Config.Bind<float>("Time To Switch Slots", "MaxTimeToSwitchSlots", 20f, "Maximum time between switching slots"); deltaTimeToSwitchSlots = ((BaseUnityPlugin)this).Config.Bind<float>("Time To Switch Slots", "DeltaTimeToSwitchSlots", 0.5f, "Time to subtract from min and max each time a switch happens"); minSwitchingSlotTime = ((BaseUnityPlugin)this).Config.Bind<float>("Time To Switch Slots", "MinSwitchingSlotTime", 3f, "The number at which subtracting from min and max stops"); minTimeToPossess = ((BaseUnityPlugin)this).Config.Bind<float>("Time To Possess", "MinTimeToPossess", 20f, "Minimum time between possessions"); maxTimeToPossess = ((BaseUnityPlugin)this).Config.Bind<float>("Time To Possess", "MaxTimeToPossess", 30f, "Maximum time between possessions"); deltaTimeToPossess = ((BaseUnityPlugin)this).Config.Bind<float>("Time To Possess", "DeltaTimeToPossess", 1f, "Time to subtract from min and max each time a possession happens"); minPossessingTime = ((BaseUnityPlugin)this).Config.Bind<float>("Time To Possess", "MinPossessingTime", 10f, "The number at which subtracting from min and max stops"); minTimeToPossessPlayer = ((BaseUnityPlugin)this).Config.Bind<float>("Item Activation Time", "MinTimeToPossessPlayer", 2f, "Minimum time of actual possession"); maxTimeToPossessPlayer = ((BaseUnityPlugin)this).Config.Bind<float>("Item Activation Time", "MaxTimeToPossessPlayer", 4f, "Maximum time of actual possession"); deltaTimeToPossessPlayer = ((BaseUnityPlugin)this).Config.Bind<float>("Item Activation Time", "DeltaTimeToPossessPlayer", 1f, "Time to add to min and max each time a possession happens"); maxPossessingPlayerTime = ((BaseUnityPlugin)this).Config.Bind<float>("Item Activation Time", "MaxPossessingPlayerTime", 9f, "The number at which adding to min and max stops"); harmony.PatchAll(); Log.LogInfo((object)"'Possessed Mask' loaded!"); } } } namespace PossessedMask.Patches { [HarmonyPatch(typeof(PlayerControllerB))] public class PlayerControllerBPatch { [HarmonyPatch("Discard_performed")] [HarmonyPrefix] private static bool PatchDiscard(PlayerControllerB __instance, CallbackContext context) { GrabbableObject val = __instance.ItemSlots[__instance.currentItemSlot]; if ((Object)(object)val == (Object)null || ((object)val).GetType() != typeof(HauntedMaskItem)) { return true; } if (__instance.ItemSlots.Count((GrabbableObject slot) => (Object)(object)slot != (Object)null) < Plugin.numberOfSlotsFilledToEnableDroppingMask.Value) { return false; } return true; } [HarmonyPatch("ScrollMouse_performed")] [HarmonyPrefix] private static bool PatchScrollMouse_performed(PlayerControllerB __instance, CallbackContext context) { GrabbableObject val = __instance.ItemSlots[__instance.currentItemSlot]; if ((Object)(object)val != (Object)null && ((object)val).GetType() == typeof(HauntedMaskItem) && __instance.activatingItem) { return false; } return true; } [HarmonyPatch("KillPlayer")] [HarmonyPostfix] private static void PatchKillPlayer(PlayerControllerB __instance) { if (__instance.isPlayerDead) { IngamePlayerSettings.Instance.playerInput.actions.FindAction("ActivateItem", false).Enable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("Interact", false).Enable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("SwitchItem", false).Enable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("Discard", false).Enable(); } } } [HarmonyPatch(typeof(StartOfRound))] public class StartOfRoundPatch { private static PlayerControllerB localPlayer = null; private static float timeHeldByPlayer = 0f; private static float nextTimeToSwitchSlot = 0f; private static float timeUntilPossession = 0f; private static AudioClip[] possessionSounds = (AudioClip[])(object)new AudioClip[3]; private static AudioClip[] slotSwitchSounds = (AudioClip[])(object)new AudioClip[2]; private static float minTimeToSwitchSlots; private static float maxTimeToSwitchSlots; private static float deltaTimeToSwitchSlots; private static float minSwitchingSlotTime; private static float minTimeToPossess; private static float maxTimeToPossess; private static float deltaTimeToPossess; private static float minPossessingTime; private static float minTimeToPossessPlayer; private static float maxTimeToPossessPlayer; private static float deltaTimeToPossessPlayer; private static float maxPossessingPlayerTime; private static Terminal terminal = null; [HarmonyPatch("Start")] [HarmonyPostfix] private static void PatchLoadResources(StartOfRound __instance) { AssetBundle val = AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetManifestResourceNames()[0])); if ((Object)(object)val == (Object)null) { Plugin.Log.LogError((object)"Failed to load asset bundle"); return; } Plugin.Log.LogInfo((object)"Asset bundle loaded"); possessionSounds[0] = val.LoadAsset<AudioClip>("possession1"); possessionSounds[1] = val.LoadAsset<AudioClip>("possession2"); possessionSounds[2] = val.LoadAsset<AudioClip>("possession3"); slotSwitchSounds[0] = val.LoadAsset<AudioClip>("slot1"); slotSwitchSounds[1] = val.LoadAsset<AudioClip>("slot2"); ((MonoBehaviour)__instance).StartCoroutine(RegisterMasks()); minTimeToSwitchSlots = Plugin.minTimeToSwitchSlots.Value; maxTimeToSwitchSlots = Plugin.maxTimeToSwitchSlots.Value; deltaTimeToSwitchSlots = Plugin.deltaTimeToSwitchSlots.Value; minSwitchingSlotTime = Plugin.minSwitchingSlotTime.Value; minTimeToPossess = Plugin.minTimeToPossess.Value; maxTimeToPossess = Plugin.maxTimeToPossess.Value; deltaTimeToPossess = Plugin.deltaTimeToPossess.Value; minPossessingTime = Plugin.minPossessingTime.Value; minTimeToPossessPlayer = Plugin.minTimeToPossessPlayer.Value; maxTimeToPossessPlayer = Plugin.maxTimeToPossessPlayer.Value; deltaTimeToPossessPlayer = Plugin.deltaTimeToPossessPlayer.Value; maxPossessingPlayerTime = Plugin.maxPossessingPlayerTime.Value; } private static IEnumerator RegisterMasks() { if (Plugin.enableChangeMaskSpawnChance.Value == 0) { yield break; } while (!Object.op_Implicit((Object)(object)terminal)) { terminal = Object.FindObjectOfType<Terminal>(); yield return (object)new WaitForSeconds(1f); } Item val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item item) => item.itemName == "Comedy")); if (!Object.op_Implicit((Object)(object)val)) { Plugin.Log.LogError((object)"Comedy not found in allItemsList, skipping patching Comedy"); } else { val.minValue = Plugin.minMaskItemBaseValue.Value; val.maxValue = Plugin.maxMaskItemBaseValue.Value; } Item val2 = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item item) => item.itemName == "Tragedy")); if (!Object.op_Implicit((Object)(object)val2)) { Plugin.Log.LogError((object)"Tragedy not found in allItemsList, skipping patching Tragedy"); } else { val2.minValue = Plugin.minMaskItemBaseValue.Value; val2.maxValue = Plugin.maxMaskItemBaseValue.Value; } SelectableLevel[] moonsCatalogueList = terminal.moonsCatalogueList; float num = Plugin.maskRarityScalingMultiplier.Value; SelectableLevel[] array = moonsCatalogueList; foreach (SelectableLevel val3 in array) { int rarity = Mathf.Clamp(Mathf.RoundToInt((float)Plugin.maskRarity.Value * (1f + (Plugin.maskRarityScaling.Value ? num : 0f))), 0, 100); if (Object.op_Implicit((Object)(object)val)) { SpawnableItemWithRarity val4 = new SpawnableItemWithRarity(); val4.spawnableItem = val; val4.rarity = rarity; int num2 = val3.spawnableScrap.FindIndex((SpawnableItemWithRarity item) => item.spawnableItem.itemName == "Comedy"); if (num2 == -1 && Plugin.enableChangeMaskSpawnChance.Value == 2) { val3.spawnableScrap.Add(val4); } else { val3.spawnableScrap[num2] = val4; } } if (Object.op_Implicit((Object)(object)val2)) { SpawnableItemWithRarity val5 = new SpawnableItemWithRarity(); val5.spawnableItem = val2; val5.rarity = rarity; int num3 = val3.spawnableScrap.FindIndex((SpawnableItemWithRarity item) => item.spawnableItem.itemName == "Tragedy"); if (num3 == -1 && Plugin.enableChangeMaskSpawnChance.Value == 2) { val3.spawnableScrap.Add(val5); } else { val3.spawnableScrap[num3] = val5; } } if (Plugin.maskRarityScaling.Value) { num *= Plugin.maskRarityScalingMultiplier.Value; } } } [HarmonyPatch("openingDoorsSequence")] [HarmonyPostfix] private static void PatchOpeningDoorsSequence(StartOfRound __instance) { localPlayer = __instance.localPlayerController; timeUntilPossession = Plugin.timeToStartPossession.Value; timeHeldByPlayer = 0f; nextTimeToSwitchSlot = 0f; minTimeToSwitchSlots = Plugin.minTimeToSwitchSlots.Value; maxTimeToSwitchSlots = Plugin.maxTimeToSwitchSlots.Value; minTimeToPossess = Plugin.minTimeToPossess.Value; maxTimeToPossess = Plugin.maxTimeToPossess.Value; minTimeToPossessPlayer = Plugin.minTimeToPossessPlayer.Value; maxTimeToPossessPlayer = Plugin.maxTimeToPossessPlayer.Value; Plugin.Log.LogInfo((object)"Reset timers and reloaded config values"); } [HarmonyPatch("Update")] [HarmonyPostfix] private static void PatchUpdate() { if ((Object)(object)localPlayer == (Object)null || localPlayer.isPlayerDead || StartOfRound.Instance.inShipPhase || StartOfRound.Instance.currentLevelID == 3) { return; } nextTimeToSwitchSlot -= Time.deltaTime; bool flag = false; for (int i = 0; i < localPlayer.ItemSlots.Length; i++) { GrabbableObject val = localPlayer.ItemSlots[i]; if (!((Object)(object)val == (Object)null) && !(((object)val).GetType() != typeof(HauntedMaskItem))) { flag = true; break; } } if (!flag) { return; } timeHeldByPlayer += Time.deltaTime; timeUntilPossession -= Time.deltaTime; GrabbableObject val2 = localPlayer.ItemSlots[localPlayer.currentItemSlot]; if (Plugin.enableMaskPossessionMechanic.Value && (Object)(object)val2 != (Object)null && ((object)val2).GetType() == typeof(HauntedMaskItem)) { if (timeUntilPossession < 0f) { float num = Random.Range(minTimeToPossessPlayer, maxTimeToPossessPlayer); minTimeToPossessPlayer += ((minTimeToPossessPlayer < maxPossessingPlayerTime) ? deltaTimeToPossessPlayer : 0f); maxTimeToPossessPlayer += ((maxTimeToPossessPlayer < maxPossessingPlayerTime) ? deltaTimeToPossessPlayer : 0f); Plugin.Log.LogInfo((object)$"Player has held mask for enough time, possessing for {num} seconds"); timeUntilPossession = Random.Range(minTimeToPossess, maxTimeToPossess); minTimeToPossess -= ((minTimeToPossess > minPossessingTime) ? deltaTimeToPossess : 0f); maxTimeToPossess -= ((maxTimeToPossess > minPossessingTime) ? deltaTimeToPossess : 0f); PossessPlayer(num); nextTimeToSwitchSlot = num + 1f; } } else { if (!Plugin.enableMaskSwitchSlotMechanic.Value || !(timeHeldByPlayer > Plugin.timeToStartSwitchingSlots.Value) || !(nextTimeToSwitchSlot <= 0f)) { return; } Plugin.Log.LogMessage((object)"Player is not holding a mask, switching to closest held mask"); int num2 = localPlayer.ItemSlots.Length; GrabbableObject[] itemSlots = localPlayer.ItemSlots; int currentItemSlot = localPlayer.currentItemSlot; bool flag2 = false; bool forward = false; bool flag3 = false; for (int j = 1; j <= num2 / 2; j++) { int num3 = ((currentItemSlot + j) % num2 + num2) % num2; Plugin.Log.LogMessage((object)$"Checking slot: {num3}"); GrabbableObject val3 = itemSlots[num3]; if ((Object)(object)val3 != (Object)null && ((object)val3).GetType() == typeof(HauntedMaskItem)) { Plugin.Log.LogMessage((object)"Success! (+1)"); flag2 = true; forward = true; if (j == 1) { flag3 = true; } break; } num3 = ((currentItemSlot - j) % num2 + num2) % num2; Plugin.Log.LogMessage((object)$"Checking slot: {num3}"); val3 = itemSlots[num3]; if ((Object)(object)val3 != (Object)null && ((object)val3).GetType() == typeof(HauntedMaskItem)) { Plugin.Log.LogMessage((object)"Success! (-1)"); flag2 = true; forward = false; if (j == 1) { flag3 = true; } break; } } if (!flag2) { Plugin.Log.LogWarning((object)"No masks were found even though player has held a mask"); return; } if ((Object)(object)val2 != (Object)null && val2.isBeingUsed) { val2.ItemActivate(false, false); } bool currentIsTwoHanded = (Object)(object)val2 != (Object)null && val2.itemProperties.twoHanded; if (flag3) { IngamePlayerSettings.Instance.playerInput.actions.FindAction("SwitchItem", false).Disable(); } if (!((Object)(object)localPlayer.currentlyHeldObject != (Object)null) || !(((object)localPlayer.currentlyHeldObject).GetType() == typeof(HauntedMaskItem))) { ((MonoBehaviour)localPlayer).StartCoroutine(SwitchSlot(forward, currentIsTwoHanded, flag3)); nextTimeToSwitchSlot = Random.Range(minTimeToSwitchSlots, maxTimeToSwitchSlots); minTimeToSwitchSlots -= ((minTimeToSwitchSlots > minSwitchingSlotTime) ? deltaTimeToSwitchSlots : 0f); maxTimeToSwitchSlots -= ((maxTimeToSwitchSlots > minSwitchingSlotTime) ? deltaTimeToSwitchSlots : 0f); Plugin.Log.LogInfo((object)("Next switch in " + nextTimeToSwitchSlot + " seconds")); } } } private static void PossessPlayer(float time) { IngamePlayerSettings.Instance.playerInput.actions.FindAction("SwitchItem", false).Disable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("Interact", false).Disable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("Discard", false).Enable(); if ((Object)(object)localPlayer.currentlyHeldObjectServer != (Object)null && ((object)localPlayer.currentlyHeldObjectServer).GetType() == typeof(HauntedMaskItem)) { IngamePlayerSettings.Instance.playerInput.actions.FindAction("SwitchItem", false).Disable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("ActivateItem", false).Disable(); ShipBuildModeManager.Instance.CancelBuildMode(true); localPlayer.currentlyHeldObjectServer.UseItemOnClient(true); ((Component)localPlayer.currentlyHeldObjectServer).GetComponent<AudioSource>().PlayOneShot(possessionSounds[Random.Range(0, possessionSounds.Length)], localPlayer.itemAudio.volume * 0.75f); ((MonoBehaviour)localPlayer).StartCoroutine(DePossessPlayer(time)); } else { nextTimeToSwitchSlot = 0f; IngamePlayerSettings.Instance.playerInput.actions.FindAction("SwitchItem", false).Enable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("Interact", false).Enable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("Discard", false).Enable(); } } private static IEnumerator DePossessPlayer(float time) { yield return (object)new WaitForSeconds(time); ShipBuildModeManager.Instance.CancelBuildMode(true); if ((Object)(object)localPlayer.currentlyHeldObjectServer != (Object)null) { localPlayer.currentlyHeldObjectServer.UseItemOnClient(false); } yield return (object)new WaitForEndOfFrame(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("ActivateItem", false).Enable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("Interact", false).Enable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("SwitchItem", false).Enable(); IngamePlayerSettings.Instance.playerInput.actions.FindAction("Discard", false).Enable(); } private static IEnumerator SwitchSlot(bool forward, bool currentIsTwoHanded, bool oneAway) { if (currentIsTwoHanded) { if (Plugin.twoHandedItemBehaviour.Value) { GrabbableObject current = localPlayer.currentlyHeldObject; yield return ((MonoBehaviour)localPlayer).StartCoroutine(localPlayer.waitToEndOfFrameToDiscard()); current.EnableItemMeshes(true); yield return (object)new WaitForEndOfFrame(); if (Random.Range(0f, 1f) < 0.25f) { localPlayer.itemAudio.PlayOneShot(slotSwitchSounds[Random.Range(0, slotSwitchSounds.Length)], localPlayer.itemAudio.volume * 0.25f); } localPlayer.SwitchToItemSlot(localPlayer.NextItemSlot(forward), (GrabbableObject)null); localPlayer.SwitchItemSlotsServerRpc(forward); } } else { if (Random.Range(0f, 1f) < 0.25f) { localPlayer.itemAudio.PlayOneShot(slotSwitchSounds[Random.Range(0, slotSwitchSounds.Length)], localPlayer.itemAudio.volume * 0.25f); } yield return (object)new WaitForEndOfFrame(); localPlayer.SwitchToItemSlot(localPlayer.NextItemSlot(forward), (GrabbableObject)null); localPlayer.SwitchItemSlotsServerRpc(forward); } if (oneAway) { yield return (object)new WaitForSeconds(0.5f); IngamePlayerSettings.Instance.playerInput.actions.FindAction("SwitchItem", false).Enable(); } } } [HarmonyPatch(typeof(Terminal))] public class TerminalPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void PatchStart(Terminal __instance) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown string name = "MaskedPlayerEnemy"; SpawnableEnemyWithRarity val = new SpawnableEnemyWithRarity(); val.rarity = 0; SelectableLevel[] moonsCatalogueList = __instance.moonsCatalogueList; for (int i = 0; i < moonsCatalogueList.Length; i++) { foreach (SpawnableEnemyWithRarity enemy in moonsCatalogueList[i].Enemies) { if (((Object)enemy.enemyType).name == name) { val.enemyType = enemy.enemyType; break; } } if ((Object)(object)val.enemyType != (Object)null) { break; } } if ((Object)(object)val.enemyType == (Object)null) { Plugin.Log.LogError((object)"Masked enemy isn't allowed to spawn on any level!"); return; } Plugin.Log.LogMessage((object)("Masked enemy found: " + ((Object)val.enemyType).name + ", fixing AI on all levels...")); moonsCatalogueList = __instance.moonsCatalogueList; foreach (SelectableLevel val2 in moonsCatalogueList) { if (!val2.Enemies.Exists((SpawnableEnemyWithRarity enemy) => ((Object)enemy.enemyType).name == name)) { Plugin.Log.LogMessage((object)("Masked enemy not found on " + val2.PlanetName + ", adding zero...")); val2.Enemies.Add(val); } else { Plugin.Log.LogMessage((object)("Masked enemy found on " + val2.PlanetName + ".")); } } } } }
plugins/ProwlerBracken.dll
Decompiled a year agousing System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using ProwlerBracken.AssetManagement; using ProwlerBracken.Libraries; using ProwlerBracken.Patches; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("ProwlerBracken")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ProwlerBracken")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("2f4ad9e2-101c-4abf-b1ee-8551bf4b9409")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace ProwlerBracken { [BepInPlugin("Danninx.Prowler", "Prowler Bracken", "0.0.1")] public class ProwlerBrackenBase : BaseUnityPlugin { private static ProwlerBrackenBase _instance; private readonly Harmony Harmony = new Harmony("Danninx.Prowler"); internal static ProwlerBrackenBase Instance { get { return _instance; } set { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown if ((Object)_instance == (Object)null) { _instance = value; } else { Object.Destroy((Object)value); } } } private void Awake() { Instance = this; Assets.PopulateAssets(((BaseUnityPlugin)this).Logger); ((BaseUnityPlugin)this).Logger.LogError((object)"You're the best of all of us Miles..."); Harmony.PatchAll(typeof(ProwlerBrackenBase)); Harmony.PatchAll(typeof(BrackenPatch)); } internal static void LogInfo(object message) { ((BaseUnityPlugin)Instance).Logger.LogInfo(message); } internal static void LogWarning(object message) { ((BaseUnityPlugin)Instance).Logger.LogWarning(message); } internal static void LogError(object message) { ((BaseUnityPlugin)Instance).Logger.LogError(message); } } public static class PluginInfo { public const string GUID = "Danninx.Prowler"; public const string NAME = "Prowler Bracken"; public const string VERSION = "0.0.1"; public const string ASSET_BUNDLE_NAME = "prowleraudio"; } } namespace ProwlerBracken.Patches { [HarmonyPatch(typeof(FlowermanAI))] internal class BrackenPatch { [HarmonyPatch("Start")] [HarmonyPostfix] public static void ChangeBrackenSounds(FlowermanAI __instance) { __instance.creatureAngerVoice.clip = Assets.ProwlerChase; __instance.crackNeckAudio.clip = Assets.ProwlerKill; __instance.crackNeckSFX = Assets.ProwlerKill; ((Component)__instance).gameObject.AddComponent<ProwlerBehavior>().Initialize((EnemyAI)(object)__instance); ProwlerBrackenBase.LogInfo("Prowler initiated."); } [HarmonyPatch("Update")] [HarmonyPostfix] public static void DisableRandomPitch(FlowermanAI __instance) { __instance.creatureAngerVoice.pitch = 1f; } } } namespace ProwlerBracken.Libraries { internal class ProwlerBehavior : MonoBehaviour { private AudioSource AmbienceSource; public const float PLAY_INTERVAL_MIN = 15f; public const float PLAY_INTERVAL_MAX = 40f; public const float MAX_AUDIO_DIST = 100f; private float NextAudioTime; private EnemyAI ProwlerAI; public void Initialize(EnemyAI ProwlerAI) { this.ProwlerAI = ProwlerAI; AmbienceSource = ProwlerAI.creatureVoice; SetNextTime(); } private void Update() { if ((double)Time.time > (double)NextAudioTime) { SetNextTime(); AudioClip randomAmbienceSFX = Assets.GetRandomAmbienceSFX(); ProwlerBrackenBase.LogInfo("Played ambience audio " + ((Object)randomAmbienceSFX).name); AmbienceSource.PlayOneShot(randomAmbienceSFX); } } private void SetNextTime() { NextAudioTime = Time.time + Random.Range(15f, 40f); } } } namespace ProwlerBracken.AssetManagement { public static class Assets { public static AssetBundle AssetBundle { get; private set; } public static AudioClip ProwlerKill { get; private set; } public static List<AudioClip> ProwlerAmbienceSFX { get; private set; } public static AudioClip ProwlerChase { get; private set; } private static string GetAssemblyName() { return Assembly.GetExecutingAssembly().FullName.Split(new char[1] { ',' })[0]; } public static void PopulateAssets(ManualLogSource ModLogger) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown if ((Object)AssetBundle != (Object)null) { return; } string name = GetAssemblyName() + ".AssetManagement.prowleraudio"; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) { AssetBundle = AssetBundle.LoadFromStream(stream); } ProwlerKill = AssetBundle.LoadAsset<AudioClip>("Assets/ProwlerKill.mp3"); ProwlerChase = AssetBundle.LoadAsset<AudioClip>("Assets/ProwlerChase.mp3"); ProwlerAmbienceSFX = new List<AudioClip>(); ModLogger.LogInfo((object)"Prowler ambience clips loaded."); string[] allAssetNames = AssetBundle.GetAllAssetNames(); foreach (string text in allAssetNames) { string[] array = text.Split(new char[1] { '/' }); if (array[1] == "ambiencesfx") { AudioClip item = AssetBundle.LoadAsset<AudioClip>(text); ProwlerAmbienceSFX.Add(item); } } } public static AudioClip GetRandomAmbienceSFX() { if (ProwlerAmbienceSFX.Count == 0) { return null; } int index = Random.Range(0, ProwlerAmbienceSFX.Count - 1); return ProwlerAmbienceSFX[index]; } } }
plugins/PushCompany.dll
Decompiled a year agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using PushCompany.Assets.Scripts; using PushCompany.Properties; 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(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("PushCompany")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Push your fellow crewmates with the interaction key! (E by default)")] [assembly: AssemblyFileVersion("1.2.0.0")] [assembly: AssemblyInformationalVersion("1.2.0")] [assembly: AssemblyProduct("PushCompany")] [assembly: AssemblyTitle("PushCompany")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); } } 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 PushCompany { [BepInPlugin("PushCompany", "PushCompany", "1.2.0")] public class PushCompanyBase : BaseUnityPlugin { public static readonly Lazy<PushCompanyBase> Instance = new Lazy<PushCompanyBase>(() => new PushCompanyBase()); public static GameObject pushPrefab; public ManualLogSource mls; private readonly Harmony harmony = new Harmony("PushCompany"); public static ConfigEntry<float> config_PushCooldown; public static ConfigEntry<float> config_PushForce; public static ConfigEntry<float> config_PushRange; public static ConfigEntry<float> config_PushCost; private void Awake() { mls = Logger.CreateLogSource("PushCompany"); ConfigSetup(); LoadBundle(); harmony.PatchAll(typeof(PushCompanyBase)); harmony.PatchAll(typeof(PlayerControllerB_Patches)); harmony.PatchAll(typeof(NetworkHandler)); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array = types; foreach (Type type in array) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array2 = methods; foreach (MethodInfo methodInfo in array2) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } mls.LogInfo((object)"PushCompany has initialized!"); } private void ConfigSetup() { config_PushCooldown = ((BaseUnityPlugin)this).Config.Bind<float>("Push Cooldown", "Value", 0.025f, "How long until the player can push again"); config_PushForce = ((BaseUnityPlugin)this).Config.Bind<float>("Push Force", "Value", 12.5f, "How strong the player pushes."); config_PushRange = ((BaseUnityPlugin)this).Config.Bind<float>("Push Range", "Value", 3f, "The distance the player is able to push."); config_PushCost = ((BaseUnityPlugin)this).Config.Bind<float>("Push Cost", "Value", 0.08f, "The energy cost of each push."); } private void LoadBundle() { AssetBundle val = AssetBundle.LoadFromMemory(Resources.pushcompany); if ((Object)(object)val == (Object)null) { throw new Exception("Failed to load Push Bundle!"); } pushPrefab = val.LoadAsset<GameObject>("Assets/Push.prefab"); if ((Object)(object)pushPrefab == (Object)null) { throw new Exception("Failed to load Push Prefab!"); } pushPrefab.AddComponent<PushComponent>(); } } public static class PluginInfo { public const string PLUGIN_GUID = "PushCompany"; public const string PLUGIN_NAME = "PushCompany"; public const string PLUGIN_VERSION = "1.2.0"; } } namespace PushCompany.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { ResourceManager resourceManager = new ResourceManager("PushCompany.Properties.Resources", typeof(Resources).Assembly); resourceMan = resourceManager; } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] AssetBundles { get { object @object = ResourceManager.GetObject("AssetBundles", resourceCulture); return (byte[])@object; } } internal static byte[] AssetBundles_manifest { get { object @object = ResourceManager.GetObject("AssetBundles.manifest", resourceCulture); return (byte[])@object; } } internal static byte[] AssetBundles1 { get { object @object = ResourceManager.GetObject("AssetBundles1", resourceCulture); return (byte[])@object; } } internal static byte[] AssetBundles2 { get { object @object = ResourceManager.GetObject("AssetBundles2", resourceCulture); return (byte[])@object; } } internal static byte[] pushcompany { get { object @object = ResourceManager.GetObject("pushcompany", resourceCulture); return (byte[])@object; } } internal static byte[] pushcompany_push { get { object @object = ResourceManager.GetObject("pushcompany.push", resourceCulture); return (byte[])@object; } } internal static byte[] pushcompany_push_manifest { get { object @object = ResourceManager.GetObject("pushcompany.push.manifest", resourceCulture); return (byte[])@object; } } internal static byte[] pushcompany_push1 { get { object @object = ResourceManager.GetObject("pushcompany.push1", resourceCulture); return (byte[])@object; } } internal Resources() { } } } namespace PushCompany.Assets.Scripts { [HarmonyPatch] public class NetworkHandler { private static GameObject pushObject; [HarmonyPrefix] [HarmonyPatch(typeof(GameNetworkManager), "Start")] private static void Init() { NetworkManager.Singleton.AddNetworkPrefab(PushCompanyBase.pushPrefab); } [HarmonyPostfix] [HarmonyPatch(typeof(StartOfRound), "Awake")] private static void SpawnNetworkPrefab() { try { if (NetworkManager.Singleton.IsServer) { pushObject = Object.Instantiate<GameObject>(PushCompanyBase.pushPrefab); pushObject.GetComponent<NetworkObject>().Spawn(true); } } catch { PushCompanyBase.Instance.Value.mls.LogError((object)"Failed to instantiate network prefab!"); } } } [HarmonyPatch(typeof(PlayerControllerB))] public static class PlayerControllerB_Patches { private static PushComponent pushComponent; [HarmonyPostfix] [HarmonyPatch(typeof(PlayerControllerB), "Update")] private static void Update(PlayerControllerB __instance) { //IL_0016: 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) if (!((NetworkBehaviour)__instance).IsOwner) { return; } MovementActions movement = __instance.playerActions.Movement; if (((MovementActions)(ref movement)).Interact.WasPressedThisFrame()) { if ((Object)(object)pushComponent == (Object)null) { pushComponent = Object.FindObjectOfType<PushComponent>(); } if ((Object)(object)pushComponent != (Object)null) { pushComponent.PushServerRpc(((NetworkBehaviour)__instance).NetworkObjectId); } } } } public class PushComponent : NetworkBehaviour { private Dictionary<ulong, float> lastPushTimes = new Dictionary<ulong, float>(); private NetworkVariable<float> PushCooldown = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private NetworkVariable<float> PushRange = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private NetworkVariable<float> PushForce = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private NetworkVariable<float> PushCost = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public override void OnNetworkSpawn() { if (((NetworkBehaviour)this).IsServer) { PushCooldown.Value = PushCompanyBase.config_PushCooldown.Value; PushRange.Value = PushCompanyBase.config_PushRange.Value; PushForce.Value = PushCompanyBase.config_PushForce.Value; PushCost.Value = PushCompanyBase.config_PushCost.Value; } } [ServerRpc(RequireOwnership = false)] public void PushServerRpc(ulong playerId) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2433198804u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2433198804u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } if (lastPushTimes.TryGetValue(playerId, out var value)) { if (Time.time - value < PushCooldown.Value) { return; } } else { lastPushTimes.Add(playerId, 0f); } GameObject playerById = GetPlayerById(playerId); PlayerControllerB component = playerById.GetComponent<PlayerControllerB>(); Camera gameplayCamera = component.gameplayCamera; if (!CanPushPlayer(component)) { return; } int num = 1 << playerById.layer; Vector3 forward = ((Component)gameplayCamera).transform.forward; Vector3 normalized = ((Vector3)(ref forward)).normalized; RaycastHit[] array = Physics.RaycastAll(((Component)gameplayCamera).transform.position, normalized, PushRange.Value, num); RaycastHit[] array2 = array; for (int i = 0; i < array2.Length; i++) { RaycastHit val3 = array2[i]; if ((Object)(object)((Component)((RaycastHit)(ref val3)).transform).gameObject != (Object)(object)playerById) { PlayerControllerB component2 = ((Component)((RaycastHit)(ref val3)).transform).GetComponent<PlayerControllerB>(); if (!component2.inSpecialInteractAnimation) { PushClientRpc(((NetworkBehaviour)component).NetworkObjectId, ((NetworkBehaviour)component2).NetworkObjectId, normalized * PushForce.Value * Time.fixedDeltaTime); lastPushTimes[playerId] = Time.time; } break; } } } [ClientRpc] private void PushClientRpc(ulong pusherId, ulong playerId, Vector3 push) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_007e: 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_00f9: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3498116674u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, pusherId); BytePacker.WriteValueBitPacked(val2, playerId); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref push); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3498116674u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { GameObject playerById = GetPlayerById(playerId); PlayerControllerB component = playerById.GetComponent<PlayerControllerB>(); ((MonoBehaviour)this).StartCoroutine(SmoothMove(component.thisController, push)); component.movementAudio.PlayOneShot(StartOfRound.Instance.playerJumpSFX); GameObject playerById2 = GetPlayerById(pusherId); PlayerControllerB component2 = playerById2.GetComponent<PlayerControllerB>(); component2.sprintMeter = Mathf.Clamp(component2.sprintMeter - PushCost.Value, 0f, 1f); } } } public IEnumerator SmoothMove(CharacterController controller, Vector3 push) { //IL_0015: 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) float force = PushForce.Value / 12.5f; float smoothTime = ((Vector3)(ref push)).magnitude / force; Vector3 targetPosition = ((Component)controller).transform.position + push; Vector3 val = targetPosition - ((Component)controller).transform.position; Vector3 direction = ((Vector3)(ref val)).normalized; float distance = Vector3.Distance(((Component)controller).transform.position, targetPosition); for (float currentTime = 0f; currentTime < smoothTime; currentTime += Time.fixedDeltaTime) { float currentDistance = distance * Mathf.Min(currentTime, smoothTime) / smoothTime; controller.Move(direction * currentDistance); yield return null; } } private bool CanPushPlayer(PlayerControllerB player) { return !player.quickMenuManager.isMenuOpen && !player.inSpecialInteractAnimation && !player.isTypingChat && !player.isExhausted; } private static GameObject GetPlayerById(ulong playerId) { if (NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(playerId, out var value)) { return ((Component)value).gameObject; } return null; } protected override void __initializeVariables() { if (PushCooldown == null) { throw new Exception("PushComponent.PushCooldown cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)PushCooldown).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushCooldown, "PushCooldown"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushCooldown); if (PushRange == null) { throw new Exception("PushComponent.PushRange cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)PushRange).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushRange, "PushRange"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushRange); if (PushForce == null) { throw new Exception("PushComponent.PushForce cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)PushForce).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushForce, "PushForce"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushForce); if (PushCost == null) { throw new Exception("PushComponent.PushCost cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)PushCost).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushCost, "PushCost"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushCost); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_PushComponent() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(2433198804u, new RpcReceiveHandler(__rpc_handler_2433198804)); NetworkManager.__rpc_func_table.Add(3498116674u, new RpcReceiveHandler(__rpc_handler_3498116674)); } private static void __rpc_handler_2433198804(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ulong playerId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); target.__rpc_exec_stage = (__RpcExecStage)1; ((PushComponent)(object)target).PushServerRpc(playerId); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3498116674(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0050: 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_0072: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ulong pusherId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref pusherId); ulong playerId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); Vector3 push = default(Vector3); ((FastBufferReader)(ref reader)).ReadValueSafe(ref push); target.__rpc_exec_stage = (__RpcExecStage)2; ((PushComponent)(object)target).PushClientRpc(pusherId, playerId, push); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "PushComponent"; } } }
plugins/ReservedFlashlightSlot.dll
Decompiled a year agousing System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using ReservedFlashlightSlot.Patches; using ReservedItemSlotCore; using ReservedItemSlotCore.Networking; using ReservedItemSlotCore.Patches; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("ReservedFlashlightSlot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReservedFlashlightSlot")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("5b7d6563-4e51-4a69-bcf9-fa1dea6eff75")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace ReservedFlashlightSlot { public static class ConfigSettings { public static ConfigEntry<string> activateFlashlightKey; public static ConfigEntry<bool> hideFlashlightMeshShoulder; public static string activateFlashlightDisplayName; public static Dictionary<string, ConfigEntryBase> currentConfigEntries = new Dictionary<string, ConfigEntryBase>(); public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); activateFlashlightKey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedFlashlightSlot", "ActivateFlashlightKey", "<Keyboard>/f", "This setting will be ignored if InputUtils is installed and enabled. (I recommend running InputUtils to edit keybinds in the in-game settings)"); hideFlashlightMeshShoulder = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedFlashlightSlot", "HideFlashlightOnShoulder", false, "Hides the flashlight mesh while on your shoulder. Only applies in scenarios where you can view your player in third person."); activateFlashlightDisplayName = GetDisplayName(activateFlashlightKey.Value); currentConfigEntries.Add(((ConfigEntryBase)activateFlashlightKey).Definition.Key, (ConfigEntryBase)(object)activateFlashlightKey); currentConfigEntries.Add(((ConfigEntryBase)hideFlashlightMeshShoulder).Definition.Key, (ConfigEntryBase)(object)hideFlashlightMeshShoulder); TryRemoveOldConfigSettings(); } public static string GetDisplayName(string key) { key = key.Replace("<Keyboard>/", ""); key = key.Replace("<Mouse>/", ""); string text = key; text = text.Replace("leftAlt", "Alt"); text = text.Replace("rightAlt", "Alt"); text = text.Replace("leftCtrl", "Ctrl"); text = text.Replace("rightCtrl", "Ctrl"); text = text.Replace("leftShift", "Shift"); text = text.Replace("rightShift", "Shift"); text = text.Replace("leftButton", "LMB"); text = text.Replace("rightButton", "RMB"); return text.Replace("middleButton", "MMB"); } public static void TryRemoveOldConfigSettings() { HashSet<string> hashSet = new HashSet<string>(); HashSet<string> hashSet2 = new HashSet<string>(); foreach (ConfigEntryBase value in currentConfigEntries.Values) { hashSet.Add(value.Definition.Section); hashSet2.Add(value.Definition.Key); } try { Plugin.Log("Cleaning old config entries"); ConfigFile config = ((BaseUnityPlugin)Plugin.instance).Config; string configFilePath = config.ConfigFilePath; if (!File.Exists(configFilePath)) { return; } string text = File.ReadAllText(configFilePath); string[] array = File.ReadAllLines(configFilePath); string text2 = ""; for (int i = 0; i < array.Length; i++) { array[i] = array[i].Replace("\n", ""); if (array[i].Length <= 0) { continue; } if (array[i].StartsWith("[")) { if (text2 != "" && !hashSet.Contains(text2)) { text2 = "[" + text2 + "]"; int num = text.IndexOf(text2); int num2 = text.IndexOf(array[i]); text = text.Remove(num, num2 - num); } text2 = array[i].Replace("[", "").Replace("]", "").Trim(); } else { if (!(text2 != "")) { continue; } if (i <= array.Length - 4 && array[i].StartsWith("##")) { int j; for (j = 1; i + j < array.Length && array[i + j].Length > 3; j++) { } if (hashSet.Contains(text2)) { int num3 = array[i + j - 1].IndexOf("="); string item = array[i + j - 1].Substring(0, num3 - 1); if (!hashSet2.Contains(item)) { int num4 = text.IndexOf(array[i]); int num5 = text.IndexOf(array[i + j - 1]) + array[i + j - 1].Length; text = text.Remove(num4, num5 - num4); } } i += j - 1; } else if (array[i].Length > 3) { text = text.Replace(array[i], ""); } } } if (!hashSet.Contains(text2)) { text2 = "[" + text2 + "]"; int num6 = text.IndexOf(text2); text = text.Remove(num6, text.Length - num6); } while (text.Contains("\n\n\n")) { text = text.Replace("\n\n\n", "\n\n"); } File.WriteAllText(configFilePath, text); config.Reload(); } catch { } } } [BepInPlugin("FlipMods.ReservedFlashlightSlot", "ReservedFlashlightSlot", "1.5.8")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class Plugin : BaseUnityPlugin { public static Plugin instance; private Harmony _harmony; public static ReservedItemInfo proFlashlightInfo = new ReservedItemInfo("Pro-flashlight", 120, true, true, true, true); public static ReservedItemInfo flashlightInfo = new ReservedItemInfo("Flashlight", 120, true, true, true, true); public static ReservedItemInfo laserPointerInfo = new ReservedItemInfo("Laser pointer", 120, true, true, true, true); private void Awake() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown instance = this; ConfigSettings.BindConfigSettings(); _harmony = new Harmony("ReservedFlashlightSlot"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"ReservedFlashlightSlot loaded"); } public static bool IsModLoaded(string guid) { return Chainloader.PluginInfos.ContainsKey(guid); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.ReservedFlashlightSlot"; public const string PLUGIN_NAME = "ReservedFlashlightSlot"; public const string PLUGIN_VERSION = "1.5.8"; } } namespace ReservedFlashlightSlot.Patches { [HarmonyPatch] internal static class Patcher { private static Vector3 playerShoulderPositionOffset = new Vector3(0.2f, 0.25f, 0f); private static Vector3 playerShoulderRotationOffset = new Vector3(90f, 0f, 0f); private static string originalControlTooltip = ""; public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController; public static PlayerControllerB GetPreviousPlayerHeldBy(FlashlightItem flashlightItem) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown return (PlayerControllerB)Traverse.Create((object)flashlightItem).Field("previousPlayerHeldBy").GetValue(); } public static FlashlightItem GetMainFlashlight(PlayerControllerB playerController) { return GetCurrentlySelectedFlashlight(playerController) ?? GetReservedFlashlight(playerController); } public static FlashlightItem GetReservedFlashlight(PlayerControllerB playerController) { return (FlashlightItem)(SyncManager.syncReservedItemsList.Contains(Plugin.flashlightInfo) ? /*isinst with value type is only supported in some contexts*/: null); } public static FlashlightItem GetCurrentlySelectedFlashlight(PlayerControllerB playerController) { return (FlashlightItem)((playerController.currentItemSlot >= 0 && playerController.currentItemSlot < playerController.ItemSlots.Length) ? /*isinst with value type is only supported in some contexts*/: null); } public static bool IsFlashlightOn(PlayerControllerB playerController) { return ((GrabbableObject)(GetMainFlashlight(playerController)?)).isBeingUsed ?? false; } [HarmonyPatch(typeof(FlashlightItem), "SwitchFlashlight")] [HarmonyPostfix] public static void OnSwitchOnOffFlashlight(bool on, FlashlightItem __instance) { if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null)) { UpdateAllFlashlightStates(((GrabbableObject)__instance).playerHeldBy, on); } } [HarmonyPatch(typeof(FlashlightItem), "PocketItem")] [HarmonyPostfix] public static void OnPocketFlashlightLocal(FlashlightItem __instance) { OnPocketFlashlight(__instance, ((GrabbableObject)__instance).isBeingUsed); } [HarmonyPatch(typeof(FlashlightItem), "PocketFlashlightClientRpc")] [HarmonyPrefix] public static void OnPocketFlashlightClientRpc(bool stillUsingFlashlight, FlashlightItem __instance) { if (NetworkHelper.IsValidClientRpcExecStage((NetworkBehaviour)(object)__instance) && !((NetworkBehaviour)__instance).IsOwner && !((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null) && !((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController)) { OnPocketFlashlight(__instance, stillUsingFlashlight); } } private static void OnPocketFlashlight(FlashlightItem flashlightItem, bool stillUsingFlashlight = false) { if ((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null) { return; } FlashlightItem currentlySelectedFlashlight = GetCurrentlySelectedFlashlight(((GrabbableObject)flashlightItem).playerHeldBy); FlashlightItem reservedFlashlight = GetReservedFlashlight(((GrabbableObject)flashlightItem).playerHeldBy); bool flag = stillUsingFlashlight || ((Object)(object)currentlySelectedFlashlight != (Object)null && ((GrabbableObject)currentlySelectedFlashlight).isBeingUsed); if ((Object)(object)currentlySelectedFlashlight != (Object)null && ((GrabbableObject)currentlySelectedFlashlight).isBeingUsed) { ((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = null; } else if (((GrabbableObject)flashlightItem).isBeingUsed) { ((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)flashlightItem; } else if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight == (Object)null || !((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight.isBeingUsed)) { ((GrabbableObject)flashlightItem).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight; } Renderer[] componentsInChildren = ((Component)flashlightItem).GetComponentsInChildren<Renderer>(); foreach (Renderer val in componentsInChildren) { if (((Object)val).name != "ScanNode" && ((Object)val).name != "ScanNode") { ((Component)val).gameObject.layer = (((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)(object)localPlayerController) ? 23 : 6); } } if ((Object)(object)flashlightItem == (Object)(object)reservedFlashlight) { ((GrabbableObject)flashlightItem).parentObject = ((GrabbableObject)flashlightItem).playerHeldBy.playerGlobalHead.parent; } } [HarmonyPatch(typeof(FlashlightItem), "EquipItem")] [HarmonyPostfix] public static void OnEquipFlashlight(FlashlightItem __instance) { if ((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null) { return; } bool mainFlashlightActive = ((Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight != (Object)null && ((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight.isBeingUsed) || ((GrabbableObject)__instance).isBeingUsed; FlashlightItem reservedFlashlight = GetReservedFlashlight(((GrabbableObject)__instance).playerHeldBy); if (((GrabbableObject)__instance).isBeingUsed || (Object)(object)__instance == (Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight) { ((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = null; } else if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight == (Object)null || !((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight.isBeingUsed)) { ((GrabbableObject)__instance).playerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight; } Renderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<Renderer>(); foreach (Renderer val in componentsInChildren) { if (((Object)val).name != "ScanNode") { ((Component)val).gameObject.layer = 6; } } ((GrabbableObject)__instance).parentObject = (((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) ? ((GrabbableObject)__instance).playerHeldBy.localItemHolder : ((GrabbableObject)__instance).playerHeldBy.serverItemHolder); UpdateAllFlashlightStates(((GrabbableObject)__instance).playerHeldBy, mainFlashlightActive); } [HarmonyPatch(typeof(FlashlightItem), "DiscardItem")] [HarmonyPrefix] public static void ResetPocketedFlashlight(FlashlightItem __instance) { PlayerControllerB previousPlayerHeldBy = GetPreviousPlayerHeldBy(__instance); if ((Object)(object)previousPlayerHeldBy == (Object)null) { return; } FlashlightItem reservedFlashlight = GetReservedFlashlight(previousPlayerHeldBy); if ((Object)(object)reservedFlashlight != (Object)null && ((Object)(object)__instance == (Object)(object)previousPlayerHeldBy.pocketedFlashlight || (Object)(object)previousPlayerHeldBy.pocketedFlashlight == (Object)null)) { previousPlayerHeldBy.pocketedFlashlight = (GrabbableObject)(object)reservedFlashlight; } MeshRenderer[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<MeshRenderer>(); foreach (MeshRenderer val in componentsInChildren) { if (((Object)val).name != "ScanNode") { ((Component)val).gameObject.layer = 6; } } } [HarmonyPatch(typeof(GrabbableObject), "LateUpdate")] [HarmonyPostfix] public static void SetPositionOffset(GrabbableObject __instance) { //IL_0076: 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_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) if (__instance is FlashlightItem && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance.parentObject != (Object)null && __instance.isPocketed && (Object)(object)__instance == (Object)(object)GetReservedFlashlight(__instance.playerHeldBy) && (Object)(object)__instance != (Object)(object)GetCurrentlySelectedFlashlight(__instance.playerHeldBy)) { Transform transform = ((Component)__instance.parentObject).transform; ((Component)__instance).transform.rotation = ((Component)__instance.parentObject).transform.rotation * Quaternion.Euler(playerShoulderRotationOffset); ((Component)__instance).transform.position = transform.position + transform.rotation * playerShoulderPositionOffset; } } [HarmonyPatch(typeof(GrabbableObject), "EnableItemMeshes")] [HarmonyPrefix] public static void OnEnableItemMeshes(ref bool enable, GrabbableObject __instance) { if (__instance is FlashlightItem && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance == (Object)(object)GetReservedFlashlight(__instance.playerHeldBy) && !ConfigSettings.hideFlashlightMeshShoulder.Value) { enable = true; } } private static void UpdateAllFlashlightStates(PlayerControllerB playerController, bool mainFlashlightActive = true) { FlashlightItem mainFlashlight = GetMainFlashlight(playerController); if ((Object)(object)mainFlashlight == (Object)null) { ((Behaviour)playerController.helmetLight).enabled = false; mainFlashlightActive = false; } else { playerController.ChangeHelmetLight(mainFlashlight.flashlightTypeID, mainFlashlightActive && (Object)(object)playerController == (Object)(object)localPlayerController && (Object)(object)playerController.ItemSlots[playerController.currentItemSlot] != (Object)(object)mainFlashlight); } for (int i = 0; i < playerController.ItemSlots.Length; i++) { GrabbableObject obj = playerController.ItemSlots[i]; FlashlightItem val = (FlashlightItem)(object)((obj is FlashlightItem) ? obj : null); if ((Object)(object)val != (Object)null) { UpdateFlashlightState(val, (Object)(object)val == (Object)(object)mainFlashlight && mainFlashlightActive); } } } private static void UpdateFlashlightState(FlashlightItem flashlightItem, bool active) { if (!((Object)(object)((GrabbableObject)flashlightItem).playerHeldBy == (Object)null)) { PlayerControllerB playerHeldBy = ((GrabbableObject)flashlightItem).playerHeldBy; ((GrabbableObject)flashlightItem).isBeingUsed = active; bool flag = (Object)(object)playerHeldBy != (Object)(object)localPlayerController || (Object)(object)playerHeldBy.ItemSlots[playerHeldBy.currentItemSlot] == (Object)(object)flashlightItem; ((Behaviour)flashlightItem.flashlightBulb).enabled = active && flag; ((Behaviour)flashlightItem.flashlightBulbGlow).enabled = active && flag; flashlightItem.usingPlayerHelmetLight = active && !flag; } } } } namespace ReservedFlashlightSlot.Input { internal class IngameKeybinds : LcInputActions { internal static IngameKeybinds Instance = new IngameKeybinds(); [InputAction("<Keyboard>/f", Name = "[ReservedItemSlots]\nToggle flashlight")] public InputAction ToggleFlashlightHotkey { get; set; } internal static InputActionAsset GetAsset() { return ((LcInputActions)Instance).Asset; } } internal class InputUtilsCompat { internal static InputActionAsset Asset => IngameKeybinds.GetAsset(); internal static bool Enabled => Plugin.IsModLoaded("com.rune580.LethalCompanyInputUtils"); public static InputAction ToggleFlashlightHotkey => IngameKeybinds.Instance.ToggleFlashlightHotkey; } [HarmonyPatch] internal static class Keybinds { public static InputActionAsset Asset; public static InputActionMap ActionMap; private static InputAction ActivateFlashlightAction; public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController; [HarmonyPatch(typeof(PreInitSceneScript), "Awake")] [HarmonyPrefix] public static void AddToKeybindMenu() { InitKeybinds(); } public static void InitKeybinds() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: 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) Plugin.Log("Initializing hotkeys."); if (InputUtilsCompat.Enabled) { Asset = InputUtilsCompat.Asset; ActionMap = Asset.actionMaps[0]; ActivateFlashlightAction = InputUtilsCompat.ToggleFlashlightHotkey; } else { Asset = new InputActionAsset(); ActionMap = new InputActionMap("ReservedItemSlots"); InputActionSetupExtensions.AddActionMap(Asset, ActionMap); ActivateFlashlightAction = InputActionSetupExtensions.AddAction(ActionMap, "ReservedItemSlots.ToggleFlashlight", (InputActionType)0, ConfigSettings.activateFlashlightKey.Value, (string)null, (string)null, (string)null, (string)null); } } [HarmonyPatch(typeof(StartOfRound), "OnEnable")] [HarmonyPostfix] public static void OnEnable() { Asset.Enable(); ActivateFlashlightAction.performed += OnActivateFlashlightPerformed; } [HarmonyPatch(typeof(StartOfRound), "OnDisable")] [HarmonyPostfix] public static void OnDisable() { Asset.Disable(); ActivateFlashlightAction.performed -= OnActivateFlashlightPerformed; } private static void OnActivateFlashlightPerformed(CallbackContext context) { if ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerControlled || localPlayerController.inTerminalMenu || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject)) { return; } FlashlightItem mainFlashlight = Patcher.GetMainFlashlight(localPlayerController); if (((CallbackContext)(ref context)).performed && !((Object)(object)mainFlashlight == (Object)null)) { float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue(); if (!(num < 0.075f)) { ((GrabbableObject)mainFlashlight).UseItemOnClient(!((GrabbableObject)mainFlashlight).isBeingUsed); Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0); } } } } }
plugins/ReservedItemSlotCore.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using ReservedItemSlotCore.Config; using ReservedItemSlotCore.Input; using ReservedItemSlotCore.Networking; using ReservedItemSlotCore.Patches; using TMPro; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; 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: AssemblyTitle("ReservedItemSlotCore")] [assembly: AssemblyDescription("Mod made by flipf17")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReservedItemSlotCore")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("238ce080-e339-46b6-9b08-992a950453a1")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("ReservedFlashlightSlot")] [assembly: InternalsVisibleTo("ReservedWalkieSlot")] [assembly: InternalsVisibleTo("ReservedWeaponSlot")] [assembly: InternalsVisibleTo("ReservedUtilitySlot")] [assembly: InternalsVisibleTo("ReservedSprayPaintSlot")] [assembly: InternalsVisibleTo("ReservedBoomboxSlot")] [assembly: InternalsVisibleTo("ReservedPersonalBoomboxSlot")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace ReservedItemSlotCore { internal class ReservedPlayerData { public PlayerControllerB playerController; public ReservedItemInfo grabbingReservedItem = null; public int previousHotbarIndex = -1; public bool inReservedHotbarSlots = false; public int hotbarSize = 4; public int reservedHotbarStartIndex = 4; public bool isLocalPlayer => (Object)(object)StartOfRound.Instance?.localPlayerController != (Object)null && (Object)(object)playerController == (Object)(object)StartOfRound.Instance.localPlayerController; public int currentItemSlot => playerController.currentItemSlot; public bool currentItemSlotIsReserved => currentItemSlot >= reservedHotbarStartIndex && currentItemSlot < reservedHotbarStartIndex + SyncManager.numReservedItemSlots; public GrabbableObject previouslyHeldItem => (previousHotbarIndex >= 0 && previousHotbarIndex < playerController.ItemSlots.Length) ? playerController.ItemSlots[previousHotbarIndex] : null; public bool IsReservedItemSlot(int index) { return index >= reservedHotbarStartIndex && index < reservedHotbarStartIndex + SyncManager.numReservedItemSlots; } public int GetNumHeldReservedItems(bool safe = false) { int num = 0; if (!safe) { for (int i = reservedHotbarStartIndex; i < reservedHotbarStartIndex + SyncManager.numReservedItemSlots; i++) { num += (((Object)(object)playerController.ItemSlots[i] != (Object)null) ? 1 : 0); } } else { for (int j = 0; j < playerController.ItemSlots.Length; j++) { GrabbableObject val = playerController.ItemSlots[j]; num += (((Object)(object)val != (Object)null && SyncManager.IsReservedItem(val.itemProperties.itemName)) ? 1 : 0); } } return num; } public string DumpData() { string text = "[ReservedPlayerData Dump]\nPlayer: " + ((Object)playerController).name + (isLocalPlayer ? " [LocalPlayer]" : "") + "\nCurrentItemSlot: " + currentItemSlot + "\nRegisteredHotbarSize: " + hotbarSize + "\nActualHotbarSize: " + playerController.ItemSlots.Length + "\nCurrentlyGrabbingReservedItem: " + ((grabbingReservedItem != null) ? grabbingReservedItem.itemName : "false") + "\nReservedHotbarStartIndex: " + reservedHotbarStartIndex + "\n" + (isLocalPlayer ? ("NumItemSlotsHUD: " + HUDManager.Instance.itemSlotIconFrames.Length + "\n") : "") + "ItemsInInventory: ["; for (int i = 0; i < playerController.ItemSlots.Length; i++) { if (i > 0) { text += ", "; } text += (("[" + i + "] " + (object)playerController.ItemSlots[i] != null) ? ((Object)playerController.ItemSlots[i]).name : "Empty"); } return text + "]\nNumHeldReservedItems: " + GetNumHeldReservedItems(safe: true); } } [BepInPlugin("FlipMods.ReservedItemSlotCore", "ReservedItemSlotCore", "1.8.6")] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class Plugin : BaseUnityPlugin { private Harmony _harmony; public static Plugin instance; private static ManualLogSource logger; public static Dictionary<string, ReservedItemInfo> reservedItemsDictDefault => ReservedItemInfo.reservedItemsDictDefault; public static List<ReservedItemInfo> reservedItemsListDefault => ReservedItemInfo.reservedItemsListDefault; public static List<ReservedItemInfo> reservedItemSlotRepsDefault => ReservedItemInfo.reservedItemSlotRepsDefault; public static int numReservedItemSlotsDefault => ReservedItemInfo.numReservedItemSlotsDefault; private void Awake() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown instance = this; CreateCustomLogger(); ConfigSettings.BindConfigSettings(); _harmony = new Harmony("ReservedItemSlotCore"); _harmony.PatchAll(); Log("ReservedItemSlotCore loaded"); } private void CreateCustomLogger() { try { logger = Logger.CreateLogSource($"{((BaseUnityPlugin)this).Info.Metadata.Name}-{((BaseUnityPlugin)this).Info.Metadata.Version}"); } catch { logger = ((BaseUnityPlugin)this).Logger; } } public static void Log(string message) { logger.LogInfo((object)message); } public static void LogError(string message) { logger.LogError((object)message); } public static void LogWarning(string message) { logger.LogWarning((object)message); } public static bool IsModLoaded(string guid) { return Chainloader.PluginInfos.ContainsKey(guid); } public static bool IsReservedItemDefault(string itemName) { return reservedItemsDictDefault.ContainsKey(itemName); } public static ReservedItemInfo GetReservedItemInfoDefault(string itemName) { return IsReservedItemDefault(itemName) ? reservedItemsDictDefault[itemName] : null; } public static ReservedItemInfo GetReservedItemInfoDefault(GrabbableObject item) { return ((Object)(object)item != (Object)null) ? GetReservedItemInfoDefault(item.itemProperties.itemName) : null; } public static int GetReservedItemHotbarIndex(string itemName) { return IsReservedItemDefault(itemName) ? reservedItemsDictDefault[itemName].indexInInventory : (-1); } } internal class ReservedItemInfo { public static Dictionary<string, ReservedItemInfo> reservedItemsDictDefault = new Dictionary<string, ReservedItemInfo>(); public static List<ReservedItemInfo> reservedItemsListDefault = new List<ReservedItemInfo>(); public static List<ReservedItemInfo> reservedItemSlotRepsDefault = new List<ReservedItemInfo>(); public static Dictionary<string, ReservedItemInfo> reservedItemsDict = new Dictionary<string, ReservedItemInfo>(); public static List<ReservedItemInfo> reservedItemsList = new List<ReservedItemInfo>(); public static List<ReservedItemInfo> reservedItemSlotReps = new List<ReservedItemInfo>(); public string itemName = ""; public HashSet<string> acceptedItemNames; public int hotbarSlotPriority = 0; public int reservedItemIndex = 0; public bool forceUpdateCanBeGrabbedBeforeGameStart = false; public bool canBeGrabbedBeforeGameStart = false; public bool forceUpdateRequiresBattery = false; public bool requiresBattery = false; public static int numReservedItemSlotsDefault => reservedItemSlotRepsDefault.Count; public int indexInInventory => ((Object)(object)PlayerPatcher.localPlayerController != (Object)null) ? (PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedItemIndex) : (-1); public ReservedItemInfo() { } public ReservedItemInfo(string itemName, int hotbarSlotPriority, bool forceUpdateCanBeGrabbedBeforeGameStart = false, bool canBeGrabbedBeforeGameStart = false, bool forceUpdateRequiresBattery = false, bool requiresBattery = false) { this.itemName = itemName; this.hotbarSlotPriority = hotbarSlotPriority; AddItemInfoToList(this); ReservedItemInfo info = new ReservedItemInfo(this); AddItemInfoToList(info, reservedItemsListDefault, reservedItemsDictDefault, reservedItemSlotRepsDefault); } public static void AddItemInfoToList(ReservedItemInfo info, List<ReservedItemInfo> _reservedItemsList = null, Dictionary<string, ReservedItemInfo> _reservedItemsDict = null, List<ReservedItemInfo> _reservedItemSlotReps = null) { if (_reservedItemsList == null) { _reservedItemsList = reservedItemsList; } if (_reservedItemsDict == null) { _reservedItemsDict = reservedItemsDict; } if (_reservedItemSlotReps == null) { _reservedItemSlotReps = reservedItemSlotReps; } if (!_reservedItemsDict.ContainsKey(info.itemName)) { _reservedItemsDict.Add(info.itemName, info); _reservedItemsList.Add(info); int i; for (i = 0; i < _reservedItemSlotReps.Count; i++) { ReservedItemInfo reservedItemInfo = _reservedItemSlotReps[i]; if (info.hotbarSlotPriority >= reservedItemInfo.hotbarSlotPriority) { break; } } info.reservedItemIndex = i; if (i == _reservedItemSlotReps.Count || info.hotbarSlotPriority != _reservedItemSlotReps[i].hotbarSlotPriority) { info.acceptedItemNames = new HashSet<string> { info.itemName }; _reservedItemSlotReps.Insert(i, info); { foreach (ReservedItemInfo _reservedItems in _reservedItemsList) { if (info != _reservedItems && _reservedItems.reservedItemIndex >= i) { _reservedItems.reservedItemIndex++; } } return; } } info.acceptedItemNames = _reservedItemSlotReps[i].acceptedItemNames; info.acceptedItemNames.Add(info.itemName); } else { Plugin.Log($"Tried to add duplicate item name to the ReservedItems list: {info.itemName}. Sorting instead"); } } public ReservedItemInfo(ReservedItemInfo copyFrom) { itemName = copyFrom.itemName; hotbarSlotPriority = copyFrom.hotbarSlotPriority; reservedItemIndex = copyFrom.reservedItemIndex; forceUpdateCanBeGrabbedBeforeGameStart = copyFrom.forceUpdateCanBeGrabbedBeforeGameStart; canBeGrabbedBeforeGameStart = copyFrom.canBeGrabbedBeforeGameStart; forceUpdateRequiresBattery = copyFrom.forceUpdateRequiresBattery; requiresBattery = copyFrom.requiresBattery; } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.ReservedItemSlotCore"; public const string PLUGIN_NAME = "ReservedItemSlotCore"; public const string PLUGIN_VERSION = "1.8.6"; } } namespace ReservedItemSlotCore.Config { public static class ConfigSettings { public static ConfigEntry<string> focusReservedHotbarHotkey; public static ConfigEntry<bool> toggleFocusReservedHotbar; public static ConfigEntry<bool> preventReservedItemSlotFade; public static Dictionary<string, ConfigEntryBase> currentConfigEntries = new Dictionary<string, ConfigEntryBase>(); public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); focusReservedHotbarHotkey = AddConfigEntry<string>(((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedItemSlotCore", "FocusReservedItemSlotsHotkey", "<Keyboard>/leftAlt", "This setting will be ignored if InputUtils is installed and enabled. (I recommend running InputUtils to edit keybinds in the in-game settings)")); toggleFocusReservedHotbar = AddConfigEntry<bool>(((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedItemSlotCore", "ToggleFocusReservedHotbar", false, "If set to true, swapping to the reserved hotbar slots will be toggled when pressing the hotkey rather than while holding the hotkey. Setting this option to true may have bugs at this current time.")); preventReservedItemSlotFade = AddConfigEntry<bool>(((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedItemSlotCore", "PreventReservedHotbarSlotFade", false, "If true, the reserved hotbar slots will not fade with the rest of the default slots.")); TryRemoveOldConfigSettings(); } public static ConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { currentConfigEntries.Add(((ConfigEntryBase)configEntry).Definition.Key, (ConfigEntryBase)(object)configEntry); return configEntry; } public static string GetDisplayName(string key) { try { if (key.Length <= 1) { return key; } int num = key.IndexOf(">/"); if (num >= 0) { key = key.Substring(num + 2); } string text = key; text = text.Replace("leftAlt", "Alt"); text = text.Replace("rightAlt", "Alt"); text = text.Replace("leftCtrl", "Ctrl"); text = text.Replace("rightCtrl", "Ctrl"); text = text.Replace("leftShift", "Shift"); text = text.Replace("rightShift", "Shift"); text = text.Replace("leftButton", "LMB"); text = text.Replace("rightButton", "RMB"); text = text.Replace("middleButton", "MMB"); try { text = char.ToUpper(text[0]) + text.Substring(1); } catch { } return text; } catch { return ""; } } public static void TryRemoveOldConfigSettings() { HashSet<string> hashSet = new HashSet<string>(); HashSet<string> hashSet2 = new HashSet<string>(); foreach (ConfigEntryBase value in currentConfigEntries.Values) { hashSet.Add(value.Definition.Section); hashSet2.Add(value.Definition.Key); } try { Plugin.Log("Cleaning old config entries"); ConfigFile config = ((BaseUnityPlugin)Plugin.instance).Config; string configFilePath = config.ConfigFilePath; if (!File.Exists(configFilePath)) { return; } string text = File.ReadAllText(configFilePath); string[] array = File.ReadAllLines(configFilePath); string text2 = ""; for (int i = 0; i < array.Length; i++) { array[i] = array[i].Replace("\n", ""); if (array[i].Length <= 0) { continue; } if (array[i].StartsWith("[")) { if (text2 != "" && !hashSet.Contains(text2)) { text2 = "[" + text2 + "]"; int num = text.IndexOf(text2); int num2 = text.IndexOf(array[i]); text = text.Remove(num, num2 - num); } text2 = array[i].Replace("[", "").Replace("]", "").Trim(); } else { if (!(text2 != "")) { continue; } if (i <= array.Length - 4 && array[i].StartsWith("##")) { int j; for (j = 1; i + j < array.Length && array[i + j].Length > 3; j++) { } if (hashSet.Contains(text2)) { int num3 = array[i + j - 1].IndexOf("="); string item = array[i + j - 1].Substring(0, num3 - 1); if (!hashSet2.Contains(item)) { int num4 = text.IndexOf(array[i]); int num5 = text.IndexOf(array[i + j - 1]) + array[i + j - 1].Length; text = text.Remove(num4, num5 - num4); } } i += j - 1; } else if (array[i].Length > 3) { text = text.Replace(array[i], ""); } } } if (!hashSet.Contains(text2)) { text2 = "[" + text2 + "]"; int num6 = text.IndexOf(text2); text = text.Remove(num6, text.Length - num6); } while (text.Contains("\n\n\n")) { text = text.Replace("\n\n\n", "\n\n"); } File.WriteAllText(configFilePath, text); config.Reload(); } catch { } } } } namespace ReservedItemSlotCore.Networking { public static class NetworkHelper { private static int NONE_EXEC_STAGE = 0; private static int SERVER_EXEC_STAGE = 1; private static int CLIENT_EXEC_STAGE = 2; public static int GetExecStage(NetworkBehaviour __instance) { return (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue(); } public static bool IsClientExecStage(NetworkBehaviour __instance) { return GetExecStage(__instance) == CLIENT_EXEC_STAGE; } public static bool IsServerExecStage(NetworkBehaviour __instance) { return GetExecStage(__instance) == SERVER_EXEC_STAGE; } public static bool IsValidClientRpcExecStage(NetworkBehaviour __instance) { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsListening) { return false; } int num = (int)Traverse.Create((object)__instance).Field("__rpc_exec_stage").GetValue(); if ((singleton.IsServer || singleton.IsHost) && num != 2) { return false; } return true; } } [HarmonyPatch] internal static class SyncManager { public static PlayerControllerB localPlayerController; public static Dictionary<string, ReservedItemInfo> syncReservedItemsDict = new Dictionary<string, ReservedItemInfo>(); public static List<ReservedItemInfo> syncReservedItemsList = new List<ReservedItemInfo>(); public static List<ReservedItemInfo> syncReservedItemSlotReps = new List<ReservedItemInfo>(); public static bool isSynced = false; public static int numReservedItemSlots => syncReservedItemSlotReps.Count; public static bool IsReservedItem(string itemName) { return syncReservedItemsDict.ContainsKey(itemName); } public static bool TryGetReservedItemInfo(string itemName, out ReservedItemInfo info) { info = null; if (IsReservedItem(itemName)) { info = syncReservedItemsDict[itemName]; return true; } return false; } public static bool TryGetReservedItemInfo(GrabbableObject item, out ReservedItemInfo info) { info = null; return (Object)(object)item != (Object)null && TryGetReservedItemInfo(item.itemProperties.itemName, out info); } public static int GetReservedItemHotbarIndex(string itemName) { return IsReservedItem(itemName) ? syncReservedItemsDict[itemName].indexInInventory : (-1); } [HarmonyPatch(typeof(StartOfRound), "Awake")] [HarmonyPrefix] public static void ResetValues() { isSynced = false; localPlayerController = null; } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void Init(PlayerControllerB __instance) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown localPlayerController = __instance; NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-OnSwapHotbarClientRpc", new HandleNamedMessageDelegate(OnSwapHotbarClientRpc)); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-RequestSyncClientRpc", new HandleNamedMessageDelegate(RequestSyncClientRpc)); if (NetworkManager.Singleton.IsServer) { isSynced = true; syncReservedItemsDict = ReservedItemInfo.reservedItemsDict; syncReservedItemsList = ReservedItemInfo.reservedItemsList; syncReservedItemSlotReps = ReservedItemInfo.reservedItemSlotReps; NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-OnSwapHotbarServerRpc", new HandleNamedMessageDelegate(OnSwapHotbarServerRpc)); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("ReservedItemSlots-RequestSyncServerRpc", new HandleNamedMessageDelegate(RequestSyncServerRpc)); { foreach (ReservedItemInfo syncReservedItems in syncReservedItemsList) { ReservedItemInfo reservedItemInfo = ReservedItemInfo.reservedItemsDictDefault[syncReservedItems.itemName]; syncReservedItems.hotbarSlotPriority = reservedItemInfo.hotbarSlotPriority; syncReservedItems.reservedItemIndex = reservedItemInfo.reservedItemIndex; } return; } } isSynced = false; syncReservedItemsDict = new Dictionary<string, ReservedItemInfo>(); syncReservedItemsList = new List<ReservedItemInfo>(); syncReservedItemSlotReps = new List<ReservedItemInfo>(); RequestSyncWithServer(); } private static void RequestSyncWithServer() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { Plugin.Log("Requesting sync with server"); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ReservedItemSlots-RequestSyncServerRpc", 0uL, new FastBufferWriter(0, (Allocator)2, -1), (NetworkDelivery)3); } } private static void RequestSyncServerRpc(ulong clientId, FastBufferReader reader) { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0107: 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_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer) { return; } Plugin.Log("Receiving sync request from client: " + clientId); int num = 4 * syncReservedItemsList.Count; foreach (ReservedItemInfo syncReservedItems in syncReservedItemsList) { num += 4 + 2 * syncReservedItems.itemName.Length; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(num, (Allocator)2, -1); int count = syncReservedItemsList.Count; ((FastBufferWriter)(ref val)).WriteValue<int>(ref count, default(ForPrimitives)); foreach (ReservedItemInfo syncReservedItems2 in syncReservedItemsList) { count = syncReservedItems2.itemName.Length; ((FastBufferWriter)(ref val)).WriteValue<int>(ref count, default(ForPrimitives)); string itemName = syncReservedItems2.itemName; for (int i = 0; i < itemName.Length; i++) { char c = itemName[i]; ((FastBufferWriter)(ref val)).WriteValue<char>(ref c, default(ForPrimitives)); } ((FastBufferWriter)(ref val)).WriteValue<int>(ref syncReservedItems2.hotbarSlotPriority, default(ForPrimitives)); } Plugin.Log("Sent sync to client."); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ReservedItemSlots-RequestSyncClientRpc", clientId, val, (NetworkDelivery)3); } private static void RequestSyncClientRpc(ulong clientId, FastBufferReader reader) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsClient || NetworkManager.Singleton.IsServer) { return; } isSynced = true; syncReservedItemsDict = new Dictionary<string, ReservedItemInfo>(); syncReservedItemsList = new List<ReservedItemInfo>(); syncReservedItemSlotReps = new List<ReservedItemInfo>(); Plugin.Log("Receiving sync from server."); int num = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives)); int num2 = default(int); char c = default(char); for (int i = 0; i < num; i++) { ((FastBufferReader)(ref reader)).ReadValue<int>(ref num2, default(ForPrimitives)); ((FastBufferReader)(ref reader)).TryBeginRead(2 * num2); string text = ""; for (int j = 0; j < num2; j++) { ((FastBufferReader)(ref reader)).ReadValue<char>(ref c, default(ForPrimitives)); text += c; } bool flag = ReservedItemInfo.reservedItemsDict.ContainsKey(text); ReservedItemInfo reservedItemInfo = (ReservedItemInfo.reservedItemsDict.ContainsKey(text) ? ReservedItemInfo.reservedItemsDict[text] : new ReservedItemInfo { itemName = text }); ((FastBufferReader)(ref reader)).ReadValue<int>(ref reservedItemInfo.hotbarSlotPriority, default(ForPrimitives)); Plugin.Log("Receiving sync for item: - Item: " + reservedItemInfo.itemName + " Prio: " + reservedItemInfo.hotbarSlotPriority); ReservedItemInfo.AddItemInfoToList(reservedItemInfo, syncReservedItemsList, syncReservedItemsDict, syncReservedItemSlotReps); } Plugin.Log("Received sync for " + syncReservedItemSlotReps.Count + " reserved item slots. (" + syncReservedItemsList.Count + " items total)"); } private static void SendSwapHotbarUpdate(int hotbarSlot) { //IL_0024: 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_0042: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); ((FastBufferWriter)(ref val)).WriteValue<int>(ref hotbarSlot, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ReservedItemSlots-OnSwapHotbarServerRpc", 0uL, val, (NetworkDelivery)3); } } private static void OnSwapHotbarServerRpc(ulong clientId, FastBufferReader reader) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsServer) { if (((FastBufferReader)(ref reader)).TryBeginRead(4)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives)); Plugin.Log("Receiving OnSwapReservedHotbar update from client. ClientId: " + clientId + " Slot: " + num); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref clientId, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("ReservedItemSlots-OnSwapHotbarClientRpc", val, (NetworkDelivery)3); } else { Plugin.Log("Failed to receive hotbar swap index from Client: " + clientId); } } } private static void OnSwapHotbarClientRpc(ulong clientId, FastBufferReader reader) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsClient) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(12)) { int hotbarSlot = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref hotbarSlot, default(ForPrimitives)); ulong num = default(ulong); ((FastBufferReader)(ref reader)).ReadValue<ulong>(ref num, default(ForPrimitives)); Plugin.Log("Receiving OnSwapReservedHotbar update from client. ClientId: " + num + " Slot: " + hotbarSlot); if (num != localPlayerController.actualClientId && !TryUpdateClientHotbarSlot(num, hotbarSlot)) { Plugin.Log("Failed to receive hotbar swap index from Client: " + num); } } else { Plugin.Log("Failed to receive hotbar swap index from Client"); } } private static bool TryUpdateClientHotbarSlot(ulong clientId, int hotbarSlot) { for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i]; if (val.actualClientId == clientId) { CallSwitchToItemSlotMethod(val, hotbarSlot); return true; } } return false; } public static void SwapHotbarSlot(int hotbarIndex) { SendSwapHotbarUpdate(hotbarIndex); CallSwitchToItemSlotMethod(localPlayerController, hotbarIndex); } private static void CallSwitchToItemSlotMethod(PlayerControllerB playerController, int hotbarIndex) { if (!((Object)(object)playerController == (Object)null) && playerController.ItemSlots != null && hotbarIndex >= 0 && hotbarIndex < playerController.ItemSlots.Length) { if ((Object)(object)playerController == (Object)(object)localPlayerController) { ShipBuildModeManager.Instance.CancelBuildMode(true); playerController.playerBodyAnimator.SetBool("GrabValidated", false); } ReservedItemPatcher.SwitchToItemSlot(playerController, hotbarIndex); if ((Object)(object)playerController.currentlyHeldObjectServer != (Object)null) { ((Component)playerController.currentlyHeldObjectServer).gameObject.GetComponent<AudioSource>().PlayOneShot(playerController.currentlyHeldObjectServer.itemProperties.grabSFX, 0.6f); } } } } } namespace ReservedItemSlotCore.Input { internal class IngameKeybinds : LcInputActions { internal static IngameKeybinds Instance = new IngameKeybinds(); [InputAction("<Keyboard>/leftAlt", Name = "[ReservedItemSlots]\nSwap hotbar")] public InputAction FocusReservedHotbarHotkey { get; set; } internal static InputActionAsset GetAsset() { return ((LcInputActions)Instance).Asset; } } internal class InputUtilsCompat { internal static InputActionAsset Asset => IngameKeybinds.GetAsset(); internal static bool Enabled => Plugin.IsModLoaded("com.rune580.LethalCompanyInputUtils"); public static InputAction FocusReservedHotbarHotkey => IngameKeybinds.Instance.FocusReservedHotbarHotkey; } [HarmonyPatch] internal class Keybinds { public static InputActionAsset Asset; public static InputActionMap ActionMap; public static InputAction FocusReservedHotbarAction; public static InputAction RawScrollAction; public static bool holdingModifierKey; public static bool scrollingReservedHotbar; public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController; [HarmonyPatch(typeof(PreInitSceneScript), "Awake")] [HarmonyPrefix] public static void AddToKeybindMenu() { InitKeybinds(); } public static void InitKeybinds() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown if (InputUtilsCompat.Enabled) { Asset = InputUtilsCompat.Asset; FocusReservedHotbarAction = InputUtilsCompat.FocusReservedHotbarHotkey; } else { Asset = new InputActionAsset(); ActionMap = new InputActionMap("ReservedItemSlots"); InputActionSetupExtensions.AddActionMap(Asset, ActionMap); FocusReservedHotbarAction = InputActionSetupExtensions.AddAction(ActionMap, "ReservedItemSlots.FocusReservedHotbar", (InputActionType)0, ConfigSettings.focusReservedHotbarHotkey.Value, (string)null, (string)null, (string)null, (string)null); } RawScrollAction = new InputAction("ReservedItemSlots.RawScroll", (InputActionType)0, "<Mouse>/scroll/y", (string)null, (string)null, (string)null); } [HarmonyPatch(typeof(StartOfRound), "OnEnable")] [HarmonyPrefix] public static void OnEnable() { Asset.Enable(); RawScrollAction.Enable(); FocusReservedHotbarAction.performed += FocusReservedHotbarSlotsAction; if (!ConfigSettings.toggleFocusReservedHotbar.Value) { FocusReservedHotbarAction.canceled += UnfocusReservedHotbarSlotsPerformed; } RawScrollAction.performed += OnScrollReservedHotbar; } [HarmonyPatch(typeof(StartOfRound), "OnDisable")] [HarmonyPrefix] public static void OnDisable() { Asset.Disable(); RawScrollAction.Disable(); FocusReservedHotbarAction.performed -= FocusReservedHotbarSlotsAction; if (!ConfigSettings.toggleFocusReservedHotbar.Value) { FocusReservedHotbarAction.canceled -= UnfocusReservedHotbarSlotsPerformed; } RawScrollAction.performed -= OnScrollReservedHotbar; } private static void FocusReservedHotbarSlotsAction(CallbackContext context) { if (SyncManager.numReservedItemSlots <= 0 || (Object)(object)localPlayerController == (Object)null || !((NetworkBehaviour)localPlayerController).IsOwner || !localPlayerController.isPlayerControlled || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject)) { return; } if (!ConfigSettings.toggleFocusReservedHotbar.Value) { holdingModifierKey = true; } if (((CallbackContext)(ref context)).performed && ReservedItemPatcher.CanSwapToReservedHotbarSlot()) { if (!ConfigSettings.toggleFocusReservedHotbar.Value) { ReservedItemPatcher.FocusReservedHotbarSlots(active: true); } else { ReservedItemPatcher.FocusReservedHotbarSlots(!PlayerPatcher.playerDataLocal.currentItemSlotIsReserved); } } } private static void UnfocusReservedHotbarSlotsPerformed(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject)) { holdingModifierKey = false; if (((CallbackContext)(ref context)).canceled && ReservedItemPatcher.CanSwapToReservedHotbarSlot()) { ReservedItemPatcher.FocusReservedHotbarSlots(active: false); } } } private static void OnScrollReservedHotbar(CallbackContext context) { //IL_0096: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)localPlayerController == (Object)null) && ((NetworkBehaviour)localPlayerController).IsOwner && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject) && ((CallbackContext)(ref context)).performed && PlayerPatcher.playerDataLocal.currentItemSlotIsReserved && PlayerPatcher.playerDataLocal.grabbingReservedItem == null) { scrollingReservedHotbar = true; MethodInfo method = ((object)localPlayerController).GetType().GetMethod("ScrollMouse_performed", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(localPlayerController, new object[1] { context }); ((MonoBehaviour)localPlayerController).StartCoroutine(ResetScrollStateEndOfFrame()); } static IEnumerator ResetScrollStateEndOfFrame() { yield return (object)new WaitForEndOfFrame(); scrollingReservedHotbar = false; } } } } namespace ReservedItemSlotCore.Patches { [HarmonyPatch] public static class HUDPatcher { private static float iconWidth; private static float xPos; private static TextMeshProUGUI hotkeyTooltip; [HarmonyPatch(typeof(HUDManager), "OnEnable")] [HarmonyPostfix] public static void Initialize(HUDManager __instance) { //IL_002a: 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) CanvasScaler componentInParent = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<CanvasScaler>(); AspectRatioFitter componentInParent2 = ((Component)__instance.itemSlotIconFrames[0]).GetComponentInParent<AspectRatioFitter>(); iconWidth = ((Component)__instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.x; xPos = componentInParent.referenceResolution.x / 2f / componentInParent2.aspectRatio - iconWidth / 4f; } public static void AddNewHotbarSlotsHud() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: 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_0080: 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_017a: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_0336: Unknown result type (might be due to invalid IL or missing references) if (PlayerPatcher.reservedHotbarSize > 0) { List<Image> list = new List<Image>(HUDManager.Instance.itemSlotIconFrames); List<Image> list2 = new List<Image>(HUDManager.Instance.itemSlotIcons); float y = ((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>().sizeDelta.y; Vector3 eulerAngles = ((Transform)((Component)HUDManager.Instance.itemSlotIconFrames[0]).GetComponent<RectTransform>()).eulerAngles; Vector3 eulerAngles2 = ((Transform)((Component)HUDManager.Instance.itemSlotIcons[0]).GetComponent<RectTransform>()).eulerAngles; Plugin.Log($"Adding {SyncManager.syncReservedItemSlotReps.Count} Reserved item slots to the inventory HUD. Previous inventory HUD size: {PlayerPatcher.playerDataLocal.reservedHotbarStartIndex}"); for (int i = 0; i < SyncManager.syncReservedItemSlotReps.Count; i++) { ReservedItemInfo reservedItemInfo = SyncManager.syncReservedItemSlotReps[i]; Plugin.Log($"Adding Reserved item slot for item types [{reservedItemInfo.itemName}]. Inventory index: {list.Count}"); float num = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + 1.125f * y * (float)i; Image val = Object.Instantiate<Image>(HUDManager.Instance.itemSlotIconFrames[PlayerPatcher.playerDataLocal.reservedHotbarStartIndex - 1], ((Component)HUDManager.Instance.itemSlotIconFrames[0]).transform.parent); ((Object)val).name = "Slot" + list.Count + " [ReservedItemSlot]"; ((Graphic)val).rectTransform.anchoredPosition = new Vector2(xPos, num); ((Transform)((Graphic)val).rectTransform).eulerAngles = eulerAngles; Animator component = ((Component)val).GetComponent<Animator>(); component.runtimeAnimatorController = (RuntimeAnimatorController)new AnimatorOverrideController(component.runtimeAnimatorController); CanvasGroup val2 = ((Component)val).gameObject.AddComponent<CanvasGroup>(); val2.ignoreParentGroups = ConfigSettings.preventReservedItemSlotFade.Value; val2.alpha = 1f; Image component2 = ((Component)((Component)val).transform.GetChild(0)).GetComponent<Image>(); ((Object)component2).name = "Icon"; ((Transform)((Graphic)component2).rectTransform).eulerAngles = eulerAngles2; list.Add(val); list2.Add(component2); } if (SyncManager.numReservedItemSlots > 0 && (Object)(object)hotkeyTooltip == (Object)null) { hotkeyTooltip = new GameObject("ReservedItemSlotTooltip", new Type[2] { typeof(RectTransform), typeof(TextMeshProUGUI) }).GetComponent<TextMeshProUGUI>(); RectTransform rectTransform = ((TMP_Text)hotkeyTooltip).rectTransform; ((Component)rectTransform).transform.parent = ((Component)list[PlayerPatcher.playerDataLocal.reservedHotbarStartIndex]).transform; ((Transform)rectTransform).localScale = Vector3.one; rectTransform.sizeDelta = new Vector2(((Graphic)list[0]).rectTransform.sizeDelta.x * 2f, 10f); rectTransform.pivot = Vector2.one / 2f; rectTransform.anchoredPosition3D = new Vector3(0f, (0f - rectTransform.sizeDelta.x / 2f) * 1.2f, 0f); ((TMP_Text)hotkeyTooltip).font = ((TMP_Text)HUDManager.Instance.controlTipLines[0]).font; ((TMP_Text)hotkeyTooltip).fontSize = 7f; ((TMP_Text)hotkeyTooltip).alignment = (TextAlignmentOptions)514; UpdateHotkeyTooltipText(); } HUDManager.Instance.itemSlotIconFrames = list.ToArray(); HUDManager.Instance.itemSlotIcons = list2.ToArray(); Plugin.Log($"Finished adding {PlayerPatcher.reservedHotbarSize} Reserved Item slots in the inventory HUD."); } } [HarmonyPatch(typeof(QuickMenuManager), "CloseQuickMenu")] [HarmonyPostfix] public static void UpdateHotkeyText(QuickMenuManager __instance) { if (!__instance.isMenuOpen) { UpdateHotkeyTooltipText(); } } private static void UpdateHotkeyTooltipText() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0033: 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_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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) InputBinding val; string key; if (!InputUtilsCompat.Enabled) { val = Keybinds.FocusReservedHotbarAction.bindings[0]; key = ((InputBinding)(ref val)).path; } else { val = Keybinds.FocusReservedHotbarAction.bindings[0]; key = ((InputBinding)(ref val)).overridePath; } string displayName = ConfigSettings.GetDisplayName(key); TextMeshProUGUI obj = hotkeyTooltip; string text3; if (!ConfigSettings.toggleFocusReservedHotbar.Value) { string text2 = (((TMP_Text)hotkeyTooltip).text = string.Format($"Hold: [{displayName}]")); text3 = text2; } else { text3 = string.Format($"Toggle: [{displayName}]"); } ((TMP_Text)obj).text = text3; } public static void UpdateHUD() { //IL_0024: 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) for (int i = 0; i < PlayerPatcher.reservedHotbarSize; i++) { int num = PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + i; float num2 = ((Graphic)HUDManager.Instance.itemSlotIconFrames[0]).rectTransform.anchoredPosition.y + 1.125f * iconWidth * (float)i; ((Graphic)HUDManager.Instance.itemSlotIconFrames[num]).rectTransform.anchoredPosition = new Vector2(xPos, num2); } } } [HarmonyPatch] public static class MouseScrollPatcher { public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController; [HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")] [HarmonyPrefix] public static void CorrectReservedScrollDirectionNextItemSlot(ref bool forward) { if (Keybinds.scrollingReservedHotbar) { forward = Keybinds.RawScrollAction.ReadValue<float>() > 0f; } } [HarmonyPatch(typeof(PlayerControllerB), "SwitchItemSlotsServerRpc")] [HarmonyPrefix] public static void CorrectReservedScrollDirectionServerRpc(ref bool forward) { if (Keybinds.scrollingReservedHotbar) { forward = Keybinds.RawScrollAction.ReadValue<float>() > 0f; } } [HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")] [HarmonyPrefix] public static bool PreventInvertedScrollingReservedHotbar(CallbackContext context) { if (PlayerPatcher.playerDataLocal.currentItemSlotIsReserved && (!Keybinds.scrollingReservedHotbar || SyncManager.numReservedItemSlots == 1 || (PlayerPatcher.playerDataLocal.GetNumHeldReservedItems() == 1 && (Object)(object)localPlayerController.ItemSlots[localPlayerController.currentItemSlot] != (Object)null))) { return false; } return true; } } [HarmonyPatch] public static class ReservedItemPatcher { public static int indexUnfocusedReservedHotbarLocal; public static int indexFocusedReservedHotbarLocal; public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController; public static int reservedHotbarSize => SyncManager.numReservedItemSlots; private static GrabbableObject GetCurrentlyGrabbingObject(PlayerControllerB playerController) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown return (GrabbableObject)Traverse.Create((object)playerController).Field("currentlyGrabbingObject").GetValue(); } private static void SetCurrentlyGrabbingObject(PlayerControllerB playerController, GrabbableObject grabbable) { Traverse.Create((object)playerController).Field("currentlyGrabbingObject").SetValue((object)grabbable); } [HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")] [HarmonyPrefix] public static bool GrabReservedItemPrefix(PlayerControllerB __instance) { //IL_0085: 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_009f: Unknown result type (might be due to invalid IL or missing references) if (!SyncManager.isSynced) { return true; } PlayerPatcher.playerDataLocal.grabbingReservedItem = null; PlayerPatcher.playerDataLocal.previousHotbarIndex = -1; if (PlayerPatcher.playerDataLocal.currentItemSlotIsReserved && !ConfigSettings.toggleFocusReservedHotbar.Value) { return false; } if (__instance.twoHanded || __instance.sinkingValue > 0.73f) { return true; } Ray val = default(Ray); ((Ray)(ref val))..ctor(((Component)__instance.gameplayCamera).transform.position, ((Component)__instance.gameplayCamera).transform.forward); RaycastHit val2 = default(RaycastHit); if (Physics.Raycast(val, ref val2, __instance.grabDistance, PlayerPatcher.INTERACTABLE_OBJECT_MASK) && ((Component)((RaycastHit)(ref val2)).collider).gameObject.layer != 8 && ((Component)((RaycastHit)(ref val2)).collider).tag == "PhysicsProp") { GrabbableObject component = ((Component)((Component)((RaycastHit)(ref val2)).collider).transform).gameObject.GetComponent<GrabbableObject>(); if ((Object)(object)component != (Object)null && !__instance.inSpecialInteractAnimation && !component.isHeld && !component.isPocketed) { NetworkObject networkObject = ((NetworkBehaviour)component).NetworkObject; if ((Object)(object)networkObject != (Object)null && networkObject.IsSpawned && SyncManager.TryGetReservedItemInfo(((Component)((Component)((RaycastHit)(ref val2)).collider).transform).gameObject.GetComponent<GrabbableObject>(), out var info)) { Plugin.Log("Beginning grab on reserved item: " + info.itemName); PlayerPatcher.playerDataLocal.grabbingReservedItem = info; PlayerPatcher.playerDataLocal.previousHotbarIndex = __instance.currentItemSlot; } } } return true; } [HarmonyPatch(typeof(PlayerControllerB), "BeginGrabObject")] [HarmonyPostfix] public static void GrabReservedItemPostfix(PlayerControllerB __instance) { if (PlayerPatcher.playerDataLocal.grabbingReservedItem != null) { SetSpecialGrabAnimationBool(__instance, setTrue: false); } } [HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")] [HarmonyPrefix] public static void GrabReservedItemClientRpcPrefix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance) { if (!SyncManager.isSynced || !NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance)) { return; } ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance]; NetworkObject val = default(NetworkObject); if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening && grabValidated && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null)) { GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>(); if (SyncManager.TryGetReservedItemInfo(component, out var info)) { if (IsItemSlotEmpty(info, __instance)) { Plugin.Log("OnGrabReservedItem for Player: " + ((Object)__instance).name + " Item: " + info.itemName); reservedPlayerData.grabbingReservedItem = info; reservedPlayerData.previousHotbarIndex = __instance.currentItemSlot; return; } Plugin.LogWarning("OnGrabReservedItem SlotFilled. Player: " + ((Object)__instance).name + " Item: " + info.itemName + " Slot: " + (reservedPlayerData.reservedHotbarStartIndex + info.reservedItemIndex)); } } reservedPlayerData.grabbingReservedItem = null; reservedPlayerData.previousHotbarIndex = -1; } [HarmonyPatch(typeof(PlayerControllerB), "GrabObjectClientRpc")] [HarmonyPostfix] public static void GrabReservedItemClientRpcPostfix(bool grabValidated, NetworkObjectReference grabbedObject, PlayerControllerB __instance) { //IL_00c0: 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_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) if (!SyncManager.isSynced || !NetworkHelper.IsClientExecStage((NetworkBehaviour)(object)__instance)) { return; } ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance]; if (reservedPlayerData.grabbingReservedItem == null) { return; } if ((Object)(object)NetworkManager.Singleton != (Object)null && NetworkManager.Singleton.IsListening) { NetworkObject val = default(NetworkObject); if (grabValidated && ((NetworkObjectReference)(ref grabbedObject)).TryGet(ref val, (NetworkManager)null)) { GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>(); if (SyncManager.TryGetReservedItemInfo(component, out var info)) { GrabbableObject val2 = __instance.ItemSlots[reservedPlayerData.previousHotbarIndex]; SetSpecialGrabAnimationBool(__instance, (Object)(object)val2 != (Object)null, val2); Animator playerBodyAnimator = __instance.playerBodyAnimator; AnimatorStateInfo currentAnimatorStateInfo = __instance.playerBodyAnimator.GetCurrentAnimatorStateInfo(0); playerBodyAnimator.Play(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash, 2, 1f); if ((Object)(object)val2 != (Object)null) { val2.EnableItemMeshes(true); } Traverse.Create((object)component).Field("previousPlayerHeldBy").SetValue((object)__instance); if ((Object)(object)__instance != (Object)(object)localPlayerController) { Plugin.Log("OnGrabReservedItem completed. Player: " + ((Object)__instance).name + " Item: " + info.itemName + " Switching to previous slot: " + reservedPlayerData.previousHotbarIndex); SwitchToItemSlot(__instance, reservedPlayerData.previousHotbarIndex); Animator playerBodyAnimator2 = __instance.playerBodyAnimator; currentAnimatorStateInfo = __instance.playerBodyAnimator.GetCurrentAnimatorStateInfo(0); playerBodyAnimator2.Play(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash, 2, 1f); reservedPlayerData.grabbingReservedItem = null; reservedPlayerData.previousHotbarIndex = -1; } else { int num = reservedPlayerData.reservedHotbarStartIndex + reservedPlayerData.grabbingReservedItem.reservedItemIndex; ((Component)HUDManager.Instance.itemSlotIconFrames[num]).GetComponent<Animator>().SetBool("selectedSlot", false); ((Component)HUDManager.Instance.itemSlotIconFrames[reservedPlayerData.previousHotbarIndex]).GetComponent<Animator>().SetBool("selectedSlot", true); ((Component)HUDManager.Instance.itemSlotIconFrames[num]).GetComponent<Animator>().Play("PanelLines", 0, 1f); ((Component)HUDManager.Instance.itemSlotIconFrames[reservedPlayerData.previousHotbarIndex]).GetComponent<Animator>().Play("PanelEnlarge", 0, 1f); } return; } } else if ((Object)(object)__instance == (Object)(object)localPlayerController) { Plugin.Log("Failed to validate ReservedItemGrab by the local player. Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + "."); Traverse.Create((object)localPlayerController).Field("grabInvalidated").SetValue((object)true); } else { Plugin.Log("Failed to validate ReservedItemGrab by player with id: " + ((Object)__instance).name + ". Object id: " + ((NetworkObjectReference)(ref grabbedObject)).NetworkObjectId + "."); } } reservedPlayerData.grabbingReservedItem = null; reservedPlayerData.previousHotbarIndex = -1; } [HarmonyPatch(typeof(GrabbableObject), "GrabItemOnClient")] [HarmonyPrefix] public static void OnReservedItemGrabbed(GrabbableObject __instance) { if (PlayerPatcher.playerDataLocal.grabbingReservedItem != null && !((Object)(object)__instance != (Object)(object)GetCurrentlyGrabbingObject(localPlayerController))) { ((MonoBehaviour)localPlayerController).StartCoroutine(OnReservedItemGrabbedEndOfFrame()); } IEnumerator OnReservedItemGrabbedEndOfFrame() { yield return (object)new WaitForEndOfFrame(); SwitchToItemSlot(localPlayerController, PlayerPatcher.playerDataLocal.previousHotbarIndex); PlayerPatcher.playerDataLocal.grabbingReservedItem = null; PlayerPatcher.playerDataLocal.previousHotbarIndex = -1; __instance.PocketItem(); Animator playerBodyAnimator = localPlayerController.playerBodyAnimator; AnimatorStateInfo currentAnimatorStateInfo = localPlayerController.playerBodyAnimator.GetCurrentAnimatorStateInfo(0); playerBodyAnimator.Play(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash, 2, 1f); } } private static void OnLocalPlayerGrabbedReservedItem() { } [HarmonyPatch(typeof(PlayerControllerB), "SwitchToItemSlot")] [HarmonyPrefix] public static void DebugSwitchToItemSlot(int slot, PlayerControllerB __instance) { if (!PlayerPatcher.allPlayerData[__instance].IsReservedItemSlot(slot)) { return; } string text = ""; ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance]; if (slot < 0) { text = "Called SwitchToItemSlot on slot: " + slot; } else if (slot >= __instance.ItemSlots.Length) { text = "Called SwitchToItemSlot on slot: " + slot + " HotbarSize: " + __instance.ItemSlots.Length; } else { if (slot < HUDManager.Instance.itemSlotIconFrames.Length) { return; } text = "Called SwitchToItemSlot on slot: " + slot + " NumItemSlotsHUD: " + HUDManager.Instance.itemSlotIconFrames.Length; } text += "\n\n"; text = text + reservedPlayerData.DumpData() + "\n\nReporting this error to Flip would be greatly appreciated!"; Debug.LogError((object)text); } [HarmonyPatch(typeof(PlayerControllerB), "SwitchToItemSlot")] [HarmonyPostfix] public static void UpdateFocusReservedHotbar(int slot, PlayerControllerB __instance) { PlayerPatcher.allPlayerData[__instance].inReservedHotbarSlots = PlayerPatcher.allPlayerData[__instance].IsReservedItemSlot(__instance.currentItemSlot); } [HarmonyPatch(typeof(PlayerControllerB), "FirstEmptyItemSlot")] [HarmonyPostfix] public static void GetReservedItemSlotPlacementIndex(ref int __result, PlayerControllerB __instance) { if (reservedHotbarSize <= 0) { return; } ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance]; ReservedItemInfo grabbingReservedItem = reservedPlayerData.grabbingReservedItem; if (grabbingReservedItem != null) { if (IsItemSlotEmpty(grabbingReservedItem, __instance)) { __result = reservedPlayerData.reservedHotbarStartIndex + grabbingReservedItem.reservedItemIndex; return; } reservedPlayerData.grabbingReservedItem = null; reservedPlayerData.previousHotbarIndex = -1; } if (!reservedPlayerData.IsReservedItemSlot(__result)) { return; } __result = -1; for (int i = 0; i < __instance.ItemSlots.Length; i++) { if (!reservedPlayerData.IsReservedItemSlot(i) && (Object)(object)__instance.ItemSlots[i] == (Object)null) { __result = i; break; } } } [HarmonyPatch(typeof(PlayerControllerB), "NextItemSlot")] [HarmonyPostfix] public static void OnNextItemSlot(ref int __result, bool forward, PlayerControllerB __instance) { if (reservedHotbarSize <= 0) { return; } ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[__instance]; bool flag = reservedPlayerData.IsReservedItemSlot(__result); if (flag == reservedPlayerData.inReservedHotbarSlots && (!flag || (Object)(object)__instance.ItemSlots[__result] != (Object)null)) { return; } int num = (forward ? 1 : (-1)); __result = __instance.currentItemSlot + num; __result = ((__result < 0) ? (__instance.ItemSlots.Length - 1) : ((__result < __instance.ItemSlots.Length) ? __result : 0)); bool flag2 = reservedPlayerData.IsReservedItemSlot(__result); if (!reservedPlayerData.inReservedHotbarSlots) { if (flag2) { __result = (forward ? ((reservedPlayerData.reservedHotbarStartIndex + reservedHotbarSize) % __instance.ItemSlots.Length) : (reservedPlayerData.reservedHotbarStartIndex - 1)); } return; } __result = (flag2 ? __result : (forward ? reservedPlayerData.reservedHotbarStartIndex : (reservedPlayerData.reservedHotbarStartIndex + reservedHotbarSize - 1))); int numHeldReservedItems = reservedPlayerData.GetNumHeldReservedItems(); while (numHeldReservedItems > 0 && __result != reservedPlayerData.currentItemSlot && (Object)(object)__instance.ItemSlots[__result] == (Object)null) { __result += num; __result = ((!reservedPlayerData.IsReservedItemSlot(__result)) ? (forward ? reservedPlayerData.reservedHotbarStartIndex : (reservedPlayerData.reservedHotbarStartIndex + reservedHotbarSize - 1)) : __result); } } [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] [HarmonyPrefix] public static void RefocusReservedHotbarAfterAnimation(PlayerControllerB __instance) { if (!((Object)(object)__instance != (Object)(object)localPlayerController) && !ConfigSettings.toggleFocusReservedHotbar.Value && Keybinds.holdingModifierKey != PlayerPatcher.playerDataLocal.currentItemSlotIsReserved && CanSwapToReservedHotbarSlot()) { FocusReservedHotbarSlots(Keybinds.holdingModifierKey); } } public static bool CanSwapToReservedHotbarSlot() { bool flag = (bool)Traverse.Create((object)localPlayerController).Field("throwingObject").GetValue(); return !(PlayerPatcher.playerDataLocal.grabbingReservedItem != null || localPlayerController.isGrabbingObjectAnimation || localPlayerController.quickMenuManager.isMenuOpen || localPlayerController.inSpecialInteractAnimation || flag) && !localPlayerController.isTypingChat && !localPlayerController.twoHanded && !localPlayerController.activatingItem && !localPlayerController.jetpackControls && !localPlayerController.disablingJetpackControls && !localPlayerController.inTerminalMenu && !localPlayerController.isPlayerDead && !(GetTimeSinceSwitchingSlots(localPlayerController) < 0.3f); } [HarmonyPatch(typeof(PlayerControllerB), "UpdateSpecialAnimationValue")] [HarmonyPostfix] public static void OnSpecialAnimationUpdate(bool specialAnimation, PlayerControllerB __instance) { if (!((Object)(object)__instance != (Object)(object)localPlayerController) && !specialAnimation && !ConfigSettings.toggleFocusReservedHotbar.Value && PlayerPatcher.playerDataLocal.currentItemSlotIsReserved != Keybinds.holdingModifierKey) { FocusReservedHotbarSlots(Keybinds.holdingModifierKey); } } public static void FocusReservedHotbarSlots(bool active) { if ((reservedHotbarSize <= 0 && active) || PlayerPatcher.playerDataLocal.currentItemSlotIsReserved == active) { return; } int num = localPlayerController.currentItemSlot; bool flag = active; if (flag && (num < PlayerPatcher.playerDataLocal.reservedHotbarStartIndex || num >= PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedHotbarSize)) { Plugin.Log("Focusing reserved hotbar slots."); if (indexFocusedReservedHotbarLocal == -1) { indexFocusedReservedHotbarLocal = PlayerPatcher.playerDataLocal.reservedHotbarStartIndex; } indexUnfocusedReservedHotbarLocal = num; num = Mathf.Clamp(indexFocusedReservedHotbarLocal, PlayerPatcher.playerDataLocal.reservedHotbarStartIndex, PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedHotbarSize - 1); if ((Object)(object)localPlayerController.ItemSlots[num] == (Object)null) { for (int i = 0; i < reservedHotbarSize; i++) { int num2 = PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + i; if ((Object)(object)localPlayerController.ItemSlots[num2] != (Object)null) { num = num2; break; } } } } else if (!flag && num >= PlayerPatcher.playerDataLocal.reservedHotbarStartIndex && num < PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedHotbarSize) { Plugin.Log("Unfocusing reserved hotbar slots."); indexFocusedReservedHotbarLocal = num; if (indexUnfocusedReservedHotbarLocal >= PlayerPatcher.playerDataLocal.reservedHotbarStartIndex && indexUnfocusedReservedHotbarLocal < PlayerPatcher.playerDataLocal.reservedHotbarStartIndex + reservedHotbarSize) { indexUnfocusedReservedHotbarLocal = 0; } num = indexUnfocusedReservedHotbarLocal; } SyncManager.SwapHotbarSlot(num); } internal static bool IsItemSlotEmpty(string itemName, PlayerControllerB playerController) { if (!SyncManager.TryGetReservedItemInfo(itemName, out var info)) { return false; } return IsItemSlotEmpty(info, playerController); } internal static bool IsItemSlotEmpty(ReservedItemInfo itemInfo, PlayerControllerB playerController) { playerController = (((Object)(object)playerController == (Object)null) ? localPlayerController : playerController); if (reservedHotbarSize == 0) { return false; } ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[playerController]; int num = reservedPlayerData.reservedHotbarStartIndex + itemInfo.reservedItemIndex; return num >= reservedPlayerData.reservedHotbarStartIndex && num < reservedPlayerData.reservedHotbarStartIndex + reservedHotbarSize && (Object)(object)playerController.ItemSlots[num] == (Object)null; } public static bool TryGetHeldReservedObject(string itemName, PlayerControllerB playerController, ref GrabbableObject obj) { playerController = (((Object)(object)playerController == (Object)null) ? localPlayerController : playerController); if ((Object)(object)playerController == (Object)null || reservedHotbarSize == 0) { return false; } if (!SyncManager.TryGetReservedItemInfo(itemName, out var info)) { return false; } ReservedPlayerData reservedPlayerData = PlayerPatcher.allPlayerData[playerController]; int num = reservedPlayerData.reservedHotbarStartIndex + info.reservedItemIndex; obj = playerController.ItemSlots[num]; return (Object)(object)obj != (Object)null; } public static float GetTimeSinceSwitchingSlots(PlayerControllerB playerController) { return (float)Traverse.Create((object)playerController).Field("timeSinceSwitchingSlots").GetValue(); } public static void SetTimeSinceSwitchingSlots(PlayerControllerB playerController, float value) { Traverse.Create((object)playerController).Field("timeSinceSwitchingSlots").SetValue((object)value); } public static void SetSpecialGrabAnimationBool(PlayerControllerB playerController, bool setTrue, GrabbableObject currentItem = null) { MethodInfo method = ((object)playerController).GetType().GetMethod("SetSpecialGrabAnimationBool", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(playerController, new object[2] { setTrue, currentItem }); } public static void SwitchToItemSlot(PlayerControllerB playerController, int slot, GrabbableObject fillSlotWithItem = null) { MethodInfo method = ((object)playerController).GetType().GetMethod("SwitchToItemSlot", BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(playerController, new object[2] { slot, fillSlotWithItem }); SetTimeSinceSwitchingSlots(playerController, 0f); } } [HarmonyPatch] public static class PlayerPatcher { public static PlayerControllerB localPlayerController; public static int vanillaHotbarSize = -1; internal static Dictionary<PlayerControllerB, ReservedPlayerData> allPlayerData = new Dictionary<PlayerControllerB, ReservedPlayerData>(); private static bool isSynced = false; public static int INTERACTABLE_OBJECT_MASK { get; private set; } public static int reservedHotbarSize => SyncManager.numReservedItemSlots; internal static ReservedPlayerData playerDataLocal => (allPlayerData != null && (Object)(object)localPlayerController != (Object)null && allPlayerData.ContainsKey(localPlayerController)) ? allPlayerData[localPlayerController] : null; [HarmonyPatch(typeof(StartOfRound), "Awake")] [HarmonyPrefix] public static void InitSession(StartOfRound __instance) { localPlayerController = null; vanillaHotbarSize = -1; ReservedItemPatcher.indexUnfocusedReservedHotbarLocal = 0; ReservedItemPatcher.indexFocusedReservedHotbarLocal = -1; Keybinds.holdingModifierKey = false; allPlayerData.Clear(); isSynced = false; } [HarmonyPatch(typeof(PlayerControllerB), "Awake")] [HarmonyPostfix] public static void InitializePlayerController(PlayerControllerB __instance) { if (vanillaHotbarSize == -1) { vanillaHotbarSize = __instance.ItemSlots.Length; } } [HarmonyPatch(typeof(PlayerControllerB), "Start")] [HarmonyPostfix] public static void InitializePlayerControllerLate(PlayerControllerB __instance) { allPlayerData.Add(__instance, new ReservedPlayerData { playerController = __instance, hotbarSize = __instance.ItemSlots.Length, reservedHotbarStartIndex = __instance.ItemSlots.Length }); } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void OnLocalPlayerConnect(PlayerControllerB __instance) { localPlayerController = __instance; INTERACTABLE_OBJECT_MASK = (int)Traverse.Create((object)__instance).Field("interactableObjectsMask").GetValue(); ((MonoBehaviour)__instance).StartCoroutine(UpdateHotbarSlotsAfterSpawnAnimation()); } private static IEnumerator UpdateHotbarSlotsAfterSpawnAnimation() { yield return (object)new WaitForSeconds(3f); if (SyncManager.isSynced && !isSynced) { OnSyncedWithServer(); } } [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] [HarmonyPostfix] public static void OnUpdate(PlayerControllerB __instance) { if (SyncManager.isSynced && !isSynced) { OnSyncedWithServer(); } ReservedPlayerData reservedPlayerData = allPlayerData[__instance]; if (!isSynced || reservedHotbarSize <= 0 || reservedPlayerData.hotbarSize == __instance.ItemSlots.Length) { return; } Plugin.Log("On update inventory size for player: " + ((Object)__instance).name + " - Old hotbar size: " + reservedPlayerData.hotbarSize + " - New hotbar size: " + __instance.ItemSlots.Length); reservedPlayerData.hotbarSize = __instance.ItemSlots.Length; int num = -1; if ((Object)(object)__instance == (Object)(object)localPlayerController) { for (int i = 0; i < HUDManager.Instance.itemSlotIconFrames.Length; i++) { if (((Object)HUDManager.Instance.itemSlotIconFrames[i]).name.ToLower().StartsWith("reserveditemslot")) { num = i; Plugin.Log("OnUpdateInventorySize A for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num); break; } } } if (num == -1) { for (int j = 0; j < __instance.ItemSlots.Length; j++) { GrabbableObject item = __instance.ItemSlots[j]; if (SyncManager.TryGetReservedItemInfo(item, out var info)) { num = j - info.reservedItemIndex; Plugin.Log("OnUpdateInventorySize B for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num); break; } } if (num == __instance.ItemSlots.Length) { num = -1; } } if (num == -1) { num = reservedPlayerData.reservedHotbarStartIndex; Plugin.Log("OnUpdateInventorySize C for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num); } if (num == -1) { num = vanillaHotbarSize; Plugin.Log("OnUpdateInventorySize D for player: " + ((Object)__instance).name + " NewReservedItemsStartIndex: " + num); } reservedPlayerData.reservedHotbarStartIndex = num; if ((Object)(object)__instance == (Object)(object)localPlayerController) { HUDPatcher.UpdateHUD(); } } private static void OnSyncedWithServer() { Plugin.Log("Finalizing sync with server."); isSynced = true; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { allPlayerData[val].reservedHotbarStartIndex = val.ItemSlots.Length; val.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[val.ItemSlots.Length + reservedHotbarSize]; allPlayerData[val].hotbarSize = val.ItemSlots.Length; } HUDPatcher.AddNewHotbarSlotsHud(); } } }
plugins/ReservedWalkieSlot.dll
Decompiled a year agousing System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using ReservedItemSlotCore; using ReservedItemSlotCore.Networking; using ReservedItemSlotCore.Patches; using ReservedWalkieSlot.Patches; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("ReservedWalkieSlot")] [assembly: AssemblyDescription("Mod made by flipf17")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ReservedWalkieSlot")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("c15c320f-d8fc-4f1c-be3c-f2d2ffc41edd")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace ReservedWalkieSlot { public static class ConfigSettings { public static ConfigEntry<string> activateWalkieKey; public static ConfigEntry<bool> hideWalkieMeshShoulder; public static string activateWalkieDisplayName; public static Dictionary<string, ConfigEntryBase> currentConfigEntries = new Dictionary<string, ConfigEntryBase>(); public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); activateWalkieKey = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("ReservedWalkieSlot", "ActivateWalkieKey", "<Keyboard>/x", "This setting will be ignored if InputUtils is installed and enabled. (I recommend running InputUtils to edit keybinds in the in-game settings)"); hideWalkieMeshShoulder = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("ReservedWalkieSlot", "HideWalkieOnShoulder", false, "Hides the walkie mesh while on your shoulder. Only applies in scenarios where you can view your player in third person."); activateWalkieDisplayName = GetDisplayName(activateWalkieKey.Value); currentConfigEntries.Add(((ConfigEntryBase)activateWalkieKey).Definition.Key, (ConfigEntryBase)(object)activateWalkieKey); currentConfigEntries.Add(((ConfigEntryBase)hideWalkieMeshShoulder).Definition.Key, (ConfigEntryBase)(object)hideWalkieMeshShoulder); TryRemoveOldConfigSettings(); } public static string GetDisplayName(string key) { key = key.Replace("<Keyboard>/", ""); key = key.Replace("<Mouse>/", ""); string text = key; text = text.Replace("leftAlt", "Alt"); text = text.Replace("rightAlt", "Alt"); text = text.Replace("leftCtrl", "Ctrl"); text = text.Replace("rightCtrl", "Ctrl"); text = text.Replace("leftShift", "Shift"); text = text.Replace("rightShift", "Shift"); text = text.Replace("leftButton", "LMB"); text = text.Replace("rightButton", "RMB"); return text.Replace("middleButton", "MMB"); } public static void TryRemoveOldConfigSettings() { HashSet<string> hashSet = new HashSet<string>(); HashSet<string> hashSet2 = new HashSet<string>(); foreach (ConfigEntryBase value in currentConfigEntries.Values) { hashSet.Add(value.Definition.Section); hashSet2.Add(value.Definition.Key); } try { Plugin.Log("Cleaning old config entries"); ConfigFile config = ((BaseUnityPlugin)Plugin.instance).Config; string configFilePath = config.ConfigFilePath; if (!File.Exists(configFilePath)) { return; } string text = File.ReadAllText(configFilePath); string[] array = File.ReadAllLines(configFilePath); string text2 = ""; for (int i = 0; i < array.Length; i++) { array[i] = array[i].Replace("\n", ""); if (array[i].Length <= 0) { continue; } if (array[i].StartsWith("[")) { if (text2 != "" && !hashSet.Contains(text2)) { text2 = "[" + text2 + "]"; int num = text.IndexOf(text2); int num2 = text.IndexOf(array[i]); text = text.Remove(num, num2 - num); } text2 = array[i].Replace("[", "").Replace("]", "").Trim(); } else { if (!(text2 != "")) { continue; } if (i <= array.Length - 4 && array[i].StartsWith("##")) { int j; for (j = 1; i + j < array.Length && array[i + j].Length > 3; j++) { } if (hashSet.Contains(text2)) { int num3 = array[i + j - 1].IndexOf("="); string item = array[i + j - 1].Substring(0, num3 - 1); if (!hashSet2.Contains(item)) { int num4 = text.IndexOf(array[i]); int num5 = text.IndexOf(array[i + j - 1]) + array[i + j - 1].Length; text = text.Remove(num4, num5 - num4); } } i += j - 1; } else if (array[i].Length > 3) { text = text.Replace(array[i], ""); } } } if (!hashSet.Contains(text2)) { text2 = "[" + text2 + "]"; int num6 = text.IndexOf(text2); text = text.Remove(num6, text.Length - num6); } while (text.Contains("\n\n\n")) { text = text.Replace("\n\n\n", "\n\n"); } File.WriteAllText(configFilePath, text); config.Reload(); } catch { } } } [BepInPlugin("FlipMods.ReservedWalkieSlot", "ReservedWalkieSlot", "1.5.4")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class Plugin : BaseUnityPlugin { public static Plugin instance; private Harmony _harmony; public static ReservedItemInfo walkieInfo = new ReservedItemInfo("Walkie-talkie", 100, true, true, true, true); private void Awake() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown instance = this; ConfigSettings.BindConfigSettings(); _harmony = new Harmony("ReservedWalkieSlot"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"ReservedWalkieSlot loaded"); } public static bool IsModLoaded(string guid) { return Chainloader.PluginInfos.ContainsKey(guid); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.ReservedWalkieSlot"; public const string PLUGIN_NAME = "ReservedWalkieSlot"; public const string PLUGIN_VERSION = "1.5.4"; } } namespace ReservedWalkieSlot.Patches { [HarmonyPatch] internal static class ReservedWalkieSlotPatcher { private static Vector3 localPlayerShoulderPositionOffset = new Vector3(0.125f, 0.4f, 0.125f); private static Vector3 playerShoulderPositionOffset = new Vector3(0.15f, -0.05f, 0.25f); private static Vector3 playerShoulderRotationOffset = new Vector3(0f, 270f, 100f); private static string originalControlTooltip = ""; public static PlayerControllerB localPlayerController => PlayerPatcher.localPlayerController; public static WalkieTalkie GetMainWalkie(PlayerControllerB playerController) { return GetCurrentlySelectedWalkie(playerController) ?? GetReservedWalkie(playerController); } public static WalkieTalkie GetReservedWalkie(PlayerControllerB playerController) { return (WalkieTalkie)(SyncManager.syncReservedItemsList.Contains(Plugin.walkieInfo) ? /*isinst with value type is only supported in some contexts*/: null); } public static WalkieTalkie GetCurrentlySelectedWalkie(PlayerControllerB playerController) { return (WalkieTalkie)((playerController.currentItemSlot >= 0 && playerController.currentItemSlot < playerController.ItemSlots.Length) ? /*isinst with value type is only supported in some contexts*/: null); } [HarmonyPatch(typeof(WalkieTalkie), "PocketItem")] [HarmonyPostfix] public static void OnPocketWalkie(WalkieTalkie __instance) { if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null)) { if ((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) { ((Component)((Component)__instance).GetComponentInChildren<Renderer>()).gameObject.layer = 23; } else { ((Component)((Component)__instance).GetComponentInChildren<Renderer>()).gameObject.layer = 6; } ((GrabbableObject)__instance).parentObject = ((Component)((GrabbableObject)__instance).playerHeldBy.playerBadgeMesh).transform.parent; } } [HarmonyPatch(typeof(WalkieTalkie), "EquipItem")] [HarmonyPostfix] public static void OnEquipWalkie(WalkieTalkie __instance) { if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null)) { ((Component)((Component)__instance).GetComponentInChildren<Renderer>()).gameObject.layer = 6; ((GrabbableObject)__instance).parentObject = (((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)(object)localPlayerController) ? ((GrabbableObject)__instance).playerHeldBy.localItemHolder : ((GrabbableObject)__instance).playerHeldBy.serverItemHolder); } } [HarmonyPatch(typeof(WalkieTalkie), "DiscardItem")] [HarmonyPostfix] public static void OnDiscardWalkie(WalkieTalkie __instance) { ((Component)((Component)__instance).GetComponentInChildren<Renderer>()).gameObject.layer = 6; } [HarmonyPatch(typeof(GrabbableObject), "LateUpdate")] [HarmonyPostfix] public static void SetPositionOffset(GrabbableObject __instance) { //IL_0076: 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_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) if (__instance is WalkieTalkie && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance.parentObject != (Object)null && __instance.isPocketed && (Object)(object)__instance == (Object)(object)GetReservedWalkie(__instance.playerHeldBy) && (Object)(object)__instance != (Object)(object)GetCurrentlySelectedWalkie(__instance.playerHeldBy)) { Transform transform = ((Component)__instance.parentObject).transform; ((Component)__instance).transform.rotation = ((Component)__instance.parentObject).transform.rotation * Quaternion.Euler(playerShoulderRotationOffset); ((Component)__instance).transform.position = transform.position + transform.rotation * playerShoulderPositionOffset; } } [HarmonyPatch(typeof(GrabbableObject), "EnableItemMeshes")] [HarmonyPrefix] public static void OnEnableItemMeshes(ref bool enable, GrabbableObject __instance) { if (__instance is WalkieTalkie && (Object)(object)__instance.playerHeldBy != (Object)null && (Object)(object)__instance == (Object)(object)GetReservedWalkie(__instance.playerHeldBy) && !ConfigSettings.hideWalkieMeshShoulder.Value) { enable = true; } } } } namespace ReservedWalkieSlot.Input { internal class IngameKeybinds : LcInputActions { internal static IngameKeybinds Instance = new IngameKeybinds(); [InputAction("<Keyboard>/x", Name = "[ReservedItemSlots]\nActivate walkie")] public InputAction ActivateWalkieHotkey { get; set; } internal static InputActionAsset GetAsset() { return ((LcInputActions)Instance).Asset; } } internal class InputUtilsCompat { internal static InputActionAsset Asset => IngameKeybinds.GetAsset(); internal static bool Enabled => Plugin.IsModLoaded("com.rune580.LethalCompanyInputUtils"); public static InputAction ActivateWalkieHotkey => IngameKeybinds.Instance.ActivateWalkieHotkey; } [HarmonyPatch] internal static class Keybinds { public static InputActionAsset Asset; public static InputActionMap ActionMap; private static InputAction ActivateWalkieAction; public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController; [HarmonyPatch(typeof(PreInitSceneScript), "Awake")] [HarmonyPrefix] public static void AddToKeybindMenu() { InitKeybinds(); } public static void InitKeybinds() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: 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) Plugin.Log("Initializing hotkeys."); if (InputUtilsCompat.Enabled) { Asset = InputUtilsCompat.Asset; ActionMap = Asset.actionMaps[0]; ActivateWalkieAction = InputUtilsCompat.ActivateWalkieHotkey; } else { Asset = new InputActionAsset(); ActionMap = new InputActionMap("ReservedItemSlots"); InputActionSetupExtensions.AddActionMap(Asset, ActionMap); ActivateWalkieAction = InputActionSetupExtensions.AddAction(ActionMap, "ReservedItemSlots.ActivateWalkie", (InputActionType)0, ConfigSettings.activateWalkieKey.Value, (string)null, (string)null, (string)null, (string)null); } } [HarmonyPatch(typeof(StartOfRound), "OnEnable")] [HarmonyPostfix] public static void OnEnable() { Asset.Enable(); ActivateWalkieAction.performed += OnPressWalkieButtonPerformed; ActivateWalkieAction.canceled += OnReleaseWalkieButtonPerformed; } [HarmonyPatch(typeof(StartOfRound), "OnDisable")] [HarmonyPostfix] public static void OnDisable() { Asset.Disable(); ActivateWalkieAction.performed -= OnPressWalkieButtonPerformed; ActivateWalkieAction.canceled -= OnReleaseWalkieButtonPerformed; } private static void OnPressWalkieButtonPerformed(CallbackContext context) { if ((Object)(object)localPlayerController == (Object)null || !localPlayerController.isPlayerControlled || (((NetworkBehaviour)localPlayerController).IsServer && !localPlayerController.isHostPlayerObject)) { return; } WalkieTalkie mainWalkie = ReservedWalkieSlotPatcher.GetMainWalkie(localPlayerController); if (((CallbackContext)(ref context)).performed && !((Object)(object)mainWalkie == (Object)null) && ((GrabbableObject)mainWalkie).isBeingUsed) { float num = (float)Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").GetValue(); if (!(num < 0.075f)) { Plugin.Log("Talking into walkie"); ShipBuildModeManager.Instance.CancelBuildMode(true); ((GrabbableObject)mainWalkie).UseItemOnClient(true); Traverse.Create((object)localPlayerController).Field("timeSinceSwitchingSlots").SetValue((object)0); } } } private static void OnReleaseWalkieButtonPerformed(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && localPlayerController.isPlayerControlled && (!((NetworkBehaviour)localPlayerController).IsServer || localPlayerController.isHostPlayerObject)) { WalkieTalkie mainWalkie = ReservedWalkieSlotPatcher.GetMainWalkie(localPlayerController); if (((CallbackContext)(ref context)).canceled && !((Object)(object)mainWalkie == (Object)null)) { Plugin.Log("Not talking into walkie"); ShipBuildModeManager.Instance.CancelBuildMode(true); ((GrabbableObject)mainWalkie).UseItemOnClient(false); } } } } }
plugins/RollingGiant/RollingGiant.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using RollingGiant; using RollingGiant.Patches; using RollingGiant.Settings; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.InputSystem; using UnityEngine.Pool; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("RollingGiant")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("RollingGiant")] [assembly: AssemblyTitle("RollingGiant")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<RollingGiantAiType>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals<RollingGiantAiType>(); NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); } } 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 RollingGiant { public class NetworkHandler : NetworkBehaviour { private static readonly List<RollingGiantAiType> _aiTypes = Enum.GetValues(typeof(RollingGiantAiType)).Cast<RollingGiantAiType>().ToList(); private NetworkVariable<RollingGiantAiType> _aiType = new NetworkVariable<RollingGiantAiType>((RollingGiantAiType)0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private static InputAction _gotoPreviousAiType; private static InputAction _gotoNextAiType; private static InputAction _reloadConfig; public static NetworkHandler Instance { get; private set; } public static RollingGiantAiType AiType => Instance._aiType.Value; public override void OnNetworkSpawn() { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { if (Object.op_Implicit((Object)(object)Instance)) { ((Component)Instance).gameObject.GetComponent<NetworkObject>().Despawn(true); } _aiType.Value = CustomConfig.AiType.GetFirst(); } Instance = this; InputAction gotoPreviousAiType = _gotoPreviousAiType; if (gotoPreviousAiType != null) { gotoPreviousAiType.Disable(); } InputAction gotoPreviousAiType2 = _gotoPreviousAiType; if (gotoPreviousAiType2 != null) { gotoPreviousAiType2.Dispose(); } _gotoPreviousAiType = new InputAction("gotoPreviousAiType", (InputActionType)1, CustomConfig.GotoPreviousAiTypeKey.Value, (string)null, (string)null, (string)null); _gotoPreviousAiType.Enable(); InputAction gotoNextAiType = _gotoNextAiType; if (gotoNextAiType != null) { gotoNextAiType.Disable(); } InputAction gotoNextAiType2 = _gotoNextAiType; if (gotoNextAiType2 != null) { gotoNextAiType2.Dispose(); } _gotoNextAiType = new InputAction("gotoNextAiType", (InputActionType)1, CustomConfig.GotoNextAiTypeKey.Value, (string)null, (string)null, (string)null); _gotoNextAiType.Enable(); InputAction reloadConfig = _reloadConfig; if (reloadConfig != null) { reloadConfig.Disable(); } InputAction reloadConfig2 = _reloadConfig; if (reloadConfig2 != null) { reloadConfig2.Dispose(); } _reloadConfig = new InputAction("reloadConfig", (InputActionType)1, CustomConfig.ReloadConfigKey.Value, (string)null, (string)null, (string)null); _reloadConfig.Enable(); ((NetworkBehaviour)this).OnNetworkSpawn(); } public void SetAiType(RollingGiantAiType aiType) { if (((NetworkBehaviour)this).IsServer || ((NetworkBehaviour)this).IsHost) { SetNewAiType(aiType, showTip: false); } } private void Update() { if (!((NetworkBehaviour)this).IsServer && !((NetworkBehaviour)this).IsHost) { return; } if (_gotoPreviousAiType.WasPressedThisFrame()) { int num = _aiTypes.IndexOf(_aiType.Value) - 1; if (num < 0) { num = Enum.GetValues(typeof(RollingGiantAiType)).Length - 1; } SetNewAiType(_aiTypes[num]); } else if (_gotoNextAiType.WasPressedThisFrame()) { int num2 = _aiTypes.IndexOf(_aiType.Value) + 1; if (num2 >= _aiTypes.Count) { num2 = 0; } SetNewAiType(_aiTypes[num2]); } else if (_reloadConfig.WasPressedThisFrame()) { Plugin.Config.Reload(); SyncedInstance<CustomConfig>.Instance.Reload(); _aiType.Value = CustomConfig.AiType.GetFirst(); SetNewAiType(_aiType.Value); HUDManager.Instance.DisplayTip("Config reloaded", $"Ai defaulted to {_aiType.Value}", false, false, "LC_Tip1"); } } private void SetNewAiType(RollingGiantAiType aiType, bool showTip = true) { RollingGiantAiType value = _aiType.Value; _aiType.Value = aiType; CustomConfig.SetCurrentAi(); EmitSharedServerSettingsClientRpc(); if (Object.op_Implicit((Object)(object)HUDManager.Instance) && value != aiType && showTip) { HUDManager.Instance.DisplayTip("Rolling Giant AI changed", aiType.ToString(), false, false, "LC_Tip1"); } Plugin.Log.LogMessage((object)$"Rolling Giant AI changed: {aiType}"); } [ClientRpc] private void EmitSharedServerSettingsClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4257552972u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4257552972u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { CustomConfig.RequestSync(); } } } protected override void __initializeVariables() { if (_aiType == null) { throw new Exception("NetworkHandler._aiType cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)_aiType).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)_aiType, "_aiType"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)_aiType); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_NetworkHandler() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(4257552972u, new RpcReceiveHandler(__rpc_handler_4257552972)); } private static void __rpc_handler_4257552972(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).EmitSharedServerSettingsClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "NetworkHandler"; } } [BepInPlugin("nomnomab.rollinggiant", "Rolling Giant", "2.3.0")] public class Plugin : BaseUnityPlugin { public const string PluginGuid = "nomnomab.rollinggiant"; public const string PluginName = "Rolling Giant"; public const string PluginVersion = "2.3.0"; private const int SaveFileVersion = 5; public static string PluginDirectory; public static AssetBundle Bundle; public static EnemyType EnemyTypeInside; public static EnemyType EnemyTypeOutside; public static EnemyType EnemyTypeOutsideDaytime; public static TerminalNode EnemyTerminalNode; public static TerminalKeyword EnemyTerminalKeyword; public static AudioClip WalkSound; public static AudioClip[] StopSounds; public static GameObject PlayerRagdoll; public static Item PosterItem; public static Material BlackAndWhiteMaterial; internal static ManualLogSource Log; public static CustomConfig CustomConfig { get; private set; } public static ConfigFile Config { get; private set; } private void Awake() { Config = ((BaseUnityPlugin)this).Config; Log = ((BaseUnityPlugin)this).Logger; PluginDirectory = ((BaseUnityPlugin)this).Info.Location; LoadSettings(); RemoveOldSettings(); LoadAssets(); LoadNetWeaver(); Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin RollingGiant is loaded!"); } private void LoadNetWeaver() { Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { try { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0) { methodInfo.Invoke(null, null); } } } catch { Log.LogWarning((object)("NetWeaver is skipping " + type.FullName)); } } } private void LoadSettings() { CustomConfig = new CustomConfig(((BaseUnityPlugin)this).Config); } private void RemoveOldSettings() { int value = ((BaseUnityPlugin)this).Config.Bind<int>("z_Ignore", "__version", 0, "The version of this config file. Do not change this.").Value; if (value != 5) { Log.LogMessage((object)$"Removing old settings... ({value} != {5})"); string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath; string destFileName = configFilePath + ".bak"; File.Copy(configFilePath, destFileName, overwrite: true); File.WriteAllText(configFilePath, ""); ((BaseUnityPlugin)this).Config.Reload(); CustomConfig.Reload(setValues: false); ((BaseUnityPlugin)this).Config.Bind<int>("z_Ignore", "__version", 5, (ConfigDescription)null).Value = 5; CustomConfig.AssignFromSaved(); ((BaseUnityPlugin)this).Config.Save(); } else { Log.LogMessage((object)$"Settings version is up to date ({value} == {5})"); } } private void LoadAssets() { //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: 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_01d3: Unknown result type (might be due to invalid IL or missing references) try { Bundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(PluginDirectory) ?? throw new Exception("Failed to get directory name!"), "rollinggiant")); EnemyTypeInside = Bundle.LoadAsset<EnemyType>("Assets/RollingGiant/Data/RollingGiant_EnemyType.asset"); EnemyTypeOutside = Bundle.LoadAsset<EnemyType>("Assets/RollingGiant/Data/RollingGiant_EnemyType_Outside.asset"); EnemyTypeOutsideDaytime = Bundle.LoadAsset<EnemyType>("Assets/RollingGiant/Data/RollingGiant_EnemyType_Outside_Daytime.asset"); EnemyTypeInside.MaxCount = CustomConfig.MaxPerLevel; EnemyTypeOutside.MaxCount = CustomConfig.MaxPerLevel; EnemyTypeOutsideDaytime.MaxCount = CustomConfig.MaxPerLevel; NetworkPatches.RegisterPrefab(EnemyTypeInside.enemyPrefab); NetworkPatches.RegisterPrefab(EnemyTypeOutside.enemyPrefab); NetworkPatches.RegisterPrefab(EnemyTypeOutsideDaytime.enemyPrefab); EnemyTerminalNode = Bundle.LoadAsset<TerminalNode>("Assets/RollingGiant/Data/RollingGiant_TerminalNode.asset"); EnemyTerminalKeyword = Bundle.LoadAsset<TerminalKeyword>("Assets/RollingGiant/Data/RollingGiant_TerminalKeyword.asset"); } catch (Exception arg) { Log.LogError((object)$"Failed to load asset bundle! {arg}"); } try { WalkSound = Bundle.LoadAsset<AudioClip>("Assets/RollingGiant/Audio/MovingLoop.wav"); StopSounds = (AudioClip[])(object)new AudioClip[5]; for (int i = 0; i < 5; i++) { StopSounds[i] = Bundle.LoadAsset<AudioClip>($"Assets/RollingGiant/Audio/Stopped{i + 1}.wav"); } PlayerRagdoll = Bundle.LoadAsset<GameObject>("Assets/RollingGiant/PlayerRagdollRollingGiant Variant.prefab"); PlayerRagdoll.AddComponent<RollingGiantDeadBody>(); PosterItem = Bundle.LoadAsset<Item>("Assets/RollingGiant/Data/RollingGiant_PosterItem.asset"); Item posterItem = PosterItem; posterItem.rotationOffset += new Vector3(45f, 0f, 0f); Item posterItem2 = PosterItem; posterItem2.positionOffset += new Vector3(-0.1f, -0.12f, 0.15f); Object.Destroy((Object)(object)PosterItem.spawnPrefab.GetComponent<PhysicsProp>()); PosterItem.spawnPrefab.AddComponent<Poster>().Init(); NetworkPatches.RegisterPrefab(PosterItem.spawnPrefab); BlackAndWhiteMaterial = Bundle.LoadAsset<Material>("Assets/RollingGiant/Materials/RollingGiant_Gray.mat"); } catch (Exception arg2) { Log.LogError((object)$"Failed to load assets! {arg2}"); } } } [Flags] public enum RollingGiantAiType { Coilhead = 1, InverseCoilhead = 2, RandomlyMoveWhileLooking = 4, LookingTooLongKeepsAgro = 8, FollowOnceAgro = 0x10, OnceSeenAgroAfterTimer = 0x20 } public static class RollingGiantAiTypeExtensions { public static RollingGiantAiType GetFirst(this RollingGiantAiType aiType) { RollingGiantAiType[] array = Enum.GetValues(typeof(RollingGiantAiType)).Cast<RollingGiantAiType>().ToArray(); foreach (RollingGiantAiType rollingGiantAiType in array) { if ((aiType & rollingGiantAiType) == rollingGiantAiType) { return rollingGiantAiType; } } return aiType; } public static RollingGiantAiType GetRandom(this RollingGiantAiType aiType) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) List<RollingGiantAiType> list = default(List<RollingGiantAiType>); PooledObject<List<RollingGiantAiType>> val = CollectionPool<List<RollingGiantAiType>, RollingGiantAiType>.Get(ref list); try { RollingGiantAiType[] array = Enum.GetValues(typeof(RollingGiantAiType)).Cast<RollingGiantAiType>().ToArray(); foreach (RollingGiantAiType rollingGiantAiType in array) { if ((aiType & rollingGiantAiType) == rollingGiantAiType) { list.Add(rollingGiantAiType); } } RollingGiantAiType result = aiType; if (list.Count > 1) { result = list[Random.Range(0, list.Count)]; } else if (list.Count == 0) { result = array[Random.Range(1, array.Length)]; } return result; } finally { ((IDisposable)val).Dispose(); } } } public class Poster : PhysicsProp { public void Init() { ((GrabbableObject)this).grabbable = true; ((GrabbableObject)this).itemProperties = Plugin.PosterItem; ((GrabbableObject)this).isInFactory = true; ((GrabbableObject)this).mainObjectRenderer = ((Component)this).GetComponent<MeshRenderer>(); ((GrabbableObject)this).grabbableToEnemies = true; } protected override void __initializeVariables() { ((PhysicsProp)this).__initializeVariables(); } protected internal override string __getTypeName() { return "Poster"; } } public class RollingGiantAI : EnemyAI { private const float ROAMING_AUDIO_PERCENT = 0.4f; [SerializeField] private AISearchRoutine _searchForPlayers; [SerializeField] private Collider _mainCollider; [SerializeField] private AudioClip[] _stopNoises; private AudioSource _rollingSFX; private NetworkVariable<float> _velocity = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private float _timeSinceHittingPlayer; private bool _wantsToChaseThisClient; private bool _hasEnteredChaseState; private bool _wasStopped; private bool _wasFeared; private bool _isAgro; private float _lastSpeed; private float _audioFade; private float _waitTimer; private float _moveTimer; private float _lookTimer; private float _agroTimer; private float _springVelocity; private static SharedAiSettings _sharedAiSettings => CustomConfig.SharedAiSettings; private static float NextDouble() { if (!Object.op_Implicit((Object)(object)RoundManager.Instance) || RoundManager.Instance.LevelRandom == null) { return Random.value; } return (float)RoundManager.Instance.LevelRandom.NextDouble(); } public override void Start() { ((EnemyAI)this).Start(); Init(); if (((NetworkBehaviour)this).IsHost || ((NetworkBehaviour)this).IsOwner) { AssignInitData_LocalClient(); } Plugin.Log.LogInfo((object)$"Rolling giant spawned with ai type: {NetworkHandler.AiType}, owner? {((NetworkBehaviour)this).IsOwner}"); } private void Init() { base.agent = ((Component)this).gameObject.GetComponentInChildren<NavMeshAgent>(); _rollingSFX = ((Component)((Component)this).transform.Find("RollingSFX")).GetComponent<AudioSource>(); AudioMixerGroup outputAudioMixerGroup = SoundManager.Instance.diageticMixer.outputAudioMixerGroup; _rollingSFX.outputAudioMixerGroup = outputAudioMixerGroup; base.creatureVoice.outputAudioMixerGroup = outputAudioMixerGroup; base.creatureSFX.outputAudioMixerGroup = outputAudioMixerGroup; _rollingSFX.loop = true; _rollingSFX.clip = Plugin.WalkSound; float time = NextDouble() * Plugin.WalkSound.length; float pitch = Mathf.Lerp(0.96f, 1.05f, NextDouble()); _rollingSFX.time = time; _rollingSFX.pitch = pitch; _rollingSFX.volume = 0f; _rollingSFX.Play(); } public override void DaytimeEnemyLeave() { ((EnemyAI)this).DaytimeEnemyLeave(); Renderer[] componentsInChildren = ((Component)((Component)this).transform).GetComponentsInChildren<Renderer>(); foreach (Renderer val in componentsInChildren) { if (!(((Object)val).name == "object_3")) { val.sharedMaterial = Plugin.BlackAndWhiteMaterial; } } _mainCollider.isTrigger = true; } public override void DoAIInterval() { //IL_008c: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //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) if (base.daytimeEnemyLeaving) { _mainCollider.isTrigger = true; return; } ((EnemyAI)this).DoAIInterval(); if (StartOfRound.Instance.livingPlayers == 0 || base.isEnemyDead) { return; } switch (base.currentBehaviourStateIndex) { case 0: { if (!((NetworkBehaviour)this).IsServer) { ((EnemyAI)this).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId); break; } for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i]; if (((EnemyAI)this).PlayerIsTargetable(val, false, base.isOutside) && !Physics.Linecast(((Component)this).transform.position + Vector3.up * 0.5f, ((Component)val.gameplayCamera).transform.position, StartOfRound.Instance.collidersAndRoomMaskAndDefault) && (double)Vector3.Distance(((Component)this).transform.position, ((Component)val).transform.position) < 30.0) { ((EnemyAI)this).SwitchToBehaviourState(1); return; } } if (!_searchForPlayers.inProgress) { ((EnemyAI)this).StartSearch(((Component)this).transform.position, _searchForPlayers); } break; } case 1: if (!TargetClosestPlayer()) { base.movingTowardsTargetPlayer = false; if (!_searchForPlayers.inProgress) { ((EnemyAI)this).SwitchToBehaviourState(0); ((EnemyAI)this).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId); } } else if (_searchForPlayers.inProgress) { ((EnemyAI)this).StopSearch(_searchForPlayers, true); base.movingTowardsTargetPlayer = true; } break; } } public override void Update() { //IL_0031: 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_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0128: 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_03be: Unknown result type (might be due to invalid IL or missing references) //IL_03c9: Unknown result type (might be due to invalid IL or missing references) //IL_03ce: Unknown result type (might be due to invalid IL or missing references) //IL_03d0: Unknown result type (might be due to invalid IL or missing references) //IL_03d2: Unknown result type (might be due to invalid IL or missing references) //IL_03d7: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_0401: Unknown result type (might be due to invalid IL or missing references) //IL_0406: Unknown result type (might be due to invalid IL or missing references) //IL_0418: Unknown result type (might be due to invalid IL or missing references) if (base.daytimeEnemyLeaving) { _mainCollider.isTrigger = true; return; } Vector3 velocity2; if (((NetworkBehaviour)this).IsHost || ((NetworkBehaviour)this).IsServer) { NetworkVariable<float> velocity = _velocity; velocity2 = base.agent.velocity; velocity.Value = ((Vector3)(ref velocity2)).magnitude; } ((EnemyAI)this).Update(); if (base.isEnemyDead) { return; } velocity2 = base.agent.velocity; _lastSpeed = ((Vector3)(ref velocity2)).magnitude; CalculateAgentSpeed(); _timeSinceHittingPlayer += Time.deltaTime; _mainCollider.isTrigger = !_wasStopped; float value = _velocity.Value; _rollingSFX.volume = Mathf.Lerp(0f, Mathf.Clamp01(0.4f * value + 0.05f), value / _sharedAiSettings.moveSpeed); GameNetworkManager instance = GameNetworkManager.Instance; PlayerControllerB localPlayerController = instance.localPlayerController; if (_wasStopped && !_wasFeared && localPlayerController.HasLineOfSightToPosition(base.eye.position, 70f, 25, -1f)) { _wasFeared = true; float num = Vector3.Distance(((Component)this).transform.position, ((Component)localPlayerController).transform.position); if (num < 4f) { instance.localPlayerController.JumpToFearLevel(0.9f, true); } else if (num < 9f) { instance.localPlayerController.JumpToFearLevel(0.4f, true); } if (_lastSpeed > 1f) { RoundManager.PlayRandomClip(base.creatureVoice, _stopNoises, false, 1f, 0); } } switch (base.currentBehaviourStateIndex) { case 0: if (_hasEnteredChaseState) { _hasEnteredChaseState = false; _wantsToChaseThisClient = false; _wasStopped = false; _wasFeared = false; _isAgro = false; _agroTimer = 0f; _waitTimer = 0f; _moveTimer = 0f; _lookTimer = 0f; _springVelocity = 0f; base.agent.stoppingDistance = 0f; base.agent.speed = _sharedAiSettings.moveSpeed; base.agent.acceleration = 200f; } if (((NetworkBehaviour)this).IsOwner && TargetClosestPlayer(1.5f, requireLineOfSight: true) && (Object)(object)base.targetPlayer == (Object)(object)localPlayerController && !_wantsToChaseThisClient) { _wantsToChaseThisClient = true; BeginChasingPlayer_ServerRpc((int)base.targetPlayer.playerClientId); ((EnemyAI)this).ChangeOwnershipOfEnemy(base.targetPlayer.actualClientId); } break; case 1: { if (!_hasEnteredChaseState) { _hasEnteredChaseState = true; _wantsToChaseThisClient = false; _wasStopped = false; _wasFeared = false; _isAgro = false; _agroTimer = 0f; _waitTimer = 0f; _moveTimer = 0f; _lookTimer = 0f; _springVelocity = 0f; base.agent.stoppingDistance = 0f; base.agent.speed = 0f; base.agent.acceleration = 200f; } if (base.stunNormalizedTimer > 0f) { break; } PlayerControllerB targetPlayer = base.targetPlayer; if (((NetworkBehaviour)this).IsOwner) { if (!TargetClosestPlayer()) { EndChasingPlayer_ServerRpc(); break; } if (_wasStopped && _sharedAiSettings.rotateToLookAtPlayer) { if (_lookTimer >= _sharedAiSettings.delayBeforeLookingAtPlayer) { Vector3 position = ((Component)base.targetPlayer).transform.position; Vector3 position2 = ((Component)this).transform.position; Vector3 val = position - position2; val.y = 0f; ((Vector3)(ref val)).Normalize(); Quaternion val2 = Quaternion.LookRotation(val); ((Component)this).transform.rotation = Quaternion.Lerp(((Component)this).transform.rotation, val2, Time.deltaTime / _sharedAiSettings.lookAtPlayerDuration); } } else if (!_wasStopped) { _ = _sharedAiSettings.rotateToLookAtPlayer; } } RollingGiantAiType aiType = NetworkHandler.AiType; PlayerControllerB closestPlayer; switch (aiType) { case RollingGiantAiType.Coilhead: if (AmIBeingLookedAt(out closestPlayer)) { _wasStopped = true; return; } break; case RollingGiantAiType.InverseCoilhead: if (!AmIBeingLookedAt(out closestPlayer) && _isAgro) { _wasStopped = true; return; } break; case RollingGiantAiType.RandomlyMoveWhileLooking: if (AmIBeingLookedAt(out closestPlayer) && _moveTimer <= 0f) { _wasStopped = true; return; } break; case RollingGiantAiType.LookingTooLongKeepsAgro: if (AmIBeingLookedAt(out closestPlayer) && _agroTimer < _sharedAiSettings.lookTimeBeforeAgro) { _wasStopped = true; return; } break; case RollingGiantAiType.OnceSeenAgroAfterTimer: if (_isAgro && _waitTimer >= 0f) { _wasStopped = true; return; } break; default: Plugin.Log.LogWarning((object)$"Unknown ai type: {aiType}"); break; case RollingGiantAiType.FollowOnceAgro: break; } _wasStopped = false; _wasFeared = false; if (((NetworkBehaviour)this).IsOwner && !((Object)(object)targetPlayer == (Object)(object)base.targetPlayer) && !((Object)(object)base.targetPlayer != (Object)(object)localPlayerController)) { ((EnemyAI)this).SetMovingTowardsTargetPlayer(base.targetPlayer); ((EnemyAI)this).ChangeOwnershipOfEnemy(base.targetPlayer.actualClientId); } break; } } } public bool TargetClosestPlayer(float bufferDistance = 1.5f, bool requireLineOfSight = false, float viewWidth = 70f) { //IL_0047: 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_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) base.mostOptimalDistance = 2000f; PlayerControllerB targetPlayer = base.targetPlayer; base.targetPlayer = null; for (int i = 0; i < StartOfRound.Instance.connectedPlayersAmount + 1; i++) { PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[i]; if (((EnemyAI)this).PlayerIsTargetable(val, false, base.isOutside) && !((EnemyAI)this).PathIsIntersectedByLineOfSight(((Component)val).transform.position, false, false) && (!requireLineOfSight || ((EnemyAI)this).HasLineOfSightToPosition(((Component)val.gameplayCamera).transform.position, viewWidth, 40, -1f))) { base.tempDist = Vector3.Distance(((Component)this).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position); if ((double)base.tempDist < (double)base.mostOptimalDistance) { base.mostOptimalDistance = base.tempDist; base.targetPlayer = StartOfRound.Instance.allPlayerScripts[i]; } } } if (Object.op_Implicit((Object)(object)base.targetPlayer) && (double)bufferDistance > 0.0 && Object.op_Implicit((Object)(object)targetPlayer) && (double)Mathf.Abs(base.mostOptimalDistance - Vector3.Distance(((Component)this).transform.position, ((Component)targetPlayer).transform.position)) < (double)bufferDistance) { base.targetPlayer = targetPlayer; } return Object.op_Implicit((Object)(object)base.targetPlayer); } private static float SmoothLerp(float a, float b, float t) { return a + t * t * (b - a); } public override void OnCollideWithPlayer(Collider other) { //IL_005b: 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) if (base.daytimeEnemyLeaving) { return; } ((EnemyAI)this).OnCollideWithPlayer(other); if (!(_timeSinceHittingPlayer < 0.6f)) { PlayerControllerB val = ((EnemyAI)this).MeetsStandardPlayerCollisionConditions(other, false, false); if (Object.op_Implicit((Object)(object)val)) { _timeSinceHittingPlayer = 0.2f; int num = StartOfRound.Instance.playerRagdolls.IndexOf(Plugin.PlayerRagdoll); val.DamagePlayer(90, true, true, (CauseOfDeath)4, num, false, default(Vector3)); base.agent.speed = 0f; GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(1f, true); } } } private void CalculateAgentSpeed() { if (base.stunNormalizedTimer >= 0f) { base.agent.speed = 0f; base.agent.acceleration = 200f; } else if (base.currentBehaviourStateIndex == 0) { base.agent.speed = ((_sharedAiSettings.moveAcceleration == 0f) ? _sharedAiSettings.moveSpeed : Mathf.Lerp(base.agent.speed, _sharedAiSettings.moveSpeed, Time.deltaTime / _sharedAiSettings.moveAcceleration)); base.agent.acceleration = 200f; } else { if (base.currentBehaviourStateIndex != 1) { return; } if (!IsAgentOnNavMesh(((Component)base.agent).gameObject)) { MoveAccelerate(); return; } PlayerControllerB closestPlayer; bool flag = AmIBeingLookedAt(out closestPlayer); if (flag) { _lookTimer += Time.deltaTime; } else { _lookTimer = 0f; } RollingGiantAiType aiType = NetworkHandler.AiType; switch (aiType) { case RollingGiantAiType.Coilhead: if (flag) { MoveDecelerate(); } else { MoveAccelerate(); } break; case RollingGiantAiType.InverseCoilhead: if (!flag && _isAgro) { MoveDecelerate(); break; } MoveAccelerate(); _isAgro = true; break; case RollingGiantAiType.RandomlyMoveWhileLooking: if (flag) { if (_waitTimer <= 0f && _moveTimer <= 0f) { GenerateWaitTime_LocalClient(); } if (_waitTimer > 0f && _moveTimer <= 0f) { MoveDecelerate(); _waitTimer -= Time.deltaTime; if (_waitTimer <= 0f) { GenerateMoveTime_LocalClient(); } break; } } MoveAccelerate(); if (_moveTimer > 0f) { _moveTimer -= Time.deltaTime; if (_moveTimer <= 0f) { GenerateWaitTime_LocalClient(); } } break; case RollingGiantAiType.LookingTooLongKeepsAgro: if (!_isAgro) { if (flag) { _agroTimer = Mathf.SmoothDamp(_agroTimer, _sharedAiSettings.lookTimeBeforeAgro + 0.5f, ref _springVelocity, 0.5f); if (_agroTimer >= _sharedAiSettings.lookTimeBeforeAgro) { _isAgro = true; } MoveDecelerate(); } else { _agroTimer = Mathf.Lerp(_agroTimer, 0f, Time.deltaTime / (_sharedAiSettings.lookTimeBeforeAgro / 2f)); } } else { MoveAccelerate(); } break; case RollingGiantAiType.FollowOnceAgro: if (!_isAgro && flag) { _isAgro = true; MoveDecelerate(); } else { MoveAccelerate(); } break; case RollingGiantAiType.OnceSeenAgroAfterTimer: if (!_isAgro) { if (flag) { _isAgro = true; GenerateWaitTime_LocalClient(); MoveDecelerate(); } } else if (_waitTimer >= 0f) { _waitTimer -= Time.deltaTime; _ = _waitTimer; _ = 0f; MoveDecelerate(); } else { MoveAccelerate(); } break; default: Plugin.Log.LogWarning((object)$"Unknown ai type: {aiType}"); break; } } } private void MoveAccelerate() { base.agent.speed = ((_sharedAiSettings.moveAcceleration == 0f) ? _sharedAiSettings.moveSpeed : Mathf.Lerp(base.agent.speed, _sharedAiSettings.moveSpeed, Time.deltaTime / _sharedAiSettings.moveAcceleration)); base.agent.acceleration = Mathf.Lerp(base.agent.acceleration, 200f, Time.deltaTime); } private void MoveDecelerate() { base.agent.speed = ((_sharedAiSettings.moveDeceleration == 0f) ? 0f : Mathf.Lerp(base.agent.speed, 0f, Time.deltaTime / _sharedAiSettings.moveDeceleration)); base.agent.acceleration = 200f; } private bool AmIBeingLookedAt(out PlayerControllerB closestPlayer) { //IL_0033: 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_0042: 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_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; float num = float.MaxValue; closestPlayer = null; PlayerControllerB[] array = allPlayerScripts; foreach (PlayerControllerB val in array) { if (((EnemyAI)this).PlayerIsTargetable(val, false, base.isOutside) && val.HasLineOfSightToPosition(((Component)this).transform.position + Vector3.up * 1.6f, 68f, 60, -1f)) { float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val).transform.position); if (num2 < num) { num = num2; closestPlayer = val; } } } return Object.op_Implicit((Object)(object)closestPlayer); } private bool IsAgentOnNavMesh(GameObject agentObject) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_0035: 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_004e: 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) Vector3 position = agentObject.transform.position; NavMeshHit val = default(NavMeshHit); if (NavMesh.SamplePosition(position, ref val, 3f, -1) && Mathf.Approximately(position.x, ((NavMeshHit)(ref val)).position.x) && Mathf.Approximately(position.z, ((NavMeshHit)(ref val)).position.z)) { return position.y >= ((NavMeshHit)(ref val)).position.y; } return false; } [ServerRpc(RequireOwnership = false)] private void BeginChasingPlayer_ServerRpc(int playerId) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(913739805u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 913739805u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { BeginChasingPlayer_ClientRpc(playerId); } } } [ClientRpc] private void BeginChasingPlayer_ClientRpc(int playerId) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2111596117u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2111596117u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { ((EnemyAI)this).SwitchToBehaviourStateOnLocalClient(1); PlayerControllerB movingTowardsTargetPlayer = StartOfRound.Instance.allPlayerScripts[playerId]; ((EnemyAI)this).SetMovingTowardsTargetPlayer(movingTowardsTargetPlayer); } } } [ServerRpc(RequireOwnership = false)] private void EndChasingPlayer_ServerRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3771085912u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3771085912u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { EndChasingPlayer_ClientRpc(); } } } [ClientRpc] private void EndChasingPlayer_ClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1947504516u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1947504516u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { base.moveTowardsDestination = false; base.movingTowardsTargetPlayer = false; ((EnemyAI)this).SwitchToBehaviourStateOnLocalClient(0); } } } [ServerRpc(RequireOwnership = false)] private void GenerateWaitTime_ServerRpc(float waitTime) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0083: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2506095827u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref waitTime, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2506095827u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { _waitTimer = waitTime; } } } private void GenerateWaitTime_LocalClient() { GenerateWaitTime_ServerRpc(_waitTimer = Mathf.Lerp(_sharedAiSettings.waitTimeMin, _sharedAiSettings.waitTimeMax, NextDouble())); } [ServerRpc(RequireOwnership = false)] private void GenerateMoveTime_ServerRpc(float moveTime) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0083: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2605455828u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref moveTime, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2605455828u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { _moveTimer = moveTime; GenerateMoveTime_ClientRpc(moveTime); } } } private void GenerateMoveTime_LocalClient() { GenerateMoveTime_ServerRpc(_moveTimer = Mathf.Lerp(_sharedAiSettings.randomMoveTimeMin, _sharedAiSettings.randomMoveTimeMax, NextDouble())); } [ClientRpc] private void GenerateMoveTime_ClientRpc(float moveTime) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0083: 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) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(4167209315u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref moveTime, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4167209315u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { _moveTimer = moveTime; } } } [ServerRpc(RequireOwnership = false)] private void AssignInitData_ServerRpc(float scale) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0083: 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_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2584131514u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref scale, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2584131514u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ((Component)base.agent).transform.localScale = Vector3.one * scale; AssignInitData_ClientRpc(scale); } } } private void AssignInitData_LocalClient() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) CustomConfig instance = SyncedInstance<CustomConfig>.Instance; float num = Mathf.Lerp(instance.GiantScaleMin, instance.GiantScaleMax, NextDouble()); ((Component)base.agent).transform.localScale = Vector3.one * num; AssignInitData_ServerRpc(num); } [ClientRpc] private void AssignInitData_ClientRpc(float scale) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: 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_0083: 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_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3644677666u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref scale, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3644677666u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Init(); ((Component)base.agent).transform.localScale = Vector3.one * scale; } } } protected override void __initializeVariables() { if (_velocity == null) { throw new Exception("RollingGiantAI._velocity cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)_velocity).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)_velocity, "_velocity"); ((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)_velocity); ((EnemyAI)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_RollingGiantAI() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(913739805u, new RpcReceiveHandler(__rpc_handler_913739805)); NetworkManager.__rpc_func_table.Add(2111596117u, new RpcReceiveHandler(__rpc_handler_2111596117)); NetworkManager.__rpc_func_table.Add(3771085912u, new RpcReceiveHandler(__rpc_handler_3771085912)); NetworkManager.__rpc_func_table.Add(1947504516u, new RpcReceiveHandler(__rpc_handler_1947504516)); NetworkManager.__rpc_func_table.Add(2506095827u, new RpcReceiveHandler(__rpc_handler_2506095827)); NetworkManager.__rpc_func_table.Add(2605455828u, new RpcReceiveHandler(__rpc_handler_2605455828)); NetworkManager.__rpc_func_table.Add(4167209315u, new RpcReceiveHandler(__rpc_handler_4167209315)); NetworkManager.__rpc_func_table.Add(2584131514u, new RpcReceiveHandler(__rpc_handler_2584131514)); NetworkManager.__rpc_func_table.Add(3644677666u, new RpcReceiveHandler(__rpc_handler_3644677666)); } private static void __rpc_handler_913739805(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int playerId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); target.__rpc_exec_stage = (__RpcExecStage)1; ((RollingGiantAI)(object)target).BeginChasingPlayer_ServerRpc(playerId); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2111596117(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int playerId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); target.__rpc_exec_stage = (__RpcExecStage)2; ((RollingGiantAI)(object)target).BeginChasingPlayer_ClientRpc(playerId); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3771085912(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)1; ((RollingGiantAI)(object)target).EndChasingPlayer_ServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1947504516(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)2; ((RollingGiantAI)(object)target).EndChasingPlayer_ClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2506095827(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { float waitTime = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref waitTime, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)1; ((RollingGiantAI)(object)target).GenerateWaitTime_ServerRpc(waitTime); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2605455828(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { float moveTime = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref moveTime, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)1; ((RollingGiantAI)(object)target).GenerateMoveTime_ServerRpc(moveTime); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_4167209315(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { float moveTime = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref moveTime, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)2; ((RollingGiantAI)(object)target).GenerateMoveTime_ClientRpc(moveTime); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2584131514(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { float scale = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref scale, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)1; ((RollingGiantAI)(object)target).AssignInitData_ServerRpc(scale); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3644677666(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { float scale = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref scale, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)2; ((RollingGiantAI)(object)target).AssignInitData_ClientRpc(scale); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "RollingGiantAI"; } } public class RollingGiantDeadBody : MonoBehaviour { } public static class Utility { public static object InvokeNotOverride(this MethodInfo methodInfo, object targetObject, params object[] arguments) { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 0) { if (arguments != null && arguments.Length != 0) { throw new Exception("Arguments cont doesn't match"); } } else if (parameters.Length != arguments.Length) { throw new Exception("Arguments cont doesn't match"); } Type returnType = null; if (methodInfo.ReturnType != typeof(void)) { returnType = methodInfo.ReturnType; } Type type = targetObject.GetType(); DynamicMethod dynamicMethod = new DynamicMethod("", returnType, new Type[2] { type, typeof(object) }, type); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); for (int i = 0; i < parameters.Length; i++) { ParameterInfo obj = parameters[i]; iLGenerator.Emit(OpCodes.Ldarg_1); iLGenerator.Emit(OpCodes.Ldc_I4_S, i); iLGenerator.Emit(OpCodes.Ldelem_Ref); Type parameterType = obj.ParameterType; if (parameterType.IsPrimitive) { iLGenerator.Emit(OpCodes.Unbox_Any, parameterType); } else if (!(parameterType == typeof(object))) { iLGenerator.Emit(OpCodes.Castclass, parameterType); } } iLGenerator.Emit(OpCodes.Call, methodInfo); iLGenerator.Emit(OpCodes.Ret); return dynamicMethod.Invoke(null, new object[2] { targetObject, arguments }); } } public static class PluginInfo { public const string PLUGIN_GUID = "RollingGiant"; public const string PLUGIN_NAME = "RollingGiant"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace RollingGiant.Settings { public struct SharedAiSettings : INetworkSerializable { public float moveSpeed; public float moveAcceleration; public float moveDeceleration; public bool rotateToLookAtPlayer; public float delayBeforeLookingAtPlayer; public float lookAtPlayerDuration; public float waitTimeMin; public float waitTimeMax; public float randomMoveTimeMin; public float randomMoveTimeMax; public float lookTimeBeforeAgro; public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_000a: 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_0020: 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_0036: 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_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0062: 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_0078: 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_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref moveSpeed, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref moveAcceleration, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref moveDeceleration, default(ForPrimitives)); ((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref rotateToLookAtPlayer, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref delayBeforeLookingAtPlayer, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref lookAtPlayerDuration, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref waitTimeMin, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref waitTimeMax, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref randomMoveTimeMin, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref randomMoveTimeMax, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref lookTimeBeforeAgro, default(ForPrimitives)); } public override string ToString() { return $"moveSpeed: {moveSpeed}, moveAcceleration: {moveAcceleration}, moveDeceleration: {moveDeceleration}, rotateToLookAtPlayer: {rotateToLookAtPlayer}, delayBeforeLookingAtPlayer: {delayBeforeLookingAtPlayer}, lookAtPlayerDuration: {lookAtPlayerDuration}, waitTimeMin: {waitTimeMin}, waitTimeMax: {waitTimeMax}, randomMoveTimeMin: {randomMoveTimeMin}, randomMoveTimeMax: {randomMoveTimeMax}, lookTimeBeforeAgro: {lookTimeBeforeAgro}"; } } [Serializable] public class CustomConfig : SyncedInstance<CustomConfig> { public const string ROLLINGGIANT_ONREQUESTCONFIGSYNC = "RollingGiant_OnRequestConfigSync"; public const string ROLLINGGIANT_ONRECEIVECONFIGSYNC = "RollingGiant_OnReceiveConfigSync"; private static ConfigFile _config; public const string Name1 = "1. General Settings"; public const string Name2 = "2. AI Settings"; public const string AiTypeDescription = "The AI type of the Rolling Giant.\n- Putting multiple will randomly choose between them each time you land on a moon\nCoilhead = Coilhead AI\nInverseCoilhead = Move when player is looking at it\nRandomlyMoveWhileLooking = Randomly move while the player is looking at it\nLookingTooLongKeepsAgro = If the player looks at it for too long it doesn't stop chasing\nFollowOnceAgro = Once the player is noticed, the Rolling Giant will follow the player constantly\nOnceSeenAgroAfterTimer = Once the player sees the Rolling Giant, it will chase the player after a timer"; public const string MoveSpeedDescription = "The speed of the Rolling Giant in m/s²."; public const string MoveAccelerationDescription = "How long it takes the Rolling Giant to get to its movement speed. in seconds"; public const string MoveDecelerationDescription = "How long it takes the Rolling Giant to stop moving in seconds."; public const string RotateToLookAtPlayerDescription = "If the Rolling Giant should rotate to look at the player."; public const string DelayBeforeLookingAtPlayerDescription = "The delay before the Rolling Giant looks at the player in seconds."; public const string LookAtPlayerDurationDescription = "The duration the Rolling Giant looks at the player in seconds."; public static SharedAiSettings SharedAiSettings { get; private set; } public static ConfigEntry<string> GotoPreviousAiTypeKey { get; private set; } public static ConfigEntry<string> GotoNextAiTypeKey { get; private set; } public static ConfigEntry<string> ReloadConfigKey { get; private set; } public static ConfigEntry<string> SpawnInEntry { get; private set; } public static ConfigEntry<bool> SpawnInAnyEntry { get; private set; } public static ConfigEntry<int> SpawnInAnyChanceEntry { get; private set; } public static ConfigEntry<bool> CanSpawnInsideEntry { get; private set; } public static ConfigEntry<bool> CanSpawnOutsideEntry { get; private set; } public static ConfigEntry<bool> DisableOutsideAtNightEntry { get; private set; } public static ConfigEntry<int> MaxPerLevelEntry { get; private set; } public static ConfigEntry<string> SpawnPosterInEntry { get; private set; } public float GiantScaleMin { get; private set; } public float GiantScaleMax { get; private set; } public static string SpawnIn { get; private set; } public static bool SpawnInAny { get; private set; } public static int SpawnInAnyChance { get; private set; } public static bool CanSpawnInside { get; private set; } public static bool CanSpawnOutside { get; private set; } public static bool DisableOutsideAtNight { get; private set; } public static int MaxPerLevel { get; private set; } public static string SpawnPosterIn { get; private set; } public static RollingGiantAiType AiType { get; internal set; } public float MoveSpeed { get; private set; } public float MoveAcceleration { get; private set; } public float MoveDeceleration { get; private set; } public bool RotateToLookAtPlayer { get; private set; } public float DelayBeforeLookingAtPlayer { get; private set; } public float LookAtPlayerDuration { get; private set; } public float RandomlyMoveWhenLooking_WaitTimeMin { get; private set; } public float RandomlyMoveWhenLooking_WaitTimeMax { get; private set; } public float RandomlyMoveWhenLooking_RandomMoveTimeMin { get; private set; } public float RandomlyMoveWhenLooking_RandomMoveTimeMax { get; private set; } public float LookingTooLongKeepsAgro_LookTimeBeforeAgro { get; private set; } public float OnceSeenAgroAfterTimer_WaitTimeMin { get; private set; } public float OnceSeenAgroAfterTimer_WaitTimeMax { get; private set; } public static ConfigEntry<float> GiantScaleMinEntry { get; private set; } public static ConfigEntry<float> GiantScaleMaxEntry { get; private set; } public static ConfigEntry<RollingGiantAiType> AiTypeEntry { get; private set; } public static ConfigEntry<float> MoveSpeedEntry { get; private set; } public static ConfigEntry<float> MoveAccelerationEntry { get; private set; } public static ConfigEntry<float> MoveDecelerationEntry { get; private set; } public static ConfigEntry<bool> RotateToLookAtPlayerEntry { get; private set; } public static ConfigEntry<float> DelayBeforeLookingAtPlayerEntry { get; private set; } public static ConfigEntry<float> LookAtPlayerDurationEntry { get; private set; } public static ConfigEntry<float> RandomlyMoveWhenLooking_WaitTimeMinEntry { get; private set; } public static ConfigEntry<float> RandomlyMoveWhenLooking_WaitTimeMaxEntry { get; private set; } public static ConfigEntry<float> RandomlyMoveWhenLooking_RandomMoveTimeMinEntry { get; private set; } public static ConfigEntry<float> RandomlyMoveWhenLooking_RandomMoveTimeMaxEntry { get; private set; } public static ConfigEntry<float> LookingTooLongKeepsAgro_LookTimeBeforeAgroEntry { get; private set; } public static ConfigEntry<float> OnceSeenAgroAfterTimer_WaitTimeMinEntry { get; private set; } public static ConfigEntry<float> OnceSeenAgroAfterTimer_WaitTimeMaxEntry { get; private set; } public CustomConfig(ConfigFile config) { _config = config; InitInstance(this); Reload(); } public void Save() { if (_config == null) { throw new NullReferenceException("Config is null."); } _config.Save(); } public void AssignFromSaved() { GiantScaleMinEntry.Value = GiantScaleMin; GiantScaleMaxEntry.Value = GiantScaleMax; SpawnInEntry.Value = SpawnIn; SpawnInAnyEntry.Value = SpawnInAny; SpawnInAnyChanceEntry.Value = SpawnInAnyChance; CanSpawnInsideEntry.Value = CanSpawnInside; CanSpawnOutsideEntry.Value = CanSpawnOutside; DisableOutsideAtNightEntry.Value = DisableOutsideAtNight; MaxPerLevelEntry.Value = MaxPerLevel; SpawnPosterInEntry.Value = SpawnPosterIn; AiTypeEntry.Value = AiType; MoveSpeedEntry.Value = MoveSpeed; MoveAccelerationEntry.Value = MoveAcceleration; MoveDecelerationEntry.Value = MoveDeceleration; RotateToLookAtPlayerEntry.Value = RotateToLookAtPlayer; DelayBeforeLookingAtPlayerEntry.Value = DelayBeforeLookingAtPlayer; LookAtPlayerDurationEntry.Value = LookAtPlayerDuration; RandomlyMoveWhenLooking_WaitTimeMinEntry.Value = RandomlyMoveWhenLooking_WaitTimeMin; RandomlyMoveWhenLooking_WaitTimeMaxEntry.Value = RandomlyMoveWhenLooking_WaitTimeMax; RandomlyMoveWhenLooking_RandomMoveTimeMinEntry.Value = RandomlyMoveWhenLooking_RandomMoveTimeMin; RandomlyMoveWhenLooking_RandomMoveTimeMaxEntry.Value = RandomlyMoveWhenLooking_RandomMoveTimeMax; LookingTooLongKeepsAgro_LookTimeBeforeAgroEntry.Value = LookingTooLongKeepsAgro_LookTimeBeforeAgro; OnceSeenAgroAfterTimer_WaitTimeMinEntry.Value = OnceSeenAgroAfterTimer_WaitTimeMin; OnceSeenAgroAfterTimer_WaitTimeMaxEntry.Value = OnceSeenAgroAfterTimer_WaitTimeMax; } public void Reload(bool setValues = true) { GiantScaleMinEntry = _config.Bind<float>("1. General Settings", "GiantScaleMin", 0.9f, "The minimum scale of the Rolling Giant.\nThis changes how small the Giant can be.\nThis is a multiplier, so 0.5 is half as large."); GiantScaleMaxEntry = _config.Bind<float>("1. General Settings", "GiantScaleMax", 1.1f, "The maximum scale of the Rolling Giant.\nThis changes how big the Giant can be.\nThis is a multiplier, so 2 is twice as large."); SpawnInEntry = _config.Bind<string>("1. General Settings", "SpawnIn", "Vow:45,March:45,Rend:54,Dine:65,Offense:45,Titan:65", "Where the Rolling Giant can spawn.\nSeparate each level with a comma, and put a chance (no decimals) separated by a colon.\nVanilla caps at 100, but you can go farther.\nThis chance is also a weight, not a percentage.\nHigher chance = higher chance to get picked\nThe names are what you see in the terminal\nExample: Vow:6,March:10"); SpawnInAnyEntry = _config.Bind<bool>("1. General Settings", "SpawnInAny", false, "If the Rolling Giant can spawn in any level."); SpawnInAnyChanceEntry = _config.Bind<int>("1. General Settings", "SpawnInAnyChance", 45, "The chance for the Rolling Giant to spawn in any level.\nRequires SpawnInAny to be enabled!\nThis is a weight, not a percentage.\nHigher chance = higher chance to get picked"); CanSpawnInsideEntry = _config.Bind<bool>("1. General Settings", "CanSpawnInside", true, "If the Rolling Giant can spawn inside."); CanSpawnOutsideEntry = _config.Bind<bool>("1. General Settings", "CanSpawnOutside", false, "If the Rolling Giant can spawn outside."); DisableOutsideAtNightEntry = _config.Bind<bool>("1. General Settings", "DisableOutsideAtNight", false, "If the Rolling Giant will turn off if it is outside at night."); MaxPerLevelEntry = _config.Bind<int>("1. General Settings", "MaxPerLevel", 3, "The maximum amount of Rolling Giants that can spawn in a level."); SpawnPosterInEntry = _config.Bind<string>("1. General Settings", "SpawnPosterIn", "Vow:12,March:12,Rend:12,Dine:12,Offense:12,Titan:12", "Where the Rolling Giant poster scrap can spawn.\nSeparate each level with a comma, and put a chance separated by a colon.\nVanilla caps at 100, but you can go farther.\nThis chance is also a weight, not a percentage.\nHigher chance = higher chance to get picked\nThe names are what you see in the terminal\nExample: Vow:12,March:12,Rend:12,Dine:12,Offense:12,Titan:12"); if (GotoPreviousAiTypeKey == null) { GotoPreviousAiTypeKey = _config.Bind<string>("Host", "GotoPreviousAiTypeKey", "<Keyboard>/numpad7", "The key to go to the previous AI type. This uses Unity's New Input System's key-bind names.\nhttps://docs.unity3d.com/Packages/[email protected]/manual/Controls.html#control-paths"); } if (GotoNextAiTypeKey == null) { GotoNextAiTypeKey = _config.Bind<string>("Host", "GotoNextAiTypeKey", "<Keyboard>/numpad8", "The key to go to the next AI type. This uses Unity's New Input System's key-bind names.\nhttps://docs.unity3d.com/Packages/[email protected]/manual/Controls.html#control-paths"); } if (ReloadConfigKey == null) { ReloadConfigKey = _config.Bind<string>("Host", "ReloadConfigKey", "<Keyboard>/numpad9", "The key to reload the config. Does not update spawn conditions. This uses Unity's New Input System's key-bind names.\nhttps://docs.unity3d.com/Packages/[email protected]/manual/Controls.html#control-paths"); } AiTypeEntry = _config.Bind<RollingGiantAiType>("2. AI Settings", "AiType", RollingGiantAiType.RandomlyMoveWhileLooking, "The AI type of the Rolling Giant.\n- Putting multiple will randomly choose between them each time you land on a moon\nCoilhead = Coilhead AI\nInverseCoilhead = Move when player is looking at it\nRandomlyMoveWhileLooking = Randomly move while the player is looking at it\nLookingTooLongKeepsAgro = If the player looks at it for too long it doesn't stop chasing\nFollowOnceAgro = Once the player is noticed, the Rolling Giant will follow the player constantly\nOnceSeenAgroAfterTimer = Once the player sees the Rolling Giant, it will chase the player after a timer"); MoveSpeedEntry = _config.Bind<float>("2. AI Settings", "MoveSpeed", 6f, "The speed of the Rolling Giant in m/s²."); MoveAccelerationEntry = _config.Bind<float>("2. AI Settings", "MoveAcceleration", 2f, "How long it takes the Rolling Giant to get to its movement speed. in seconds"); MoveDecelerationEntry = _config.Bind<float>("2. AI Settings", "MoveDeceleration", 0.5f, "How long it takes the Rolling Giant to stop moving in seconds."); RotateToLookAtPlayerEntry = _config.Bind<bool>("2. AI Settings", "RotateToLookAtPlayer", true, "If the Rolling Giant should rotate to look at the player."); DelayBeforeLookingAtPlayerEntry = _config.Bind<float>("2. AI Settings", "DelayBeforeLookingAtPlayer", 2f, "The delay before the Rolling Giant looks at the player in seconds."); LookAtPlayerDurationEntry = _config.Bind<float>("2. AI Settings", "LookAtPlayerDuration", 3f, "The duration the Rolling Giant looks at the player in seconds."); RandomlyMoveWhenLooking_WaitTimeMinEntry = _config.Bind<float>("AI.RandomlyMoveWhenLooking", "WaitTimeMin", 1f, "The minimum duration in seconds that the Rolling Giant waits before moving again."); RandomlyMoveWhenLooking_WaitTimeMaxEntry = _config.Bind<float>("AI.RandomlyMoveWhenLooking", "WaitTimeMax", 3f, "The maximum duration in seconds that the Rolling Giant waits before moving again."); RandomlyMoveWhenLooking_RandomMoveTimeMinEntry = _config.Bind<float>("AI.RandomlyMoveWhenLooking", "RandomMoveTimeMin", 1f, "The minimum duration in seconds that the Rolling Giant moves for."); RandomlyMoveWhenLooking_RandomMoveTimeMaxEntry = _config.Bind<float>("AI.RandomlyMoveWhenLooking", "RandomMoveTimeMax", 3f, "The maximum duration in seconds that the Rolling Giant moves for."); LookingTooLongKeepsAgro_LookTimeBeforeAgroEntry = _config.Bind<float>("AI.LookingTooLongKeepsAgro", "LookTimeBeforeAgro", 10f, "How long the player can look at the Rolling Giant before it starts chasing in seconds."); OnceSeenAgroAfterTimer_WaitTimeMinEntry = _config.Bind<float>("AI.OnceSeenAgroAfterTimer", "WaitTimeMin", 30f, "The minimum duration in seconds the Rolling Giant waits before chasing the player."); OnceSeenAgroAfterTimer_WaitTimeMaxEntry = _config.Bind<float>("AI.OnceSeenAgroAfterTimer", "WaitTimeMax", 60f, "The minimum duration in seconds the Rolling Giant waits before chasing the player."); if (setValues) { GiantScaleMin = GiantScaleMinEntry.Value; GiantScaleMax = GiantScaleMaxEntry.Value; SpawnIn = SpawnInEntry.Value; SpawnInAny = SpawnInAnyEntry.Value; SpawnInAnyChance = SpawnInAnyChanceEntry.Value; CanSpawnInside = CanSpawnInsideEntry.Value; CanSpawnOutside = CanSpawnOutsideEntry.Value; DisableOutsideAtNight = DisableOutsideAtNightEntry.Value; MaxPerLevel = MaxPerLevelEntry.Value; SpawnPosterIn = SpawnPosterInEntry.Value; AiType = AiTypeEntry.Value; MoveSpeed = MoveSpeedEntry.Value; MoveAcceleration = MoveAccelerationEntry.Value; MoveDeceleration = MoveDecelerationEntry.Value; RotateToLookAtPlayer = RotateToLookAtPlayerEntry.Value; DelayBeforeLookingAtPlayer = DelayBeforeLookingAtPlayerEntry.Value; LookAtPlayerDuration = LookAtPlayerDurationEntry.Value; RandomlyMoveWhenLooking_WaitTimeMin = RandomlyMoveWhenLooking_WaitTimeMinEntry.Value; RandomlyMoveWhenLooking_WaitTimeMax = RandomlyMoveWhenLooking_WaitTimeMaxEntry.Value; RandomlyMoveWhenLooking_RandomMoveTimeMin = RandomlyMoveWhenLooking_RandomMoveTimeMinEntry.Value; RandomlyMoveWhenLooking_RandomMoveTimeMax = RandomlyMoveWhenLooking_RandomMoveTimeMaxEntry.Value; LookingTooLongKeepsAgro_LookTimeBeforeAgro = LookingTooLongKeepsAgro_LookTimeBeforeAgroEntry.Value; OnceSeenAgroAfterTimer_WaitTimeMin = OnceSeenAgroAfterTimer_WaitTimeMinEntry.Value; OnceSeenAgroAfterTimer_WaitTimeMax = OnceSeenAgroAfterTimer_WaitTimeMaxEntry.Value; SetCurrentAi(); } Plugin.Log.LogInfo((object)"Config reloaded."); } public static SharedAiSettings GetSharedAiSettings() { SharedAiSettings result = default(SharedAiSettings); result.moveSpeed = SyncedInstance<CustomConfig>.Instance.MoveSpeed; result.moveAcceleration = SyncedInstance<CustomConfig>.Instance.MoveAcceleration; result.moveDeceleration = SyncedInstance<CustomConfig>.Instance.MoveDeceleration; result.rotateToLookAtPlayer = SyncedInstance<CustomConfig>.Instance.RotateToLookAtPlayer; result.delayBeforeLookingAtPlayer = SyncedInstance<CustomConfig>.Instance.DelayBeforeLookingAtPlayer; result.lookAtPlayerDuration = SyncedInstance<CustomConfig>.Instance.LookAtPlayerDuration; return result; } public static void RequestSync() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (!SyncedInstance<CustomConfig>.IsClient) { Plugin.Log.LogError((object)"Config sync error: Not a client."); return; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(SyncedInstance<CustomConfig>.IntSize, (Allocator)2, -1); try { SyncedInstance<CustomConfig>.MessageManager.SendNamedMessage("RollingGiant_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3); Plugin.Log.LogInfo((object)"Config sync request sent."); } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } public static void OnRequestSync(ulong clientId, FastBufferReader _) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) if (!SyncedInstance<CustomConfig>.IsHost) { Plugin.Log.LogError((object)"Config sync error: Not a host."); return; } Plugin.Log.LogInfo((object)$"Config sync request received from client: {clientId}"); byte[] array = SyncedInstance<CustomConfig>.SerializeToBytes(SyncedInstance<CustomConfig>.Instance); int num = array.Length; FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<CustomConfig>.IntSize, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0); SyncedInstance<CustomConfig>.MessageManager.SendNamedMessage("RollingGiant_OnReceiveConfigSync", clientId, val, (NetworkDelivery)4); Plugin.Log.LogInfo((object)$"Config sync sent to client: {clientId}"); } catch (Exception arg) { Plugin.Log.LogError((object)$"Error occurred syncing config with client: {clientId}\n{arg}"); } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } public static void OnReceiveSync(ulong _, FastBufferReader reader) { //IL_0024: 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) if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<CustomConfig>.IntSize)) { Plugin.Log.LogError((object)"Config sync error: Could not begin reading buffer."); return; } int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); if (!((FastBufferReader)(ref reader)).TryBeginRead(num)) { Plugin.Log.LogError((object)"Config sync error: Host could not sync."); return; } byte[] data = new byte[num]; ((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0); SyncedInstance<CustomConfig>.SyncInstance(data); SetCurrentAi(); Plugin.Log.LogInfo((object)"Successfully synced config with host."); } public static void SetCurrentAi() { if (Object.op_Implicit((Object)(object)NetworkHandler.Instance)) { RollingGiantAiType aiType = NetworkHandler.AiType; SharedAiSettings sharedAiSettings2; switch (aiType) { case RollingGiantAiType.Coilhead: sharedAiSettings2 = GetSharedAiSettings(); break; case RollingGiantAiType.InverseCoilhead: sharedAiSettings2 = GetSharedAiSettings(); break; case RollingGiantAiType.RandomlyMoveWhileLooking: { SharedAiSettings sharedAiSettings = GetSharedAiSettings(); sharedAiSettings.waitTimeMin = SyncedInstance<CustomConfig>.Instance.RandomlyMoveWhenLooking_WaitTimeMin; sharedAiSettings.waitTimeMax = SyncedInstance<CustomConfig>.Instance.RandomlyMoveWhenLooking_WaitTimeMax; sharedAiSettings.randomMoveTimeMin = SyncedInstance<CustomConfig>.Instance.RandomlyMoveWhenLooking_RandomMoveTimeMin; sharedAiSettings.randomMoveTimeMax = SyncedInstance<CustomConfig>.Instance.RandomlyMoveWhenLooking_RandomMoveTimeMax; sharedAiSettings2 = sharedAiSettings; break; } case RollingGiantAiType.LookingTooLongKeepsAgro: { SharedAiSettings sharedAiSettings = GetSharedAiSettings(); sharedAiSettings.lookTimeBeforeAgro = SyncedInstance<CustomConfig>.Instance.LookingTooLongKeepsAgro_LookTimeBeforeAgro; sharedAiSettings2 = sharedAiSettings; break; } case RollingGiantAiType.FollowOnceAgro: sharedAiSettings2 = GetSharedAiSettings(); break; case RollingGiantAiType.OnceSeenAgroAfterTimer: { SharedAiSettings sharedAiSettings = GetSharedAiSettings(); sharedAiSettings.waitTimeMin = SyncedInstance<CustomConfig>.Instance.OnceSeenAgroAfterTimer_WaitTimeMin; sharedAiSettings.waitTimeMax = SyncedInstance<CustomConfig>.Instance.OnceSeenAgroAfterTimer_WaitTimeMax; sharedAiSettings2 = sharedAiSettings; break; } default: throw new ArgumentOutOfRangeException(); } SharedAiSettings = sharedAiSettings2; Plugin.Log.LogInfo((object)$"[{aiType}]: {SharedAiSettings}"); } } } public class GeneralSettings { public const string Name = "1. General Settings"; public ConfigEntry<float> ChanceForGiant; public ConfigEntry<float> GiantScaleMin; public ConfigEntry<float> GiantScaleMax; public ConfigEntry<bool> SpawnInAllLevels; public ConfigEntry<bool> SpawnInLevelsWithCoilHead; public ConfigEntry<bool> SpawnInside; public ConfigEntry<bool> SpawnDaytime; public ConfigEntry<bool> SpawnOutside; public ConfigEntry<int> Version; public ConfigEntry<string> GotoPreviousAiTypeKey; public ConfigEntry<string> GotoNextAiTypeKey; public GeneralSettings(ConfigFile configFile) { ChanceForGiant = configFile.Bind<float>("1. General Settings", "ChanceForGiant", 0.4f, "0.0-1.0: Chance for a Rolling Giant to spawn. Higher means more chances for a Rolling Giant."); GiantScaleMin = configFile.Bind<float>("1. General Settings", "GiantScaleMin", 1f, "The minimum scale of the Rolling Giant."); GiantScaleMax = configFile.Bind<float>("1. General Settings", "GiantScaleMax", 1f, "The maximum scale of the Rolling Giant."); SpawnInAllLevels = configFile.Bind<bool>("1. General Settings", "SpawnInAllLevels", false, "If the Rolling Giant should spawn in all levels."); SpawnInLevelsWithCoilHead = configFile.Bind<bool>("1. General Settings", "SpawnInLevelsWithCoilHead", true, "If the Rolling Giant should spawn in levels with a Coilhead."); SpawnInside = configFile.Bind<bool>("1. General Settings", "SpawnInside", true, "If the Rolling Giant should spawn inside."); SpawnDaytime = configFile.Bind<bool>("1. General Settings", "SpawnDaytime", false, "If the Rolling Giant should spawn during the day."); SpawnOutside = configFile.Bind<bool>("1. General Settings", "SpawnOutside", false, "If the Rolling Giant should spawn outside."); Version = configFile.Bind<int>("z_Ignore", "__version", 0, "The version of this config file. Do not change this."); GotoPreviousAiTypeKey = configFile.Bind<string>("Dev", "GotoPreviousAiTypeKey", "<Keyboard>/numpad7", "The key to go to the previous AI type. This uses Unity's New Input System's key-bind names."); GotoNextAiTypeKey = configFile.Bind<string>("Dev", "GotoNextAiTypeKey", "<Keyboard>/numpad9", "The key to go to the next AI type. This uses Unity's New Input System's key-bind names."); } public float GetRandomScale(Random rng) { float num = (float)rng.NextDouble(); float value = GiantScaleMin.Value; float value2 = GiantScaleMax.Value; return Mathf.Lerp(value, value2, num); } } [Serializable] public class SyncedInstance<T> { [NonSerialized] protected static int IntSize = 4; internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager; internal static bool IsClient => NetworkManager.Singleton.IsClient; internal static bool IsHost => NetworkManager.Singleton.IsHost; public static T Default { get; private set; } public static T Instance { get; private set; } public static bool Synced { get; internal set; } protected void InitInstance(T instance) { Default = instance; Instance = instance; IntSize = 4; } internal static void SyncInstance(byte[] data) { Instance = DeserializeFromBytes(data); Synced = true; } internal static void RevertSync() { Instance = Default; Synced = false; } public static byte[] SerializeToBytes(T val) { BinaryFormatter binaryFormatter = new BinaryFormatter(); using MemoryStream memoryStream = new MemoryStream(); try { binaryFormatter.Serialize(memoryStream, val); return memoryStream.ToArray(); } catch (Exception arg) { Plugin.Log.LogError((object)$"Error serializing instance: {arg}"); return null; } } public static T DeserializeFromBytes(byte[] data) { BinaryFormatter binaryFormatter = new BinaryFormatter(); using MemoryStream serializationStream = new MemoryStream(data); try { return (T)binaryFormatter.Deserialize(serializationStream); } catch (Exception arg) { Plugin.Log.LogError((object)$"Error deserializing instance: {arg}"); return default(T); } } } } namespace RollingGiant.Patches { [HarmonyPatch] public static class EnemyPatches { [HarmonyPatch(typeof(StartOfRound), "Awake")] [HarmonyPostfix] private static void RegisterEnemy(StartOfRound __instance) { //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Expected O, but got Unknown //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Expected O, but got Unknown //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Expected O, but got Unknown //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Expected O, but got Unknown (string, int)[] levelChances = GetLevelChances(CustomConfig.SpawnIn); (string, int)[] levelChances2 = GetLevelChances(CustomConfig.SpawnPosterIn); if (!__instance.allItemsList.itemsList.Contains(Plugin.PosterItem)) { __instance.allItemsList.itemsList.Add(Plugin.PosterItem); } bool spawnInAny = CustomConfig.SpawnInAny; SelectableLevel[] levels = __instance.levels; foreach (SelectableLevel val in levels) { try { string levelName = val.PlanetName.ToLower().Replace(" ", string.Empty); (string, int)[] array = levelChances; for (int j = 0; j < array.Length; j++) { var (value, num) = array[j]; if (!spawnInAny && !levelName.Contains(value)) { continue; } if (spawnInAny) { num = CustomConfig.SpawnInAnyChance; } if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)Plugin.PosterItem)) { (string, int) tuple2 = levelChances2.FirstOrDefault(((string, int) x) => levelName.Contains(x.Item1)); if (!string.IsNullOrEmpty(tuple2.Item1)) { val.spawnableScrap.Add(new SpawnableItemWithRarity { spawnableItem = Plugin.PosterItem, rarity = tuple2.Item2 }); Plugin.Log.LogMessage((object)$"Added {Plugin.PosterItem.itemName} to {val.PlanetName} with chance of {tuple2.Item2}"); } } if (CustomConfig.CanSpawnInside && val.Enemies.All((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType != (Object)(object)Plugin.EnemyTypeInside)) { val.Enemies.Add(new SpawnableEnemyWithRarity { enemyType = Plugin.EnemyTypeInside, rarity = num }); Plugin.Log.LogMessage((object)$"Added {Plugin.EnemyTypeOutside.enemyName} to {val.PlanetName} with chance of {num} (inside)"); } if (!CustomConfig.DisableOutsideAtNight && CustomConfig.CanSpawnOutside && val.OutsideEnemies.All((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType != (Object)(object)Plugin.EnemyTypeOutside)) { val.OutsideEnemies.Add(new SpawnableEnemyWithRarity { enemyType = Plugin.EnemyTypeOutside, rarity = num }); Plugin.Log.LogMessage((object)$"Added {Plugin.EnemyTypeOutside.enemyName} to {val.PlanetName} with chance of {num} (outside)"); } if (CustomConfig.DisableOutsideAtNight && CustomConfig.CanSpawnOutside && val.DaytimeEnemies.All((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType != (Object)(object)Plugin.EnemyTypeOutsideDaytime)) { val.DaytimeEnemies.Add(new SpawnableEnemyWithRarity { enemyType = Plugin.EnemyTypeOutsideDaytime, rarity = num }); Plugin.Log.LogMessage((object)$"Added {Plugin.EnemyTypeOutsideDaytime.enemyName} to {val.PlanetName} with chance of {num} (daytime)"); } } } catch (Exception arg) { Plugin.Log.LogError((object)$"Failed to add enemy to {val.PlanetName}!\n{arg}"); } } } private static (string, int)[] GetLevelChances(string str) { if (string.IsNullOrEmpty(str)) { return new(string, int)[0]; } return str.Replace(" ", string.Empty).Split(",").Select(delegate(string x) { if (!x.Contains(":")) { return (x.ToLower().Replace(" ", string.Empty), 0); } string[] array = x.Split(":"); if (!int.TryParse(array[1], out var result)) { result = 0; } return (array[0].ToLower().Replace(" ", string.Empty), result); }) .ToArray(); } [HarmonyPatch(typeof(QuickMenuManager), "Debug_SetEnemyDropdownOptions")] [HarmonyPrefix] private static void AddGiantToDebugList(QuickMenuManager __instance) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_00
plugins/Ryokune.CompatibilityChecker.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using CompatibilityChecker.MonoBehaviours; using CompatibilityChecker.Netcode; using CompatibilityChecker.Patches; using CompatibilityChecker.Utils; using HarmonyLib; using Newtonsoft.Json; using Steamworks; using Steamworks.Data; using TMPro; using UnityEngine; using UnityEngine.Events; 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 = "")] [assembly: AssemblyCompany("Ryokune")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Lethal Company Library that lets you know which mods a modded server has.")] [assembly: AssemblyFileVersion("1.1.6.0")] [assembly: AssemblyInformationalVersion("1.1.6")] [assembly: AssemblyProduct("CompatibilityChecker")] [assembly: AssemblyTitle("Ryokune.CompatibilityChecker")] [assembly: AssemblyVersion("1.1.6.0")] namespace CompatibilityChecker { [BepInPlugin("Ryokune.CompatibilityChecker", "CompatibilityChecker", "1.1.6")] [BepInProcess("Lethal Company.exe")] public class ModNotifyBase : BaseUnityPlugin { public static ModNotifyBase instance; public static ManualLogSource Logger; private readonly Harmony harmony = new Harmony("Ryokune.CompatibilityChecker"); public static Dictionary<string, PluginInfo> ModList = new Dictionary<string, PluginInfo>(); public static string ModListString; public static string[] ModListArray; public static bool loadedMods; public static string seperator = "/@/"; public static string Text; public static TMP_InputField searchInputField; private static IEnumerator JoinLobby(SteamId lobbyId, SteamLobbyManager lobbyManager) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) bool found = false; Logger.LogWarning((object)"Getting Lobby"); Task<Lobby?> joinTask = SteamMatchmaking.JoinLobbyAsync(lobbyId); yield return (object)new WaitUntil((Func<bool>)(() => joinTask.IsCompleted)); if (joinTask.Result.HasValue) { Logger.LogWarning((object)"Getting Lobby Value"); Lobby lobby = joinTask.Result.Value; if (!Utility.IsNullOrWhiteSpace(((Lobby)(ref lobby)).GetData("vers"))) { LobbySlot.JoinLobbyAfterVerifying(lobby, ((Lobby)(ref lobby)).Id); found = true; Logger.LogWarning((object)"Success!"); } lobby = default(Lobby); } else { Logger.LogWarning((object)"Failed to join lobby."); } if (!found) { lobbyManager.LoadServerList(); } else if ((Object)(object)searchInputField != (Object)null) { searchInputField.text = ""; Text = ""; } } private static void OnEndEdit(string newValue) { //IL_001c: 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) Text = newValue; SteamLobbyManager val = Object.FindObjectOfType<SteamLobbyManager>(); if (ulong.TryParse(newValue, out var result)) { SteamId val2 = default(SteamId); val2.Value = result; CoroutineHandler.Instance.NewCoroutine(JoinLobby(SteamId.op_Implicit(result), val)); } else { val.LoadServerList(); } } private static IEnumerator displayCopied(TextMeshProUGUI textMesh) { string oldtext = ((TMP_Text)textMesh).text; if (GameNetworkManager.Instance.currentLobby.HasValue) { ((TMP_Text)textMesh).text = "(Copied to clipboard!)"; Lobby value = GameNetworkManager.Instance.currentLobby.Value; SteamId id2 = ((Lobby)(ref value)).Id; string id = (GUIUtility.systemCopyBuffer = ((object)(SteamId)(ref id2)).ToString()); Logger.LogWarning((object)("Lobby code copied to clipboard: " + id)); } else { ((TMP_Text)textMesh).text = "Can't get Lobby code!"; } yield return (object)new WaitForSeconds(1.2f); ((TMP_Text)textMesh).text = oldtext; } private static void sceneLoad(Scene sceneName, LoadSceneMode load) { //IL_0155: 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_0169: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Expected O, but got Unknown //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Expected O, but got Unknown //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Expected O, but got Unknown if (((Scene)(ref sceneName)).name == "MainMenu") { GameObject val = GameObject.Find("/Canvas/MenuContainer/LobbyList/JoinCode"); if ((Object)(object)val != (Object)null) { try { GameObject val2 = Object.Instantiate<GameObject>(val.gameObject, val.transform.parent); val2.SetActive(true); searchInputField = val2.GetComponent<TMP_InputField>(); ((Selectable)searchInputField).interactable = true; ((TMP_Text)((Component)searchInputField.placeholder).gameObject.GetComponent<TextMeshProUGUI>()).text = "Search or Enter a room code..."; searchInputField.onEndEdit = new SubmitEvent(); searchInputField.onEndTextSelection = new TextSelectionEvent(); searchInputField.onSubmit = new SubmitEvent(); ((UnityEvent<string>)(object)searchInputField.onSubmit).AddListener((UnityAction<string>)OnEndEdit); } catch (Exception ex) { Logger.LogError((object)ex); } } } else { if (!(((Scene)(ref sceneName)).name == "SampleSceneRelay")) { return; } GameObject val3 = GameObject.Find("/Systems/UI/Canvas/QuickMenu/MainButtons/Resume"); if ((Object)(object)val3 != (Object)null) { GameObject val4 = Object.Instantiate<GameObject>(val3.gameObject, val3.transform.parent); RectTransform component = val4.GetComponent<RectTransform>(); component.anchoredPosition += new Vector2(0f, 182f); TextMeshProUGUI LobbyCodeTextMesh = val4.GetComponentInChildren<TextMeshProUGUI>(); ((TMP_Text)LobbyCodeTextMesh).text = "> Lobby Code"; Button component2 = val4.GetComponent<Button>(); component2.onClick = new ButtonClickedEvent(); ((UnityEvent)component2.onClick).AddListener((UnityAction)delegate { CoroutineHandler.Instance.NewCoroutine(displayCopied(LobbyCodeTextMesh)); }); } } } private void Awake() { SceneManager.sceneLoaded += sceneLoad; if ((Object)(object)instance == (Object)null) { instance = this; Logger = ((BaseUnityPlugin)this).Logger; } CoroutineHandler.Instance.NewCoroutine(ThunderstoreAPI.Initialize()); Logger.LogInfo((object)"Plugin Ryokune.CompatibilityChecker is loaded!"); Logger.LogInfo((object)"Modded servers with CompatibilityChecker will now notify you what mods are needed."); harmony.PatchAll(typeof(ModNotifyBase)); harmony.PatchAll(typeof(PlayerJoinNetcode)); harmony.PatchAll(typeof(SteamLobbyManagerPatch)); } public static IEnumerator InitializeModsCoroutine() { yield return (object)new WaitUntil((Func<bool>)(() => ThunderstoreAPI.Packages != null)); ModList = Chainloader.PluginInfos; StringBuilder messageBuilder = new StringBuilder(); MenuManager menuManager = Object.FindObjectOfType<MenuManager>(); PlayerJoinNetcode.old = ((((Component)((TMP_Text)menuManager.menuNotificationButtonText).transform.parent).GetComponent<RectTransform>().sizeDelta != Vector2.zero) ? ((Component)((TMP_Text)menuManager.menuNotificationButtonText).transform.parent).GetComponent<RectTransform>().sizeDelta : PlayerJoinNetcode.old); int i = 0; int count = ModList.Count(); menuManager.menuNotification.SetActive(true); foreach (PluginInfo info in ModList.Values) { i++; ((TMP_Text)menuManager.menuNotificationText).text = $"Loading mods {i}/{count}"; ((TMP_Text)menuManager.menuNotificationButtonText).text = null; ((Component)((TMP_Text)menuManager.menuNotificationButtonText).transform.parent).GetComponent<RectTransform>().sizeDelta = Vector2.zero; string noSpace = Regex.Replace(info.Metadata.Name, "[\\s\\-_]", ""); Package package = ThunderstoreAPI.GetPackage(noSpace, info); if (package != null) { Logger.LogInfo((object)$"[{info.Metadata.GUID}] Found package: {info.Metadata.Name}[{info.Metadata.Version}]\n\t\tDATA:\n\t\t--NAME: {package.FullName}\n\t\t--LINK: {package.PackageUrl}"); if (VersionUtil.ConvertToNumber(package.Versions[0].VersionNumber) > VersionUtil.ConvertToNumber(info.Metadata.Version.ToString())) { messageBuilder.AppendLine($"\n\t\t--Mod {info.Metadata.Name} [{info.Metadata.GUID}] v{info.Metadata.Version} does not equal the latest release!"); messageBuilder.AppendLine("\t\t--Latest version: v" + package.Versions[0].VersionNumber); messageBuilder.AppendLine("\t\t--Link: " + package.PackageUrl); messageBuilder.AppendLine("\t\t--Full mod name: " + package.FullName); messageBuilder.AppendLine("\t\t--(If this is wrong, please ignore this.)"); } } if (package?.Categories.Contains("Server-side") ?? false) { if (package.Name == "CompatibilityChecker" && package.Versions[0].VersionNumber != "1.1.6") { string warning = "Current CompatibilityChecker v1.1.6 does not equal latest release v" + package.Versions[0].VersionNumber + "!\nPlease update to the latest version of CompatibilityChecker!!!"; Logger.LogWarning((object)warning); Object.FindObjectOfType<MenuManager>().DisplayMenuNotification(warning, (string)null); } ModListString += $"{info.Metadata.Name}[{info.Metadata.Version}]{seperator}"; } else if (package == null) { Logger.LogWarning((object)$"Couldn't find package: {info.Metadata.Name}[{info.Metadata.Version}]\n\t\t[{info.Metadata.GUID}]"); ModListString += $"{info.Metadata.GUID}[{info.Metadata.Version}]{seperator}"; } yield return null; } if (messageBuilder.Length != 0) { Logger.LogWarning((object)messageBuilder.ToString()); } ModListString = ModListString.Remove(ModListString.Length - 3, 3); ModListArray = ModListString.Split(seperator); Logger.LogWarning((object)$"Server-sided Mod List Count: {ModListArray.Count()}"); menuManager.menuNotification.SetActive(false); loadedMods = true; } } public static class PluginInfo { public const string PLUGIN_GUID = "Ryokune.CompatibilityChecker"; public const string PLUGIN_NAME = "CompatibilityChecker"; public const string PLUGIN_VERSION = "1.1.6"; } } namespace CompatibilityChecker.Utils { [Serializable] public class Package { [JsonProperty("name")] public string Name; [JsonProperty("full_name")] public string FullName; [JsonProperty("owner")] public string Owner; [JsonProperty("package_url")] public string PackageUrl; [JsonProperty("categories")] public string[] Categories; [JsonProperty("versions")] public Version[] Versions; public long TotalDownloads; [JsonProperty("is_deprecated")] public bool IsDeprecated; } [Serializable] public class Version { [JsonProperty("name")] public string Name; [JsonProperty("full_name")] public string FullName; [JsonProperty("version_number")] public string VersionNumber; [JsonProperty("download_url")] public Uri DownloadUrl; [JsonProperty("downloads")] public long Downloads; [JsonProperty("website_url")] public Uri WebsiteUrl; } public static class ThunderstoreAPI { private const string ApiBaseUrl = "https://thunderstore.io/c/lethal-company/api/v1/package/"; private static List<Package> packages; public static List<Package> Packages => packages; public static async Task InitializeThunderstorePackagesAsync(Action onComplete) { try { using HttpClient httpClient = new HttpClient(); packages = JsonConvert.DeserializeObject<List<Package>>(await httpClient.GetStringAsync("https://thunderstore.io/c/lethal-company/api/v1/package/")); ModNotifyBase.Logger.LogInfo((object)$"ThunderstoreAPI Initialized! Got packages: {packages.Count()}"); foreach (Package pack in packages) { Version[] versions = pack.Versions; foreach (Version ver in versions) { pack.TotalDownloads += ver.Downloads; } } } catch (Exception ex2) { Exception ex = ex2; ModNotifyBase.Logger.LogError((object)("Failed to initialize Thunderstore packages. Error: " + ex.Message)); } onComplete?.Invoke(); } public static bool IsSimilar(string s1, string s2) { string pattern = string.Join(".*?", s2.ToCharArray()); Match match = Regex.Match(s1, pattern); if (match.Success) { return match.Success; } int[,] array = new int[s1.Length + 1, s2.Length + 1]; for (int i = 0; i <= s1.Length; i++) { for (int j = 0; j <= s2.Length; j++) { if (i == 0) { array[i, j] = j; } else if (j == 0) { array[i, j] = i; } else { array[i, j] = Math.Min(Math.Min(array[i - 1, j] + 1, array[i, j - 1] + 1), array[i - 1, j - 1] + ((s1[i - 1] != s2[j - 1]) ? 1 : 0)); } } } int num = Math.Max(s1.Length, s2.Length); int num2 = array[s1.Length, s2.Length]; double num3 = 1.0 - (double)num2 / (double)num; return num3 > 0.54; } private static bool IsMatchingName(Package package, string searchString) { string[] array = Regex.Split(package.Name, "(?<=[a-z])(?=[A-Z])|[\\s_\\-]"); string[] searchStringSplit = Regex.Split(searchString, "(?<=[a-z])(?=[A-Z])|[\\s_\\-]"); int num = ((array.Length > searchStringSplit.Length) ? (searchStringSplit.Length / 2) : (array.Length / 2)); int num2 = array.Count((string token) => searchStringSplit.Contains<string>(token, StringComparer.OrdinalIgnoreCase)); return num2 >= num; } private static bool IsMatchingName(Package package, string searchString, string owner) { string[] source = Regex.Split(Regex.Replace(package.Name, "[\\s_]+(\\w)", (Match m) => m.Groups[1].Value.ToUpper()).Replace(" ", ""), "(?<=[a-z])(?=[A-Z])"); string[] searchStringNameTokens = Regex.Split(searchString, "(?<=[a-z])(?=[A-Z])"); int num = 2; int num2 = source.Count((string token) => searchStringNameTokens.Contains<string>(token, StringComparer.OrdinalIgnoreCase)); return num2 >= num && owner.Contains(package.Owner, StringComparison.OrdinalIgnoreCase); } public static List<Package> GetPackages(string searchString) { return Packages?.Where((Package package) => IsMatchingName(package, searchString)).ToList(); } public static List<Package> GetPackages(string searchString, string owner) { return Packages?.Where((Package package) => IsMatchingName(package, searchString, owner)).ToList(); } public static Package GetPackage(string searchString) { Package package = null; foreach (Package package2 in Packages) { if (package2.IsDeprecated) { continue; } string text = Regex.Replace(package2.Name, "[\\s\\-_]", ""); if (text.Equals(searchString, StringComparison.OrdinalIgnoreCase) || searchString.Contains(text, StringComparison.OrdinalIgnoreCase) || text.Contains(searchString, StringComparison.OrdinalIgnoreCase)) { if (package == null) { package = package2; } if (package2.TotalDownloads >= package?.TotalDownloads) { package = package2; } } } return package; } public static Package GetPackage(string searchString, PluginInfo info) { Package result = null; bool flag = false; foreach (Package package in Packages) { if (package.IsDeprecated) { continue; } if (info.Metadata.GUID.Split(".").Contains(package.Owner)) { flag = true; } string text = Regex.Replace(package.Name, "[\\s\\-_]", ""); if (text.Equals(searchString, StringComparison.OrdinalIgnoreCase) || text.Equals(info.Metadata.Name, StringComparison.OrdinalIgnoreCase) || text.Equals(info.Metadata.GUID, StringComparison.OrdinalIgnoreCase)) { if (flag) { return package; } result = package; } if (searchString.Contains(text, StringComparison.OrdinalIgnoreCase) || text.Contains(searchString, StringComparison.OrdinalIgnoreCase) || text.Contains(info.Metadata.Name, StringComparison.OrdinalIgnoreCase) || text.Contains(info.Metadata.GUID, StringComparison.OrdinalIgnoreCase)) { result = package; } if (IsSimilar(package.Name, searchString)) { result = package; } } return result; } public static IEnumerator Initialize(Action onComplete = null) { yield return InitializeThunderstorePackagesAsync(onComplete); } } internal static class VersionUtil { public static int ConvertToNumber(string version) { string s = version.Replace(".", ""); if (int.TryParse(s, out var result)) { return result; } ModNotifyBase.Logger.LogError((object)("Error parsing version: " + version)); return 0; } } } namespace CompatibilityChecker.Patches { internal class SteamLobbyManagerPatch { [HarmonyPatch(typeof(SteamLobbyManager), "LoadServerList")] [HarmonyPostfix] [HarmonyAfter(new string[] { "me.swipez.melonloader.morecompany" })] public static void loadserverListPatch(ref SteamLobbyManager __instance, ref Lobby[] ___currentLobbyList) { CoroutineHandler.Instance.NewCoroutine(BetterCompatibility(__instance)); } public static IEnumerator BetterCompatibility(SteamLobbyManager lobbyManager) { yield return (object)new WaitUntil((Func<bool>)(() => ((Transform)((Component)lobbyManager.levelListContainer).GetComponent<RectTransform>()).childCount - 1 != 0 && ((Transform)((Component)lobbyManager.levelListContainer).GetComponent<RectTransform>()).childCount - 1 == Object.FindObjectsOfType(typeof(LobbySlot)).Length && !GameNetworkManager.Instance.waitingForLobbyDataRefresh)); int i = 0; float lobbySlotPositionOffset = 0f; try { LobbySlot[] array = (LobbySlot[])(object)Object.FindObjectsOfType(typeof(LobbySlot)); foreach (LobbySlot slot in array) { i++; Transform obj = ((Component)slot).transform.Find("JoinButton"); GameObject JoinButton = ((obj != null) ? ((Component)obj).gameObject : null); if ((Object)(object)JoinButton != (Object)null) { GameObject CopyCodeButton = Object.Instantiate<GameObject>(JoinButton, JoinButton.transform.parent); CopyCodeButton.SetActive(true); RectTransform rectTransform = CopyCodeButton.GetComponent<RectTransform>(); if ((Object)(object)rectTransform != (Object)null) { rectTransform.anchoredPosition -= new Vector2(78f, 0f); ((TMP_Text)CopyCodeButton.GetComponentInChildren<TextMeshProUGUI>()).text = "Code"; Button ButtonComponent = CopyCodeButton.GetComponent<Button>(); if ((Object)(object)ButtonComponent != (Object)null) { ButtonComponent.onClick = new ButtonClickedEvent(); ((UnityEvent)ButtonComponent.onClick).AddListener((UnityAction)delegate { string text2 = (GUIUtility.systemCopyBuffer = ((object)(SteamId)(ref slot.lobbyId)).ToString()); ModNotifyBase.Logger.LogInfo((object)("Lobby code copied to clipboard: " + text2)); }); } } } Lobby lobby = slot.thisLobby; if (!Utility.IsNullOrWhiteSpace(((Lobby)(ref lobby)).GetData("mods")) && !((TMP_Text)slot.LobbyName).text.Contains("[Checker]")) { ((TMP_Text)slot.LobbyName).text = ((TMP_Text)slot.LobbyName).text + " [Checker]"; } if (!Utility.IsNullOrWhiteSpace(ModNotifyBase.Text) && !((TMP_Text)slot.LobbyName).text.Contains(ModNotifyBase.Text, StringComparison.OrdinalIgnoreCase)) { i--; Object.DestroyImmediate((Object)(object)((Component)slot).gameObject); } else { ((Component)slot).gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(0f, lobbySlotPositionOffset); lobbySlotPositionOffset -= 42f; lobby = default(Lobby); } } RectTransform rect = ((Component)lobbyManager.levelListContainer).GetComponent<RectTransform>(); float newWidth = rect.sizeDelta.x; float newHeight = Mathf.Max(0f, (float)i * 42f); rect.SetSizeWithCurrentAnchors((Axis)0, newWidth); rect.SetSizeWithCurrentAnchors((Axis)1, newHeight); } catch (Exception err) { ModNotifyBase.Logger.LogError((object)err); } } [HarmonyPatch(typeof(SteamLobbyManager), "loadLobbyListAndFilter")] [HarmonyAfter(new string[] { "me.swipez.melonloader.morecompany" })] [HarmonyPrefix] public static bool loadLobbyPrefixPatch(ref SteamLobbyManager __instance, ref Lobby[] ___currentLobbyList, ref float ___lobbySlotPositionOffset, ref IEnumerator __result) { __result = modifiedLoadLobbyIEnumerator(__instance, ___currentLobbyList, ___lobbySlotPositionOffset); return false; } public static IEnumerator modifiedLoadLobbyIEnumerator(SteamLobbyManager __instance, Lobby[] ___currentLobbyList, float ___lobbySlotPositionOffset) { string[] offensiveWords = new string[21] { "nigger", "faggot", "n1g", "nigers", "cunt", "pussies", "pussy", "minors", "chink", "buttrape", "molest", "rape", "coon", "negro", "beastiality", "cocks", "cumshot", "ejaculate", "pedophile", "furfag", "necrophilia" }; for (int i = 0; i < ___currentLobbyList.Length; i++) { Lobby currentLobby = ___currentLobbyList[i]; Friend[] blockedUsers = SteamFriends.GetBlocked().ToArray(); if (blockedUsers != null) { Friend[] array = blockedUsers; for (int j = 0; j < array.Length; j++) { Friend blockedUser = array[j]; if (((Lobby)(ref currentLobby)).IsOwnedBy(blockedUser.Id)) { } } } string lobbyName = ((Lobby)(ref currentLobby)).GetData("name"); bool lobbyModded = !Utility.IsNullOrWhiteSpace(((Lobby)(ref currentLobby)).GetData("mods")); if (!Utility.IsNullOrWhiteSpace(lobbyName)) { string lobbyNameLowercase = lobbyName.ToLower(); if (__instance.censorOffensiveLobbyNames) { string[] array2 = offensiveWords; foreach (string word in array2) { if (lobbyNameLowercase.Contains(word)) { } } } GameObject gameObject = Object.Instantiate<GameObject>(__instance.LobbySlotPrefab, __instance.levelListContainer); gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(0f, ___lobbySlotPositionOffset); ___lobbySlotPositionOffset -= 42f; LobbySlot componentInChildren = gameObject.GetComponentInChildren<LobbySlot>(); ((TMP_Text)componentInChildren.LobbyName).text = lobbyName + " " + (lobbyModded ? "[Checker]" : ""); ((TMP_Text)componentInChildren.playerCount).text = $"{((Lobby)(ref currentLobby)).MemberCount} / 4"; componentInChildren.lobbyId = ((Lobby)(ref currentLobby)).Id; componentInChildren.thisLobby = currentLobby; } currentLobby = default(Lobby); } yield break; } } } namespace CompatibilityChecker.Netcode { [HarmonyPatch] internal class PlayerJoinNetcode { private static string[] serverModList = null; public static Vector2 old = Vector2.zero; public static IEnumerator SetLobbyData(Lobby lobby) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (GameNetworkManager.Instance.currentLobby.HasValue) { ((Lobby)(ref lobby)).SetData("mods", ModNotifyBase.ModListString); ModNotifyBase.Logger.LogInfo((object)("Set " + ((Lobby)(ref lobby)).GetData("name") + " mods to: " + ModNotifyBase.ModListString)); } yield break; } [HarmonyPatch(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated")] [HarmonyPrefix] public static bool OnLobbyCreated(ref GameNetworkManager __instance, Result result, ref Lobby lobby) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) if ((int)result == 1) { CoroutineHandler.Instance.NewCoroutine(SetLobbyData(lobby)); } return true; } [HarmonyPatch(typeof(GameNetworkManager), "StartHost")] [HarmonyPrefix] public static bool StartHost(ref GameNetworkManager __instance) { if (!ModNotifyBase.loadedMods) { CoroutineHandler.Instance.NewCoroutine(Connect()); CoroutineHandler.Instance.NewCoroutine(ModNotifyBase.InitializeModsCoroutine()); return false; } return true; } public static IEnumerator Connect() { yield return (object)new WaitUntil((Func<bool>)(() => ModNotifyBase.loadedMods)); GameNetworkManager.Instance.StartHost(); } [HarmonyPatch(typeof(GameNetworkManager), "LobbyDataIsJoinable")] [HarmonyPrefix] public static bool IsJoinable(ref Lobby lobby) { string data = ((Lobby)(ref lobby)).GetData("mods"); if (!Utility.IsNullOrWhiteSpace(data)) { serverModList = data.Split(ModNotifyBase.seperator); ModNotifyBase.Logger.LogWarning((object)(((Lobby)(ref lobby)).GetData("name") + " returned:")); try { string[] array = serverModList; foreach (string input in array) { string text = Regex.Replace(input, "\\[([\\d.]+)\\]", ""); string text2 = (Regex.Match(input, "\\[([\\d.]+)\\]").Groups[1].Value ?? "") ?? "No version number found"; string text3 = ""; if (Chainloader.PluginInfos.ContainsKey(text)) { PluginInfo obj = Chainloader.PluginInfos[text]; object obj2; if (obj == null) { obj2 = null; } else { BepInPlugin metadata = obj.Metadata; obj2 = ((metadata == null) ? null : metadata.Version?.ToString()); } text3 = (string)obj2; } string text4 = text; string text5 = ((!Utility.IsNullOrWhiteSpace(text3) && !Utility.IsNullOrWhiteSpace(text2) && !VersionUtil.ConvertToNumber(text2).Equals(VersionUtil.ConvertToNumber(text3))) ? (" (May be incompatible with your version v" + text3 + ")") : ""); Package package = ThunderstoreAPI.GetPackage(text); if (package != null) { text4 = Regex.Replace(input, "\\[([\\d.]+)\\]", "") + " v" + text2 + text5; } ModNotifyBase.Logger.LogWarning((object)text4); } } catch (Exception ex) { ModNotifyBase.Logger.LogError((object)ex); } } return true; } [HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")] [HarmonyPostfix] public static void JoinLobbyPostfix() { if (ModNotifyBase.ModList.Count == 0) { CoroutineHandler.Instance.NewCoroutine(ModNotifyBase.InitializeModsCoroutine()); } } [HarmonyPatch(typeof(MenuManager), "SetLoadingScreen")] [HarmonyPostfix] public static void SetLoadingScreenPatch(ref MenuManager __instance, ref RoomEnter result, ref bool isLoading, ref string overrideMessage) { //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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_0115: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) if (old == Vector2.zero) { old = ((Component)((TMP_Text)__instance.menuNotificationButtonText).transform.parent).GetComponent<RectTransform>().sizeDelta; } if ((int)result != 5 || !Utility.IsNullOrWhiteSpace(overrideMessage)) { ((Component)((TMP_Text)__instance.menuNotificationButtonText).transform.parent).GetComponent<RectTransform>().sizeDelta = old; return; } ((Component)((TMP_Text)__instance.menuNotificationButtonText).transform.parent).GetComponent<RectTransform>().sizeDelta = old; Package package = ThunderstoreAPI.GetPackage("CompatibilityChecker"); bool flag = VersionUtil.ConvertToNumber(package.Versions[0].VersionNumber) > VersionUtil.ConvertToNumber("1.1.6"); string text = (flag ? ("New CompatibilityChecker update is available! v" + package.Versions[0].VersionNumber + " != 1.1.6") : "[ Close ]"); if (flag & !isLoading) { ((Component)((TMP_Text)__instance.menuNotificationButtonText).transform.parent).GetComponent<RectTransform>().sizeDelta = new Vector2(256.375f, 58.244f); } if (ModNotifyBase.ModList.Count == 0) { CoroutineHandler.Instance.NewCoroutine(ModNotifyBase.InitializeModsCoroutine()); } if (Utility.IsNullOrWhiteSpace(overrideMessage) && Utility.IsNullOrWhiteSpace(GameNetworkManager.Instance.disconnectionReasonMessage) && !isLoading) { if (serverModList == null) { __instance.DisplayMenuNotification("Failed to join Modded Crew!\n Missing mods:\nCan't display: Host does not have CompatibilityChecker!", text); } else { GameNetworkManager instance = GameNetworkManager.Instance; object obj; if (instance == null) { obj = null; } else { Lobby value = instance.currentLobby.Value; obj = ((Lobby)(ref value)).GetData("name"); } string text2 = (string)obj; string[] array = serverModList.Except(ModNotifyBase.ModListArray).ToArray(); string[] array2 = ModNotifyBase.ModListArray.Except(serverModList).ToArray(); string text3 = ((array == null || array.Length == 0) ? "None..?" : string.Join("\n", array)); string text4 = ((array2 == null || array2.Length == 0) ? "None." : string.Join("\n\t\t", array2)); __instance.DisplayMenuNotification("Modded crew\n(Check logs/console for links)!\n Missing mods:\n" + text3, text); ModNotifyBase.Logger.LogError((object)("\nMissing server-sided mods from lobby \"" + text2 + "\":")); string[] array3 = array; foreach (string text5 in array3) { string text6 = text5; Package package2 = ThunderstoreAPI.GetPackage(text5); if (package2 != null) { string text7 = (Regex.Match(text5, "\\[([\\d.]+)\\]").Success ? ("v" + Regex.Match(text5, "\\[([\\d.]+)\\]").Value) : "No version number found"); text6 = string.Format("\n\t--Name: {0}\n\t--Link: {1}\n\t--Version: {2}\n\t--Downloads: {3}\n\t--Categories: [{4}]", text5, package2.PackageUrl, text7, package2.Versions[0].Downloads, string.Join(", ", package2.Categories)); } ModNotifyBase.Logger.LogError((object)text6); } ModNotifyBase.Logger.LogWarning((object)("Mods \"" + text2 + "\" may not be compatible with:\n\t\t" + text4)); serverModList = null; } } if (flag) { ModNotifyBase.Logger.LogWarning((object)("NEW VERSION OF COMPATIBILITY CHECKER IS AVAILABE. PLEASE UPDATE TO " + package.Versions[0].VersionNumber)); } } [HarmonyPatch(typeof(MenuManager), "connectionTimeOut")] [HarmonyPostfix] public static void timeoutPatch() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) if (GameNetworkManager.Instance.currentLobby.HasValue && serverModList == null) { Lobby value = GameNetworkManager.Instance.currentLobby.Value; serverModList = ((Lobby)(ref value)).GetData("mods")?.Split(ModNotifyBase.seperator); } } [HarmonyPatch(typeof(GameNetworkManager), "Singleton_OnClientConnectedCallback")] [HarmonyPostfix] public static void ConnectCallbackPatch() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) Lobby? currentLobby = GameNetworkManager.Instance.currentLobby; if ((Object)(object)StartOfRound.Instance != (Object)null && currentLobby.HasValue) { Lobby value = currentLobby.Value; if (Utility.IsNullOrWhiteSpace(((Lobby)(ref value)).GetData("mods"))) { ModNotifyBase.Logger.LogInfo((object)"Setting lobbys mods"); CoroutineHandler.Instance.NewCoroutine(SetLobbyData(currentLobby.Value)); } } } } } namespace CompatibilityChecker.MonoBehaviours { internal class CoroutineHandler : MonoBehaviour { private static CoroutineHandler instance; private List<Type> runningCoroutines = new List<Type>(); public static CoroutineHandler Instance { get { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if ((Object)(object)instance == (Object)null) { GameObject val = new GameObject("CoroutineHandler"); instance = val.AddComponent<CoroutineHandler>(); Object.DontDestroyOnLoad((Object)(object)val); } return instance; } } public void NewCoroutine(IEnumerator coroutine) { if (!IsCoroutineRunning(coroutine.GetType())) { runningCoroutines.Add(coroutine.GetType()); ((MonoBehaviour)this).StartCoroutine(ExecuteCoroutine(coroutine)); } else { ModNotifyBase.Logger.LogWarning((object)("Coroutine " + coroutine.GetType().FullName + " is already running")); } } private bool IsCoroutineRunning(Type coroutine) { return runningCoroutines.Any((Type runningCoroutine) => runningCoroutine == coroutine); } private IEnumerator ExecuteCoroutine(IEnumerator coroutine) { yield return ((MonoBehaviour)this).StartCoroutine(coroutine); runningCoroutines.Remove(coroutine.GetType()); } } public class SearchBox : MonoBehaviour { private TMP_InputField searchInputField; private GameObject canvas; public string Text = ""; public void Awake() { ModNotifyBase.Logger.LogInfo((object)"SearchBox: I have awoken"); } public void Start() { ModNotifyBase.Logger.LogInfo((object)"SearchBox: Start method called"); LoadCanvas(); } private void LoadCanvas() { canvas = GameObject.Find("/Canvas/MenuContainer/LobbyList"); if ((Object)(object)canvas == (Object)null) { ModNotifyBase.Logger.LogError((object)"SearchBox: Canvas not found. Make sure the hierarchy and names are correct."); return; } ModNotifyBase.Logger.LogInfo((object)"SearchBox: Canvas found. Creating search box."); CreateSearchBox(); } private void CreateSearchBox() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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_00a3: 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) ModNotifyBase.Logger.LogInfo((object)"SearchBox: Creating search box"); searchInputField = CreateInputField("Search..", Vector2.zero); ((UnityEvent<string>)(object)searchInputField.onEndEdit).AddListener((UnityAction<string>)OnEndEdit); RectTransform component = ((Component)searchInputField).GetComponent<RectTransform>(); component.sizeDelta = new Vector2(200f, 30f); component.anchoredPosition = new Vector2(0f, 0f); component.anchoredPosition = new Vector2(canvas.GetComponent<RectTransform>().sizeDelta.x / 2f, canvas.GetComponent<RectTransform>().sizeDelta.y / 2f); ((Component)searchInputField).transform.SetParent(canvas.transform, false); ((Component)searchInputField).gameObject.SetActive(false); ((Component)searchInputField).gameObject.SetActive(true); } private TMP_InputField CreateInputField(string placeholder, Vector2 position) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0024: 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_0046: Expected O, but got Unknown //IL_007d: 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_009d: Expected O, but got Unknown //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) TextMeshProUGUI component = GameObject.Find("/Canvas/MenuContainer/LobbyList/ListPanel/ListHeader").GetComponent<TextMeshProUGUI>(); GameObject val = new GameObject("SearchInputField"); RectTransform val2 = val.AddComponent<RectTransform>(); val2.anchoredPosition = position; TMP_InputField val3 = val.AddComponent<TMP_InputField>(); ((Selectable)val3).interactable = true; GameObject val4 = new GameObject("Placeholder"); val4.transform.SetParent(val.transform, false); TextMeshProUGUI val5 = val4.AddComponent<TextMeshProUGUI>(); ((TMP_Text)val5).text = placeholder; ((TMP_Text)val5).font = ((TMP_Text)component).font; ((Graphic)val5).color = ((Graphic)component).color; val3.placeholder = (Graphic)(object)val5; GameObject val6 = new GameObject("Text"); val6.transform.SetParent(val.transform, false); TextMeshProUGUI val7 = val6.AddComponent<TextMeshProUGUI>(); ((TMP_Text)val7).font = ((TMP_Text)component).font; ((Graphic)val7).color = ((Graphic)component).color; val3.textComponent = (TMP_Text)(object)val7; RectTransform component2 = ((Component)val3).GetComponent<RectTransform>(); component2.sizeDelta = new Vector2(200f, 30f); component2.anchoredPosition = new Vector2(0f, 0f); return val3; } private void OnEndEdit(string newValue) { Text = newValue; ModNotifyBase.Logger.LogInfo((object)("SearchBox: Search Value Changed - " + newValue)); SteamLobbyManager val = Object.FindObjectOfType<SteamLobbyManager>(); val.LoadServerList(); } } }
plugins/ScalingStartCredits.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; 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("ScalingStartCredits")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("ScalingStartCredits")] [assembly: AssemblyTitle("ScalingStartCredits")] [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 ScalingStartCredits { [BepInPlugin("sunnobunno.scalingstartcredits", "Scaling Start Credits", "1.0.1")] public class ScalingStartCreditsBase : BaseUnityPlugin { public const string modGUID = "sunnobunno.scalingstartcredits"; public const string modName = "Scaling Start Credits"; public const string modVersion = "1.0.1"; private readonly Harmony harmony = new Harmony("sunnobunno.scalingstartcredits"); public static ScalingStartCreditsBase? Instance; internal ManualLogSource? mls; public ConfigEntry<int> configCreditIncrement; public ConfigEntry<int> configPlayerCountThreshold; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } BindConfiguration(); mls = Logger.CreateLogSource("sunnobunno.scalingstartcredits"); mls.LogInfo((object)"sunnobunno.scalingstartcredits is loading."); harmony.PatchAll(); mls.LogInfo((object)"sunnobunno.scalingstartcredits is loaded."); } private void BindConfiguration() { configCreditIncrement = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Credit Increment", 15, "The amount of credits per player added to the starting group credits"); configPlayerCountThreshold = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Player Threshold", 4, "The number of players required in the lobby before credits are added per new player."); } } } namespace ScalingStartCredits.Patches { [HarmonyPatch(typeof(StartMatchLever))] internal class StartingCreditsPatch { private static ManualLogSource mls = Logger.CreateLogSource("sunnobunno.scalingstartcredits"); private static int groupCreditIncreaseIncrement; private static int playerThreshold; private static int playerCount; private static int days; private static HUDManager hudManager; [HarmonyPatch("StartGame")] [HarmonyPrefix] private static void StartMatchLeverPatch(ref StartOfRound ___playersManager) { //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Expected O, but got Unknown //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Expected O, but got Unknown groupCreditIncreaseIncrement = ScalingStartCreditsBase.Instance.configCreditIncrement.Value; playerThreshold = ScalingStartCreditsBase.Instance.configPlayerCountThreshold.Value; playerCount = ___playersManager.fullyLoadedPlayers.Count; days = ___playersManager.daysPlayersSurvivedInARow; bool flag = true; mls.LogInfo((object)$"Days: {days}"); mls.LogInfo((object)$"Player Count: {playerCount}"); if (days != 0) { mls.LogInfo((object)"No longer first day. Aborting"); flag = false; } if (playerCount <= playerThreshold && flag) { mls.LogInfo((object)"Player threshold not met. Aborting"); flag = false; } if (flag) { hudManager = (HUDManager)Object.FindObjectOfType(typeof(HUDManager)); Terminal val = (Terminal)Object.FindObjectOfType(typeof(Terminal)); int num = playerCount - playerThreshold; int num2 = num * groupCreditIncreaseIncrement; int num3 = val.groupCredits + num2; val.SyncGroupCreditsServerRpc(num3, val.numberOfItemsInDropship); mls.LogInfo((object)$"Credits Added for {num} players above threshold of {playerThreshold}: {num2}"); mls.LogInfo((object)$"Group Credits: {val.groupCredits}"); hudManager.AddTextToChatOnServer($"Credits Added for {num} players above threshold of {playerThreshold}: {num2}", -1); hudManager.AddTextToChatOnServer($"Group Credits: {val.groupCredits}", -1); } } } }
plugins/SkinwalkerMod.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dissonance.Config; using HarmonyLib; using Unity.Netcode; using UnityEngine; using UnityEngine.Networking; 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: AssemblyTitle("SkinwalkerMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SkinwalkerMod")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("fd4979a2-cef0-46af-8bf8-97e630b11475")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>(); NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); } } namespace SkinwalkerMod; [BepInPlugin("RugbugRedfern.SkinwalkerMod", "Skinwalker Mod", "1.0.8")] internal class PluginLoader : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("RugbugRedfern.SkinwalkerMod"); private const string modGUID = "RugbugRedfern.SkinwalkerMod"; private const string modVersion = "1.0.8"; private static bool initialized; public static PluginLoader Instance { get; private set; } private void Awake() { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown if (initialized) { return; } initialized = true; Instance = this; harmony.PatchAll(Assembly.GetExecutingAssembly()); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array = types; foreach (Type type in array) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array2 = methods; foreach (MethodInfo methodInfo in array2) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } SkinwalkerLogger.Initialize("RugbugRedfern.SkinwalkerMod"); SkinwalkerLogger.Log("SKINWALKER MOD STARTING UP 1.0.8"); SkinwalkerConfig.InitConfig(); SceneManager.sceneLoaded += SkinwalkerNetworkManagerHandler.ClientConnectInitializer; GameObject val = new GameObject("Skinwalker Mod"); val.AddComponent<SkinwalkerModPersistent>(); ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val); } public void BindConfig<T>(ref ConfigEntry<T> config, string section, string key, T defaultValue, string description = "") { config = ((BaseUnityPlugin)this).Config.Bind<T>(section, key, defaultValue, description); } } internal class SkinwalkerBehaviour : MonoBehaviour { private AudioSource audioSource; public const float PLAY_INTERVAL_MIN = 15f; public const float PLAY_INTERVAL_MAX = 40f; private const float MAX_DIST = 100f; private float nextTimeToPlayAudio; private EnemyAI ai; public void Initialize(EnemyAI ai) { this.ai = ai; audioSource = ai.creatureVoice; SetNextTime(); } private void Update() { //IL_0077: 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) if (!(Time.time > nextTimeToPlayAudio)) { return; } SetNextTime(); float num = -1f; if (Object.op_Implicit((Object)(object)ai) && !ai.isEnemyDead) { if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || (num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)this).transform.position)) < 100f) { AudioClip sample = SkinwalkerModPersistent.Instance.GetSample(); if (Object.op_Implicit((Object)(object)sample)) { SkinwalkerLogger.Log(((Object)this).name + " played voice line 1"); audioSource.PlayOneShot(sample); } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line 0"); } } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line no (too far away) " + num); } } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line no (dead) EnemyAI: " + (object)ai); } } private void SetNextTime() { if (SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value <= 0f) { nextTimeToPlayAudio = Time.time + 100000000f; } else { nextTimeToPlayAudio = Time.time + Random.Range(15f, 40f) / SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value; } } private T CopyComponent<T>(T original, GameObject destination) where T : Component { Type type = ((object)original).GetType(); Component val = destination.AddComponent(type); FieldInfo[] fields = type.GetFields(); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { fieldInfo.SetValue(val, fieldInfo.GetValue(original)); } return (T)(object)((val is T) ? val : null); } } internal class SkinwalkerConfig { public static ConfigEntry<bool> VoiceEnabled_BaboonHawk; public static ConfigEntry<bool> VoiceEnabled_Bracken; public static ConfigEntry<bool> VoiceEnabled_BunkerSpider; public static ConfigEntry<bool> VoiceEnabled_Centipede; public static ConfigEntry<bool> VoiceEnabled_CoilHead; public static ConfigEntry<bool> VoiceEnabled_EyelessDog; public static ConfigEntry<bool> VoiceEnabled_ForestGiant; public static ConfigEntry<bool> VoiceEnabled_GhostGirl; public static ConfigEntry<bool> VoiceEnabled_GiantWorm; public static ConfigEntry<bool> VoiceEnabled_HoardingBug; public static ConfigEntry<bool> VoiceEnabled_Hygrodere; public static ConfigEntry<bool> VoiceEnabled_Jester; public static ConfigEntry<bool> VoiceEnabled_Masked; public static ConfigEntry<bool> VoiceEnabled_Nutcracker; public static ConfigEntry<bool> VoiceEnabled_SporeLizard; public static ConfigEntry<bool> VoiceEnabled_Thumper; public static ConfigEntry<float> VoiceLineFrequency; public static void InitConfig() { PluginLoader.Instance.BindConfig(ref VoiceLineFrequency, "Voice Settings", "VoiceLineFrequency", 1f, "1 is the default, and voice lines will occur every " + 15f.ToString("0") + " to " + 40f.ToString("0") + " seconds per enemy. Setting this to 2 means they will occur twice as often, 0.5 means half as often, etc."); PluginLoader.Instance.BindConfig(ref VoiceEnabled_BaboonHawk, "Monster Voices", "Baboon Hawk", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Bracken, "Monster Voices", "Bracken", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_BunkerSpider, "Monster Voices", "Bunker Spider", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Centipede, "Monster Voices", "Centipede", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_CoilHead, "Monster Voices", "Coil Head", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_EyelessDog, "Monster Voices", "Eyeless Dog", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_ForestGiant, "Monster Voices", "Forest Giant", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_GhostGirl, "Monster Voices", "Ghost Girl", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_GiantWorm, "Monster Voices", "Giant Worm", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_HoardingBug, "Monster Voices", "Hoarding Bug", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Hygrodere, "Monster Voices", "Hygrodere", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Jester, "Monster Voices", "Jester", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Masked, "Monster Voices", "Masked", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Nutcracker, "Monster Voices", "Nutcracker", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_SporeLizard, "Monster Voices", "Spore Lizard", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Thumper, "Monster Voices", "Thumper", defaultValue: true); SkinwalkerLogger.Log("VoiceEnabled_BaboonHawk" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BaboonHawk.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Bracken" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Bracken.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_BunkerSpider" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BunkerSpider.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Centipede" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Centipede.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_CoilHead" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_CoilHead.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_EyelessDog" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_EyelessDog.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_ForestGiant" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_ForestGiant.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_GhostGirl" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GhostGirl.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_GiantWorm" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GiantWorm.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_HoardingBug" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_HoardingBug.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Hygrodere" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Hygrodere.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Jester" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Jester.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Masked" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Masked.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Nutcracker" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Nutcracker.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_SporeLizard" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_SporeLizard.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Thumper" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Thumper.Value}]"); SkinwalkerLogger.Log("VoiceLineFrequency" + $" VALUE LOADED FROM CONFIG: [{VoiceLineFrequency.Value}]"); } } internal static class SkinwalkerLogger { internal static ManualLogSource logSource; public static void Initialize(string modGUID) { logSource = Logger.CreateLogSource(modGUID); } public static void Log(object message) { logSource.LogInfo(message); } public static void LogError(object message) { logSource.LogError(message); } public static void LogWarning(object message) { logSource.LogWarning(message); } } public class SkinwalkerModPersistent : MonoBehaviour { private string audioFolder; private List<AudioClip> cachedAudio = new List<AudioClip>(); private float nextTimeToCheckFolder = 30f; private float nextTimeToCheckEnemies = 30f; private const float folderScanInterval = 8f; private const float enemyScanInterval = 5f; public static SkinwalkerModPersistent Instance { get; private set; } private void Awake() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) Instance = this; ((Component)this).transform.position = Vector3.zero; SkinwalkerLogger.Log("Skinwalker Mod Object Initialized"); audioFolder = Path.Combine(Application.dataPath, "..", "Dissonance_Diagnostics"); EnableRecording(); if (!Directory.Exists(audioFolder)) { Directory.CreateDirectory(audioFolder); } } private void Start() { try { if (Directory.Exists(audioFolder)) { Directory.Delete(audioFolder, recursive: true); } } catch (Exception message) { SkinwalkerLogger.Log(message); } } private void OnApplicationQuit() { DisableRecording(); } private void EnableRecording() { DebugSettings.Instance.EnablePlaybackDiagnostics = true; DebugSettings.Instance.RecordFinalAudio = true; } private void Update() { if (Time.realtimeSinceStartup > nextTimeToCheckFolder) { nextTimeToCheckFolder = Time.realtimeSinceStartup + 8f; if (!Directory.Exists(audioFolder)) { SkinwalkerLogger.Log("Audio folder not present. Don't worry about it, it will be created automatically when you play with friends. (" + audioFolder + ")"); return; } string[] files = Directory.GetFiles(audioFolder); SkinwalkerLogger.Log($"Got audio file paths ({files.Length})"); string[] array = files; foreach (string path in array) { ((MonoBehaviour)this).StartCoroutine(LoadWavFile(path, delegate(AudioClip audioClip) { cachedAudio.Add(audioClip); })); } } if (!(Time.realtimeSinceStartup > nextTimeToCheckEnemies)) { return; } nextTimeToCheckEnemies = Time.realtimeSinceStartup + 5f; EnemyAI[] array2 = Object.FindObjectsOfType<EnemyAI>(true); EnemyAI[] array3 = array2; SkinwalkerBehaviour skinwalkerBehaviour = default(SkinwalkerBehaviour); foreach (EnemyAI val in array3) { SkinwalkerLogger.Log("IsEnemyEnabled " + ((Object)val).name + " " + IsEnemyEnabled(val)); if (IsEnemyEnabled(val) && !((Component)val).TryGetComponent<SkinwalkerBehaviour>(ref skinwalkerBehaviour)) { ((Component)val).gameObject.AddComponent<SkinwalkerBehaviour>().Initialize(val); } } } private bool IsEnemyEnabled(EnemyAI enemy) { if ((Object)(object)enemy == (Object)null) { return false; } return ((Object)((Component)enemy).gameObject).name switch { "MaskedPlayerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Masked.Value, "NutcrackerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Nutcracker.Value, "BaboonHawkEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BaboonHawk.Value, "Flowerman(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Bracken.Value, "SandSpider(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BunkerSpider.Value, "RedLocustBees(Clone)" => false, "Centipede(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Centipede.Value, "SpringMan(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_CoilHead.Value, "MouthDog(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_EyelessDog.Value, "ForestGiant(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_ForestGiant.Value, "DressGirl(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GhostGirl.Value, "SandWorm(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GiantWorm.Value, "HoarderBug(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_HoardingBug.Value, "Blob(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Hygrodere.Value, "JesterEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Jester.Value, "PufferEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_SporeLizard.Value, "Crawler(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Thumper.Value, "DocileLocustBees(Clone)" => false, "DoublewingedBird(Clone)" => false, _ => true, }; } internal IEnumerator LoadWavFile(string path, Action<AudioClip> callback) { UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20); try { yield return www.SendWebRequest(); if ((int)www.result == 1) { SkinwalkerLogger.Log("Loaded clip from path " + path); AudioClip audioClip = DownloadHandlerAudioClip.GetContent(www); if (audioClip.length > 0.9f) { callback(audioClip); } try { File.Delete(path); } catch (Exception e) { SkinwalkerLogger.LogWarning(e); } } } finally { ((IDisposable)www)?.Dispose(); } } private void DisableRecording() { DebugSettings.Instance.EnablePlaybackDiagnostics = false; DebugSettings.Instance.RecordFinalAudio = false; if (Directory.Exists(audioFolder)) { Directory.Delete(audioFolder, recursive: true); } } public AudioClip GetSample() { if (cachedAudio.Count > 0) { int index = Random.Range(0, cachedAudio.Count - 1); AudioClip result = cachedAudio[index]; cachedAudio.RemoveAt(index); return result; } while (cachedAudio.Count > 200) { cachedAudio.RemoveAt(0); } return null; } public void ClearCache() { cachedAudio.Clear(); } } internal static class SkinwalkerNetworkManagerHandler { internal static void ClientConnectInitializer(Scene sceneName, LoadSceneMode sceneEnum) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown if (((Scene)(ref sceneName)).name == "SampleSceneRelay") { GameObject val = new GameObject("SkinwalkerNetworkManager"); val.AddComponent<NetworkObject>(); val.AddComponent<SkinwalkerNetworkManager>(); Debug.Log((object)"Initialized SkinwalkerNetworkManager"); } } } internal class SkinwalkerNetworkManager : NetworkBehaviour { public NetworkVariable<bool> VoiceEnabled_BaboonHawk = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Bracken = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_BunkerSpider = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Centipede = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_CoilHead = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_EyelessDog = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_ForestGiant = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_GhostGirl = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_GiantWorm = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_HoardingBug = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Hygrodere = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Jester = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Masked = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Nutcracker = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_SporeLizard = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Thumper = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<float> VoiceLineFrequency = new NetworkVariable<float>(1f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static SkinwalkerNetworkManager Instance { get; private set; } private void Awake() { Instance = this; if (GameNetworkManager.Instance.isHostingGame) { VoiceEnabled_BaboonHawk.Value = SkinwalkerConfig.VoiceEnabled_BaboonHawk.Value; VoiceEnabled_Bracken.Value = SkinwalkerConfig.VoiceEnabled_Bracken.Value; VoiceEnabled_BunkerSpider.Value = SkinwalkerConfig.VoiceEnabled_BunkerSpider.Value; VoiceEnabled_Centipede.Value = SkinwalkerConfig.VoiceEnabled_Centipede.Value; VoiceEnabled_CoilHead.Value = SkinwalkerConfig.VoiceEnabled_CoilHead.Value; VoiceEnabled_EyelessDog.Value = SkinwalkerConfig.VoiceEnabled_EyelessDog.Value; VoiceEnabled_ForestGiant.Value = SkinwalkerConfig.VoiceEnabled_ForestGiant.Value; VoiceEnabled_GhostGirl.Value = SkinwalkerConfig.VoiceEnabled_GhostGirl.Value; VoiceEnabled_GiantWorm.Value = SkinwalkerConfig.VoiceEnabled_GiantWorm.Value; VoiceEnabled_HoardingBug.Value = SkinwalkerConfig.VoiceEnabled_HoardingBug.Value; VoiceEnabled_Hygrodere.Value = SkinwalkerConfig.VoiceEnabled_Hygrodere.Value; VoiceEnabled_Jester.Value = SkinwalkerConfig.VoiceEnabled_Jester.Value; VoiceEnabled_Masked.Value = SkinwalkerConfig.VoiceEnabled_Masked.Value; VoiceEnabled_Nutcracker.Value = SkinwalkerConfig.VoiceEnabled_Nutcracker.Value; VoiceEnabled_SporeLizard.Value = SkinwalkerConfig.VoiceEnabled_SporeLizard.Value; VoiceEnabled_Thumper.Value = SkinwalkerConfig.VoiceEnabled_Thumper.Value; VoiceLineFrequency.Value = SkinwalkerConfig.VoiceLineFrequency.Value; SkinwalkerLogger.Log("HOST SENDING CONFIG TO CLIENTS"); } SkinwalkerLogger.Log("SkinwalkerNetworkManager Awake"); } public override void OnDestroy() { ((NetworkBehaviour)this).OnDestroy(); SkinwalkerLogger.Log("SkinwalkerNetworkManager OnDestroy"); SkinwalkerModPersistent.Instance?.ClearCache(); } protected override void __initializeVariables() { if (VoiceEnabled_BaboonHawk == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BaboonHawk cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_BaboonHawk).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk, "VoiceEnabled_BaboonHawk"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk); if (VoiceEnabled_Bracken == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Bracken cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Bracken).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Bracken, "VoiceEnabled_Bracken"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Bracken); if (VoiceEnabled_BunkerSpider == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BunkerSpider cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_BunkerSpider).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider, "VoiceEnabled_BunkerSpider"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider); if (VoiceEnabled_Centipede == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Centipede cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Centipede).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Centipede, "VoiceEnabled_Centipede"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Centipede); if (VoiceEnabled_CoilHead == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_CoilHead cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_CoilHead).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_CoilHead, "VoiceEnabled_CoilHead"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_CoilHead); if (VoiceEnabled_EyelessDog == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_EyelessDog cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_EyelessDog).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_EyelessDog, "VoiceEnabled_EyelessDog"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_EyelessDog); if (VoiceEnabled_ForestGiant == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_ForestGiant cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_ForestGiant).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_ForestGiant, "VoiceEnabled_ForestGiant"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_ForestGiant); if (VoiceEnabled_GhostGirl == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GhostGirl cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_GhostGirl).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GhostGirl, "VoiceEnabled_GhostGirl"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GhostGirl); if (VoiceEnabled_GiantWorm == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GiantWorm cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_GiantWorm).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GiantWorm, "VoiceEnabled_GiantWorm"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GiantWorm); if (VoiceEnabled_HoardingBug == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_HoardingBug cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_HoardingBug).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_HoardingBug, "VoiceEnabled_HoardingBug"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_HoardingBug); if (VoiceEnabled_Hygrodere == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Hygrodere cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Hygrodere).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Hygrodere, "VoiceEnabled_Hygrodere"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Hygrodere); if (VoiceEnabled_Jester == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Jester cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Jester).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Jester, "VoiceEnabled_Jester"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Jester); if (VoiceEnabled_Masked == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Masked cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Masked).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Masked, "VoiceEnabled_Masked"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Masked); if (VoiceEnabled_Nutcracker == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Nutcracker cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Nutcracker).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Nutcracker, "VoiceEnabled_Nutcracker"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Nutcracker); if (VoiceEnabled_SporeLizard == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_SporeLizard cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_SporeLizard).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_SporeLizard, "VoiceEnabled_SporeLizard"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_SporeLizard); if (VoiceEnabled_Thumper == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Thumper cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Thumper).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Thumper, "VoiceEnabled_Thumper"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Thumper); if (VoiceLineFrequency == null) { throw new Exception("SkinwalkerNetworkManager.VoiceLineFrequency cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceLineFrequency).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceLineFrequency, "VoiceLineFrequency"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceLineFrequency); ((NetworkBehaviour)this).__initializeVariables(); } protected internal override string __getTypeName() { return "SkinwalkerNetworkManager"; } }
plugins/SolosBodycams.dll
Decompiled a year 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"; }
plugins/Suit Saver.dll
Decompiled a year agousing System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using GameNetcodeStuff; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("Suit Saver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Suit Saver")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("cb7cfb30-b06e-4e41-9de7-03640e1662ea")] [assembly: AssemblyFileVersion("1.1.2.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyVersion("1.0.0.0")] namespace SuitSaver { [BepInPlugin("Hexnet.lethalcompany.suitsaver", "Suit Saver", "1.1.2")] public class SuitSaver : BaseUnityPlugin { private const string modGUID = "Hexnet.lethalcompany.suitsaver"; private const string modName = "Suit Saver"; private const string modVersion = "1.1.2"; private readonly Harmony harmony = new Harmony("Hexnet.lethalcompany.suitsaver"); private void Awake() { harmony.PatchAll(); Debug.Log((object)"[SS]: Suit Saver loaded successfully!"); } } } namespace SuitSaver.Patches { [HarmonyPatch] internal class Patches { [HarmonyPatch(typeof(StartOfRound))] internal class StartPatch { [HarmonyPatch("ResetShip")] [HarmonyPostfix] private static void ResetShipPatch() { Debug.Log((object)"[SS]: Ship has been reset!"); Debug.Log((object)"[SS]: Reloading suit..."); LoadSuitFromFile(); } } [HarmonyPatch(typeof(UnlockableSuit))] internal class SuitPatch { [HarmonyPatch("SwitchSuitClientRpc")] [HarmonyPostfix] private static void SyncSuit(ref UnlockableSuit __instance, int playerID) { PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; int num = (int)localPlayerController.playerClientId; if (playerID != num) { UnlockableSuit.SwitchSuitForPlayer(StartOfRound.Instance.allPlayerScripts[playerID], __instance.syncedSuitID.Value, true); } } [HarmonyPatch("SwitchSuitToThis")] [HarmonyPostfix] private static void EquipSuitPatch() { PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; string unlockableName = StartOfRound.Instance.unlockablesList.unlockables[localPlayerController.currentSuitID].unlockableName; SaveToFile(unlockableName); Debug.Log((object)("[SS]: Successfully saved current suit. (" + unlockableName + ")")); } } [HarmonyPatch(typeof(PlayerControllerB))] internal class JoinGamePatch { [HarmonyPatch("ConnectClientToPlayerObject")] [HarmonyPostfix] private static void LoadSuitPatch(ref PlayerControllerB __instance) { ((Component)GameNetworkManager.Instance.localPlayerController).gameObject.AddComponent<EquipAfterSyncPatch>(); } } internal class EquipAfterSyncPatch : MonoBehaviour { private void Start() { ((MonoBehaviour)this).StartCoroutine(LoadSuit()); } private IEnumerator LoadSuit() { Debug.Log((object)"[SS]: Waiting for suits to sync..."); yield return (object)new WaitForSeconds(1f); LoadSuitFromFile(); } } public static string SavePath = Application.persistentDataPath + "\\suitsaver.txt"; private static void SaveToFile(string suitName) { File.WriteAllText(SavePath, suitName); } private static string LoadFromFile() { if (File.Exists(SavePath)) { return File.ReadAllText(SavePath); } return "-1"; } private static UnlockableSuit GetSuitByName(string Name) { List<UnlockableItem> unlockables = StartOfRound.Instance.unlockablesList.unlockables; UnlockableSuit[] array = Resources.FindObjectsOfTypeAll<UnlockableSuit>(); foreach (UnlockableSuit val in array) { if (val.syncedSuitID.Value >= 0) { string unlockableName = unlockables[val.syncedSuitID.Value].unlockableName; if (unlockableName == Name) { return val; } } } return null; } private static void LoadSuitFromFile() { string text = LoadFromFile(); PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; if (!(text == "-1")) { UnlockableSuit suitByName = GetSuitByName(text); if ((Object)(object)suitByName != (Object)null) { UnlockableSuit.SwitchSuitForPlayer(localPlayerController, suitByName.syncedSuitID.Value, false); suitByName.SwitchSuitServerRpc((int)localPlayerController.playerClientId); Debug.Log((object)("[SS]: Successfully loaded saved suit. (" + text + ")")); } else { Debug.Log((object)("[SS]: Failed to load saved suit. Perhaps it's locked? (" + text + ")")); } } } } }
plugins/TooManyEmotes.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using Dissonance.Integrations.Unity_NFGO; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using MoreCompany.Cosmetics; using TMPro; using TooManyEmotes.Config; using TooManyEmotes.Input; using TooManyEmotes.Networking; using TooManyEmotes.Patches; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Animations.Rigging; using UnityEngine.EventSystems; using UnityEngine.Experimental.Rendering; using UnityEngine.InputSystem; using UnityEngine.Rendering; 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: AssemblyTitle("TooManyEmotes")] [assembly: AssemblyDescription("Mod made by flipf17")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TooManyEmotes")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("d6950625-e3a1-4896-a183-87110491bf18")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace TooManyEmotes { [HarmonyPatch] public static class EmoteMenuManager { public static GameObject menuGameObject; public static RectTransform menuTransform; public static CanvasGroup canvasGroup; public static RawImage renderTextureImageUI; public static TextMeshPro swapPageText; public static TextMeshPro currentEmoteText; public static RenderTexture renderTexture; public static Camera renderingCamera; public static GameObject previewPlayerObject; public static SkinnedMeshRenderer previewPlayerMesh; public static Animator previewPlayerAnimator; public static AnimatorOverrideController previewPlayerAnimatorController; public static int playerLayer = LayerMask.NameToLayer("Player"); public static float hoveredAlpha = 0.75f; public static float unhoveredAlpha = 0.75f; public static Color defaultUIColor = new Color(0.3f, 0.3f, 0.3f); public static List<EmoteUIElement> emoteUIElementsList; public static int hoveredEmoteUIIndex = -1; public static int currentPage = 0; public static List<EmoteLoadoutUIElement> emoteLoadoutUIElementsList; public static List<List<UnlockableEmote>> emoteLoadouts; public static Color selectedLoadoutUIColor = new Color(0.2f, 0.2f, 1f); public static int currentLoadoutIndex = -1; public static int numLoadouts = 3; public static int hoveredLoadoutUIIndex = -1; public static QuickMenuManager quickMenuManager => StartOfRound.Instance?.localPlayerController?.quickMenuManager; public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController; public static int playerLayerMask => 1 << playerLayer; public static int hoveredEmoteIndex => (hoveredEmoteUIIndex >= 0) ? (hoveredEmoteUIIndex + 8 * currentPage) : (-1); public static int numPages => (currentLoadoutEmotesList != null) ? (Mathf.Max((currentLoadoutEmotesList.Count - 1) / emoteUIElementsList.Count, 0) + 1) : 0; public static UnlockableEmote previewingEmote => (currentLoadoutEmotesList != null && hoveredEmoteIndex >= 0 && hoveredEmoteIndex < currentLoadoutEmotesList.Count) ? currentLoadoutEmotesList[hoveredEmoteIndex] : null; public static List<UnlockableEmote> currentLoadoutEmotesList => (emoteLoadouts != null && currentLoadoutIndex >= 0 && currentLoadoutIndex < emoteLoadouts.Count) ? emoteLoadouts[currentLoadoutIndex] : null; public static bool isMenuOpen => (Object)(object)menuGameObject != (Object)null && menuGameObject.activeSelf; [HarmonyPatch(typeof(HUDManager), "Start")] [HarmonyPostfix] public static void InitializeUI(HUDManager __instance) { if (!ConfigSettings.disableEmotesForSelf.Value && !((Object)(object)Plugin.radialMenuPrefab == (Object)null)) { menuGameObject = Object.Instantiate<GameObject>(Plugin.radialMenuPrefab, __instance.HUDContainer.transform.parent); menuGameObject.transform.SetAsLastSibling(); ((Object)menuGameObject).name = "EmotesRadialMenu"; menuTransform = menuGameObject.GetComponent<RectTransform>(); renderTextureImageUI = menuGameObject.GetComponentInChildren<RawImage>(); Transform transform = ((Component)((Transform)menuTransform).Find("RadialMenuUI/RadialElements")).transform; swapPageText = ((Component)((Transform)menuTransform).Find("RadialMenuUI/RadialBase/SwapPageText")).GetComponent<TextMeshPro>(); currentEmoteText = ((Component)((Transform)menuTransform).Find("RadialMenuUI/RadialBase/CurrentEmoteText")).GetComponent<TextMeshPro>(); ((TMP_Text)currentEmoteText).text = ""; emoteUIElementsList = new List<EmoteUIElement>(); currentPage = 0; hoveredEmoteUIIndex = -1; for (int i = 0; i < transform.childCount; i++) { Transform child = transform.GetChild(i); EmoteUIElement item = new EmoteUIElement { uiGameObject = ((Component)child).gameObject, id = i, backgroundImage = ((Component)child).GetComponentInChildren<Image>(), textContainer = ((Component)child).GetComponentInChildren<TextMeshPro>() }; emoteUIElementsList.Add(item); } EmoteLoadoutUIElement.uiCount = 0; Transform transform2 = ((Component)((Transform)menuTransform).Find("RadialMenuUI/EmoteLoadouts")).transform; ((Component)transform2).gameObject.AddComponent<EmoteLoadoutUIContainer>(); emoteLoadoutUIElementsList = new List<EmoteLoadoutUIElement>(); emoteLoadoutUIElementsList.Add(((Component)transform2.GetChild(0)).gameObject.AddComponent<EmoteLoadoutUIElement>()); emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2)); emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2)); emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2)); emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2)); emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2)); emoteLoadoutUIElementsList.Add(Object.Instantiate<EmoteLoadoutUIElement>(emoteLoadoutUIElementsList[0], transform2)); for (int j = 0; j < emoteLoadoutUIElementsList.Count; j++) { ((Object)emoteLoadoutUIElementsList[j]).name = "EmoteLoadout_" + j; } emoteLoadoutUIElementsList[0].loadoutName = "Favorites"; emoteLoadoutUIElementsList[1].loadoutName = $"<color={UnlockableEmote.rarityColorCodes[3]}>Legendary</color>"; emoteLoadoutUIElementsList[2].loadoutName = $"<color={UnlockableEmote.rarityColorCodes[2]}>Rare</color>"; emoteLoadoutUIElementsList[3].loadoutName = $"<color={UnlockableEmote.rarityColorCodes[1]}>Uncommon</color>"; emoteLoadoutUIElementsList[4].loadoutName = $"<color={UnlockableEmote.rarityColorCodes[0]}>Common</color>"; emoteLoadoutUIElementsList[5].loadoutName = "Complementary"; emoteLoadoutUIElementsList[6].loadoutName = "All"; SaveManager.LoadFavoritedEmotes(); emoteLoadouts = new List<List<UnlockableEmote>> { StartOfRoundPatcher.unlockedFavoriteEmotes, StartOfRoundPatcher.unlockedEmotesTier3, StartOfRoundPatcher.unlockedEmotesTier2, StartOfRoundPatcher.unlockedEmotesTier1, StartOfRoundPatcher.unlockedEmotesTier0, StartOfRoundPatcher.complementaryEmotes, StartOfRoundPatcher.unlockedEmotes }; if (currentLoadoutIndex < 0 || currentLoadoutIndex >= emoteLoadouts.Count) { currentLoadoutIndex = emoteLoadouts.Count - 1; } InitializeAnimationRenderer(); menuGameObject.SetActive(false); } } [HarmonyPatch(typeof(HUDManager), "Update")] [HarmonyPostfix] public static void GetInput() { //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_008c: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: 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) if (ConfigSettings.disableEmotesForSelf.Value || (Object)(object)previewPlayerAnimatorController == (Object)null || !isMenuOpen) { return; } if (EmoteLoadoutUIContainer.hovered || hoveredLoadoutUIIndex != -1) { if (hoveredEmoteUIIndex != -1) { OnHoveredNewElement(-1); } return; } Vector2 val = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue(); Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor((float)(Screen.width / 2), (float)(Screen.height / 2)); Vector2 val3 = val - val2; int num = -1; if (((Vector2)(ref val3)).magnitude / (float)Screen.height >= 0.17f) { float num2 = Mathf.Atan2(val3.y, 0f - val3.x) * 57.29578f - 67.5f; if (num2 < 0f) { num2 += 360f; } num = Mathf.FloorToInt(num2 / 45f); } if (num != hoveredEmoteUIIndex) { OnHoveredNewElement(num); } } public static void OnHoveredNewLoadoutElement(int index) { if (hoveredLoadoutUIIndex == index) { return; } hoveredLoadoutUIIndex = index; foreach (EmoteLoadoutUIElement emoteLoadoutUIElements in emoteLoadoutUIElementsList) { emoteLoadoutUIElements.OnHover(emoteLoadoutUIElements.id == index); } } public static void OnHoveredNewElement(int index) { if (hoveredEmoteUIIndex != -1 && hoveredEmoteUIIndex != index) { emoteUIElementsList[hoveredEmoteUIIndex].OnHover(hovered: false); } if (index != -1) { emoteUIElementsList[index].OnHover(); } hoveredEmoteUIIndex = index; SetPreviewAnimation(hoveredEmoteIndex); } public static void SwapPrevPage() { currentPage--; if (currentPage < 0) { currentPage = numPages - 1; } UpdateEmoteWheel(); } public static void SwapNextPage() { currentPage++; if (currentPage >= numPages) { currentPage = 0; } UpdateEmoteWheel(); } public static void UpdateEmoteWheel() { //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0165: 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_01b9: Unknown result type (might be due to invalid IL or missing references) currentPage = Mathf.Clamp(currentPage, 0, numPages - 1); ((TMP_Text)swapPageText).text = $"[{currentPage + 1} / {numPages}]\n[Mouse Scroll]"; for (int i = 0; i < emoteLoadoutUIElementsList.Count; i++) { EmoteLoadoutUIElement emoteLoadoutUIElement = emoteLoadoutUIElementsList[i]; emoteLoadoutUIElement.OnHover(hoveredLoadoutUIIndex == emoteLoadoutUIElement.id); } for (int j = 0; j < emoteLoadouts.Count; j++) { List<UnlockableEmote> list = emoteLoadouts[j]; EmoteLoadoutUIElement emoteLoadoutUIElement2 = emoteLoadoutUIElementsList[j]; string text = ((TMP_Text)emoteLoadoutUIElement2.textContainer).text; int num = text.IndexOf(" "); text = text[..((num == -1) ? text.Length : num)] + " [" + list.Count + "]"; ((TMP_Text)emoteLoadoutUIElement2.textContainer).text = text; } for (int k = 0; k < emoteUIElementsList.Count; k++) { EmoteUIElement emoteUIElement = emoteUIElementsList[k]; int num2 = k + 8 * currentPage; ((TMP_Text)emoteUIElement.textContainer).text = ""; emoteUIElement.emote = null; Color baseColor = defaultUIColor; if (num2 < currentLoadoutEmotesList.Count) { UnlockableEmote unlockableEmote = currentLoadoutEmotesList[num2]; if (unlockableEmote != null) { emoteUIElement.emote = unlockableEmote; ((TMP_Text)emoteUIElement.textContainer).text = unlockableEmote.displayName; } } emoteUIElement.baseColor = baseColor; emoteUIElement.OnHover(hovered: false); } if (hoveredEmoteUIIndex >= 0 && hoveredEmoteUIIndex < 8) { OnHoveredNewElement(hoveredEmoteUIIndex); } } public static void SetPreviewAnimation(int emoteIndex) { if (emoteIndex >= 0 && emoteIndex < currentLoadoutEmotesList.Count && currentLoadoutEmotesList[emoteIndex] != null) { UnlockableEmote unlockableEmote = currentLoadoutEmotesList[emoteIndex]; previewPlayerObject.SetActive(true); ((Behaviour)renderingCamera).enabled = true; previewPlayerAnimatorController["EmoteStart"] = unlockableEmote.animationClip; previewPlayerAnimatorController["EmoteLoop"] = (((Object)(object)unlockableEmote.transitionsToClip != (Object)null) ? unlockableEmote.transitionsToClip : null); previewPlayerAnimator.SetBool("hasTransition", (Object)(object)unlockableEmote.transitionsToClip != (Object)null); previewPlayerAnimator.Play("EmoteStart", 0, 0f); ((TMP_Text)currentEmoteText).text = "[" + unlockableEmote.displayNameColorCoded + "]\n[MMB] " + (StartOfRoundPatcher.allFavoriteEmotes.Contains(unlockableEmote.emoteName) ? "Unfavorite" : "Favorite"); } else { previewPlayerAnimatorController["EmoteStart"] = null; previewPlayerAnimatorController["EmoteLoop"] = null; previewPlayerObject.SetActive(false); ((TMP_Text)currentEmoteText).text = ""; DisableRenderCameraNextFrame(); } } public static void DisableRenderCameraNextFrame() { ((MonoBehaviour)HUDManager.Instance).StartCoroutine(DisableRenderCameraNextFrameCoroutine()); static IEnumerator DisableRenderCameraNextFrameCoroutine() { yield return null; ((Behaviour)renderingCamera).enabled = false; } } public static void SetCurrentEmoteLoadout(int loadoutIndex) { if (currentLoadoutIndex != loadoutIndex) { currentPage = 0; currentLoadoutIndex = loadoutIndex; UpdateEmoteWheel(); } } public static void ToggleFavoriteHoveredEmote() { if (isMenuOpen && previewingEmote != null) { string emoteName = previewingEmote.emoteName; if (StartOfRoundPatcher.allFavoriteEmotes.Contains(emoteName)) { StartOfRoundPatcher.allFavoriteEmotes.Remove(emoteName); } else { StartOfRoundPatcher.allFavoriteEmotes.Add(emoteName); } StartOfRoundPatcher.UpdateUnlockedFavoriteEmotes(); SaveManager.SaveFavoritedEmotes(); UpdateEmoteWheel(); } } public static void ToggleEmoteMenu() { if (!isMenuOpen) { OpenEmoteMenu(); } else { CloseEmoteMenu(); } } public static void OpenEmoteMenu() { menuGameObject.SetActive(true); Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; quickMenuManager.isMenuOpen = true; ((Renderer)previewPlayerMesh).material = ((Renderer)localPlayerController.thisPlayerModel).material; UpdateEmoteWheel(); } public static void CloseEmoteMenu() { Cursor.lockState = (CursorLockMode)1; Cursor.visible = false; localPlayerController.isFreeCamera = false; menuGameObject.SetActive(false); quickMenuManager.CloseQuickMenu(); } public static bool CanOpenEmoteMenu() { if ((quickMenuManager.isMenuOpen && !isMenuOpen) || (Object)(object)previewPlayerObject == (Object)null) { return false; } if (localPlayerController.isPlayerDead || localPlayerController.inTerminalMenu || localPlayerController.isTypingChat || localPlayerController.isPlayerDead || localPlayerController.inSpecialInteractAnimation || localPlayerController.isGrabbingObjectAnimation || localPlayerController.inShockingMinigame || localPlayerController.isClimbingLadder || localPlayerController.isSinking || (Object)(object)localPlayerController.inAnimationWithEnemy != (Object)null) { return false; } return true; } private static void InitializeAnimationRenderer() { //IL_0006: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) renderingCamera = new GameObject("AnimationRenderingCamera").AddComponent<Camera>(); Object.Destroy((Object)(object)((Component)renderingCamera).GetComponent<AudioListener>()); renderingCamera.cullingMask = playerLayerMask; renderingCamera.clearFlags = (CameraClearFlags)2; renderingCamera.cameraType = (CameraType)4; renderingCamera.backgroundColor = new Color(0.1f, 0.1f, 0.1f, 0f); renderingCamera.allowHDR = false; renderingCamera.allowMSAA = false; renderingCamera.farClipPlane = 5f; renderTexture = new RenderTexture(1024, 1024, 24); renderTexture.format = (RenderTextureFormat)0; renderTexture.graphicsFormat = (GraphicsFormat)8; renderTexture.depthStencilFormat = (GraphicsFormat)92; renderingCamera.targetTexture = renderTexture; ((Component)renderingCamera).transform.position = Vector3.down * 1000f; renderTextureImageUI.texture = (Texture)(object)renderTexture; Light val = new GameObject("Spotlight").AddComponent<Light>(); val.type = (LightType)0; ((Component)val).transform.position = ((Component)renderingCamera).transform.position; ((Component)val).transform.parent = ((Component)renderingCamera).transform; ((Component)val).transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity); val.intensity = 50f; val.range = 40f; val.innerSpotAngle = 100f; val.spotAngle = 120f; ((Component)val).gameObject.layer = playerLayer; DisableRenderCameraNextFrame(); } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void InitializePlayerCloneRenderObject(PlayerControllerB __instance) { if (!ConfigSettings.disableEmotesForSelf.Value && !((Object)(object)Plugin.radialMenuPrefab == (Object)null)) { ((MonoBehaviour)__instance).StartCoroutine(InitPlayerCloneAfterSpawnAnimation()); } IEnumerator InitPlayerCloneAfterSpawnAnimation() { yield return (object)new WaitForSeconds(2f); previewPlayerObject = Object.Instantiate<GameObject>(((Component)__instance).gameObject, ((Component)renderingCamera).transform); ((Object)previewPlayerObject).name = "PreviewPlayerAnimationObject"; GameObject modelGameObject = ((Component)previewPlayerObject.transform.Find("ScavengerModel")).gameObject; GameObject metarigGameObject = ((Component)modelGameObject.transform.Find("metarig")).gameObject; PlayerControllerB copyPlayerController = previewPlayerObject.GetComponentInChildren<PlayerControllerB>(); ((Renderer)copyPlayerController.thisPlayerModel).shadowCastingMode = (ShadowCastingMode)1; previewPlayerMesh = copyPlayerController.thisPlayerModel; Object.Destroy((Object)(object)modelGameObject.GetComponentInChildren<LODGroup>()); Object.DestroyImmediate((Object)(object)metarigGameObject.GetComponentInChildren<RigBuilder>()); Object.DestroyImmediate((Object)(object)copyPlayerController.playerBodyAnimator); previewPlayerAnimator = metarigGameObject.AddComponent<Animator>(); previewPlayerAnimatorController = new AnimatorOverrideController(Plugin.previewAnimatorController); previewPlayerAnimator.runtimeAnimatorController = (RuntimeAnimatorController)(object)previewPlayerAnimatorController; previewPlayerAnimator.Play("EmoteStart", 0, 0f); Object.Destroy((Object)(object)previewPlayerObject.GetComponent<NfgoPlayer>()); foreach (Transform item in previewPlayerObject.transform) { Transform child3 = item; if (((Object)child3).name != "ScavengerModel") { Object.Destroy((Object)(object)((Component)child3).gameObject); } } foreach (Transform item2 in modelGameObject.transform) { Transform child2 = item2; if (((Object)child2).name != "LOD1" && ((Object)child2).name != "metarig") { Object.Destroy((Object)(object)((Component)child2).gameObject); } } foreach (Transform item3 in metarigGameObject.transform) { Transform child = item3; if (((Object)child).name != "spine") { Object.Destroy((Object)(object)((Component)child).gameObject); } } previewPlayerObject.transform.position = ((Component)renderingCamera).transform.position + ((Component)renderingCamera).transform.forward * 2.8f + Vector3.down * 1.35f; previewPlayerObject.transform.LookAt(new Vector3(((Component)renderingCamera).transform.position.x, previewPlayerObject.transform.position.y, ((Component)renderingCamera).transform.position.z)); SetObjectLayerRecursive(previewPlayerObject, playerLayer); MonoBehaviour[] components = previewPlayerObject.GetComponents<MonoBehaviour>(); foreach (MonoBehaviour script in components) { Object.Destroy((Object)(object)script); } } } private static void SetObjectLayerRecursive(GameObject obj, int layer) { if (!((Object)(object)obj == (Object)null)) { obj.layer = layer; for (int i = 0; i < obj.transform.childCount; i++) { Transform child = obj.transform.GetChild(i); SetObjectLayerRecursive((child != null) ? ((Component)child).gameObject : null, layer); } } } [HarmonyPatch(typeof(PlayerControllerB), "ScrollMouse_performed")] [HarmonyPrefix] public static bool OnScrollMouse(CallbackContext context, PlayerControllerB __instance) { if (ConfigSettings.disableEmotesForSelf.Value || !isMenuOpen || (Object)(object)__instance != (Object)(object)localPlayerController || !((CallbackContext)(ref context)).performed) { return true; } if (((CallbackContext)(ref context)).ReadValue<float>() < 0f && !ConfigSettings.reverseEmoteWheelScrollDirection.Value) { SwapPrevPage(); } else { SwapNextPage(); } return false; } [HarmonyPatch(typeof(PlayerControllerB), "ItemSecondaryUse_performed")] [HarmonyPrefix] public static bool PreventItemSecondaryUseInMenu(CallbackContext context) { if (ConfigSettings.disableEmotesForSelf.Value) { return true; } return !isMenuOpen; } [HarmonyPatch(typeof(PlayerControllerB), "ItemTertiaryUse_performed")] [HarmonyPrefix] public static bool PreventItemTertiaryUseInMenu(CallbackContext context) { if (ConfigSettings.disableEmotesForSelf.Value) { return true; } return !isMenuOpen; } [HarmonyPatch(typeof(PlayerControllerB), "Interact_performed")] [HarmonyPrefix] public static bool PreventInteractInMenu(CallbackContext context) { if (ConfigSettings.disableEmotesForSelf.Value) { return true; } return !isMenuOpen; } [HarmonyPatch(typeof(QuickMenuManager), "OpenQuickMenu")] [HarmonyPrefix] public static bool OnOpenQuickMenu() { if (!isMenuOpen) { return true; } CloseEmoteMenu(); return false; } [HarmonyPatch(typeof(QuickMenuManager), "CloseQuickMenu")] [HarmonyPostfix] public static void OnCloseQuickMenu() { if (isMenuOpen) { CloseEmoteMenu(); } } [HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")] [HarmonyPostfix] public static void OnLocalPlayerDeath(Vector3 bodyVelocity, PlayerControllerB __instance) { if (isMenuOpen && (Object)(object)__instance == (Object)(object)localPlayerController && __instance.isPlayerDead) { CloseEmoteMenu(); } } } public class EmoteUIElement { public GameObject uiGameObject; public int id; public Image backgroundImage; public TextMeshPro textContainer; public Color baseColor; public UnlockableEmote emote; public void OnHover(bool hovered = true) { //IL_0002: 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_001b: 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) Color color = baseColor * (hovered ? 1f : 0.5f); color.a = (hovered ? EmoteMenuManager.hoveredAlpha : EmoteMenuManager.unhoveredAlpha); ((Graphic)backgroundImage).color = color; } } public class EmoteLoadoutUIElement : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler { public static int uiCount; public int id; public string loadoutName; public Image backgroundImage; public TextMeshPro textContainer; private void Awake() { id = uiCount++; backgroundImage = ((Component)this).GetComponentInChildren<Image>(); textContainer = ((Component)this).GetComponentInChildren<TextMeshPro>(); } private void Start() { ((TMP_Text)textContainer).text = loadoutName; } public void OnHover(bool hovered = true) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) Color color = ((EmoteMenuManager.currentLoadoutIndex == id) ? EmoteMenuManager.selectedLoadoutUIColor : EmoteMenuManager.defaultUIColor) * (hovered ? 1f : 0.5f); color.a = (hovered ? EmoteMenuManager.hoveredAlpha : EmoteMenuManager.unhoveredAlpha); ((Graphic)backgroundImage).color = color; } public void OnPointerEnter(PointerEventData eventData) { EmoteMenuManager.OnHoveredNewLoadoutElement(id); OnHover(); } public void OnPointerExit(PointerEventData eventData) { EmoteMenuManager.OnHoveredNewLoadoutElement(-1); OnHover(hovered: false); } } public class EmoteLoadoutUIContainer : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler { public static bool hovered; public void OnPointerEnter(PointerEventData eventData) { hovered = true; } public void OnPointerExit(PointerEventData eventData) { hovered = false; } } public class UnlockableEmote { public int emoteId; public string emoteName; public string randomEmotePoolName = ""; public string displayName = ""; public bool purchasable = true; public AnimationClip animationClip; public AnimationClip transitionsToClip = null; public List<UnlockableEmote> randomEmotePool; public bool complementary = false; public bool isPose = false; public bool canSyncEmote = false; public bool favorite = false; public int rarity = 0; public static string[] rarityColorCodes = new string[4] { ConfigSettings.emoteNameColorTier0.Value, ConfigSettings.emoteNameColorTier1.Value, ConfigSettings.emoteNameColorTier2.Value, ConfigSettings.emoteNameColorTier3.Value }; public string displayNameColorCoded => $"<color={nameColor}>{displayName}</color>"; public string rarityText { get { if (rarity == 0) { return "Common"; } if (rarity == 1) { return "Uncommon"; } if (rarity == 2) { return "Rare"; } if (rarity == 3) { return "Legendary"; } return "Invalid"; } } public int price { get { int num = -1; if (complementary) { num = 0; } else if (rarity == 0) { num = ConfigSync.instance.syncBasePriceEmoteTier0; } else if (rarity == 1) { num = ConfigSync.instance.syncBasePriceEmoteTier1; } else if (rarity == 2) { num = ConfigSync.instance.syncBasePriceEmoteTier2; } else if (rarity == 3) { num = ConfigSync.instance.syncBasePriceEmoteTier3; } return (int)Mathf.Max((float)num * ConfigSync.instance.syncPriceMultiplierEmotesStore, 0f); } } public string nameColor => rarityColorCodes[rarity]; } [BepInPlugin("FlipMods.TooManyEmotes", "TooManyEmotes", "1.7.6")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { private Harmony _harmony; public static Plugin instance; public static List<AnimationClip> customAnimationClips; public static Dictionary<string, AnimationClip> customAnimationClipsLoopDict = new Dictionary<string, AnimationClip>(); public static List<AnimationClip> complementaryAnimationClips; public static List<AnimationClip> animationClipsTier0; public static List<AnimationClip> animationClipsTier1; public static List<AnimationClip> animationClipsTier2; public static List<AnimationClip> animationClipsTier3; public static AnimationClip idleClip; public static GameObject radialMenuPrefab; public static RuntimeAnimatorController previewAnimatorController; public static Dictionary<string, AudioClip> musicClips; private void Awake() { //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Expected O, but got Unknown instance = this; ConfigSettings.BindConfigSettings(); Keybinds.InitKeybinds(); customAnimationClips = new List<AnimationClip>(); customAnimationClipsLoopDict = new Dictionary<string, AnimationClip>(); complementaryAnimationClips = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_complementary")); animationClipsTier0 = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_0")); animationClipsTier1 = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_1")); animationClipsTier2 = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_2")); animationClipsTier3 = new List<AnimationClip>(LoadEmoteAssetBundle("Assets/emotes_3")); AnimationClip[] array = LoadEmoteAssetBundle("Assets/emotes_misc"); if (array != null && array.Length >= 1) { AnimationClip[] array2 = array; foreach (AnimationClip val in array2) { if (((Object)val).name.Contains("idle")) { idleClip = val; } } } customAnimationClips.AddRange(complementaryAnimationClips); customAnimationClips.AddRange(animationClipsTier0); customAnimationClips.AddRange(animationClipsTier1); customAnimationClips.AddRange(animationClipsTier2); customAnimationClips.AddRange(animationClipsTier3); foreach (AnimationClip customAnimationClip in customAnimationClips) { if (((Object)customAnimationClip).name.StartsWith("fn_")) { ((Object)customAnimationClip).name = ((Object)customAnimationClip).name.Replace("fn_", ""); } if (((Object)customAnimationClip).name.EndsWith("_loop")) { customAnimationClipsLoopDict.Add(((Object)customAnimationClip).name, customAnimationClip); } } foreach (AnimationClip value in customAnimationClipsLoopDict.Values) { customAnimationClips.Remove(value); } LoadRadialMenuAsset(); _harmony = new Harmony("TooManyEmotes"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"TooManyEmotes loaded"); } public static bool IsModLoaded(string guid) { return Chainloader.PluginInfos.ContainsKey(guid); } private static AnimationClip[] LoadEmoteAssetBundle(string assetBundleName) { try { string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)instance).Info.Location), assetBundleName); AssetBundle val = AssetBundle.LoadFromFile(text); AnimationClip[] array = val.LoadAllAssets<AnimationClip>(); Log($"Successfully loaded {array.Length} animation clips from asset bundle: {assetBundleName}"); return array; } catch { LogError("Failed to load emotes asset bundle: " + assetBundleName + "."); return (AnimationClip[])(object)new AnimationClip[0]; } } public static void LoadRadialMenuAsset() { try { string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)instance).Info.Location), "Assets/radial_menu"); AssetBundle val = AssetBundle.LoadFromFile(text); radialMenuPrefab = val.LoadAsset<GameObject>("RadialMenu"); previewAnimatorController = val.LoadAsset<RuntimeAnimatorController>("PreviewAnimatorController"); Log("Successfully loaded radial menu asset."); } catch { LogError("Failed to load radial menu asset."); } } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } public static void LogWarning(string message) { ((BaseUnityPlugin)instance).Logger.LogWarning((object)message); } public static void LogError(string message) { ((BaseUnityPlugin)instance).Logger.LogError((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.TooManyEmotes"; public const string PLUGIN_NAME = "TooManyEmotes"; public const string PLUGIN_VERSION = "1.7.6"; } } namespace TooManyEmotes.Config { public static class ConfigSettings { public static ConfigEntry<bool> unlockEverything; public static ConfigEntry<bool> shareEverything; public static ConfigEntry<bool> syncUnsharedEmotes; public static ConfigEntry<bool> disableRaritySystem; public static ConfigEntry<int> basePriceEmoteRaritySystemDisabled; public static ConfigEntry<int> startingEmoteCredits; public static ConfigEntry<float> addEmoteCreditsMultiplier; public static ConfigEntry<bool> purchaseEmotesWithDefaultCurrency; public static ConfigEntry<float> priceMultiplierEmotesStore; public static ConfigEntry<int> basePriceEmoteTier0; public static ConfigEntry<int> basePriceEmoteTier1; public static ConfigEntry<int> basePriceEmoteTier2; public static ConfigEntry<int> basePriceEmoteTier3; public static ConfigEntry<int> numEmotesStoreRotation; public static ConfigEntry<float> rotationChanceEmoteTier0; public static ConfigEntry<float> rotationChanceEmoteTier1; public static ConfigEntry<float> rotationChanceEmoteTier2; public static ConfigEntry<float> rotationChanceEmoteTier3; public static ConfigEntry<bool> enableMaskedEnemiesEmoting; public static ConfigEntry<float> maskedEnemiesEmoteChanceOnEncounter; public static ConfigEntry<bool> maskedEnemiesAlwaysEmoteOnFirstEncounter; public static ConfigEntry<bool> enableSyncingEmotesWithMaskedEnemies; public static ConfigEntry<bool> overrideStopAndStareDuration; public static ConfigEntry<string> maskedEnemyEmoteRandomDelay; public static ConfigEntry<string> maskedEnemyEmoteRandomDuration; public static ConfigEntry<bool> disableEmotesForSelf; public static ConfigEntry<string> openEmoteMenuKeybind; public static ConfigEntry<string> rotateCharacterInEmoteKeybind; public static ConfigEntry<bool> toggleEmoteMenu; public static ConfigEntry<bool> reverseEmoteWheelScrollDirection; public static ConfigEntry<string> emoteNameColorTier0; public static ConfigEntry<string> emoteNameColorTier1; public static ConfigEntry<string> emoteNameColorTier2; public static ConfigEntry<string> emoteNameColorTier3; public static Dictionary<string, ConfigEntryBase> currentConfigEntries = new Dictionary<string, ConfigEntryBase>(); public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); unlockEverything = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Emote Settings", "I am a Party Pooper", false, "[Host only] If true, every emote will be unlocked in your emote wheel at the start of the game. Also, you're not really a party pooper."); shareEverything = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Emote Settings", "ShareEverything", true, "[Host only] If set to false, emotes in the store will be different for each player. Unlocking emotes will only unlock for the player that purchased the emote. Each player will have their own emote credits. The amount of emote credits that each player will receive will NOT be reduced."); syncUnsharedEmotes = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Emote Settings", "CanSyncUnsharedEmotes", true, "[Host only] Only applies if ShareEverything is false. If set to true, players will be able to sync emotes with other players, even if they do not have the emote being performed unlocked."); disableRaritySystem = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Emote Settings", "DisableRaritySystem", false, "[Host only] If true, every emote will have the same likelyhood of appearing in the emote store."); basePriceEmoteRaritySystemDisabled = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Emote Settings", "BasePriceEmote - Rarity System Disabled", 100, "[Host only] Base price of emotes if the rarity system is disabled."); startingEmoteCredits = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Emote Settings", "StartingEmoteCredits", 100, "[Host only] The number of emote credits you start each game with."); addEmoteCreditsMultiplier = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Emote Settings", "AddEmoteCreditsMultiplier", 0.5f, "[Host only] You gain emote credits based off this multiplier of normal group credits earned. Example: If set to the default, 0.5, and you earn 200 group credits, you will also gain 100 emote credits."); purchaseEmotesWithDefaultCurrency = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Emote Settings", "PurchaseEmotesWithDefaultCredits", true, "[Host only] Setting this to true will allow you to purchase emotes with normal group credits once you run out of emote credits. This setting will automatically be disabled if ShareEverything is false."); priceMultiplierEmotesStore = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Emote Settings", "PriceMultiplierEmotesStore", 1f, "[Host only] Price multiplier for emotes in the store. Only applies if UnlockEverythingAtStart is false."); basePriceEmoteTier0 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Emote Settings", "PriceCommonEmote", 50, "[Host only] The base price of [common]emotes in the store."); basePriceEmoteTier1 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Emote Settings", "PriceUncommonEmote", 100, "[Host only] The base price of [uncommon] emotes in the store."); basePriceEmoteTier2 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Emote Settings", "PriceRareEmote", 200, "[Host only] The base price of [rare] emotes in the store."); basePriceEmoteTier3 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Emote Settings", "PriceLegendaryEmote", 300, "[Host only] The base price of [legendary] emotes in the store."); numEmotesStoreRotation = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("Emote Settings", "EmotesInStoreRotation", 6, "[Host only] The number of emotes that will be available at a time in the store. Only applies if UnlockEverythingAtStart is false."); rotationChanceEmoteTier0 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Emote Settings", "RotationWeightCommonEmote", 0.55f, "[Host only] The likelyhood of [common] emotes appearing (per slot) in the store rotation."); rotationChanceEmoteTier1 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Emote Settings", "RotationWeightUncommonEmote", 0.35f, "[Host only] The likelyhood of [uncommon] emotes appearing (per slot) in the store rotation."); rotationChanceEmoteTier2 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Emote Settings", "RotationWeightRareEmote", 0.08f, "[Host only] The likelyhood of [rare] emotes appearing (per slot) in the store rotation."); rotationChanceEmoteTier3 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("Emote Settings", "RotationWeightLegendaryEmote", 0.02f, "[Host only] The likelyhood of [legendary] emotes appearing (per slot) in the store rotation."); enableMaskedEnemiesEmoting = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("MaskedEnemyEmotes - Beta", "EnableMaskedEnemiesEmoting", true, "[Host only] Enabling this alone does not change the behaviour of the Masked Enemies, and shouldn't conflict with other mods."); maskedEnemiesEmoteChanceOnEncounter = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("MaskedEnemyEmotes - Beta", "EmoteChanceOnEncounter", 0.25f, "[Host only] Chance per encounter with a Masked Enemy, for them to perform an emote. Use values between 0 and 1."); maskedEnemiesAlwaysEmoteOnFirstEncounter = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("MaskedEnemyEmotes - Beta", "AlwaysEmoteOnFirstEncounter", true, "[Host only] This will force the first encounter (for each player) with a Masked Enemy to trigger an emote, regardless of EmoteChanceOnEncounter."); enableSyncingEmotesWithMaskedEnemies = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("MaskedEnemyEmotes - Beta", "EnableSyncingEmotesWithMaskedEnemies", true, "[Client-side] Enabling this will allow you to sync emotes with Masked Enemies. This config is mainly here to disable in case of strange issues."); maskedEnemyEmoteRandomDelay = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("MaskedEnemyEmotes - Beta", "RandomEmoteDelay", "1.5,2.0", "[Host only] Random range at which Masked Enemies will delay before performing an emote. These values could be raised a bit if OverrideStopAndStareDuration is enabled, otherwise, you may run into emotes ending quickly."); overrideStopAndStareDuration = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("MaskedEnemyEmotes - Beta", "OverrideStopAndStareDuration", true, "[Host only] Enabling this will allow this mod to extend the stop and stare duration for longer emotes. If disabled, emotes may end very quickly. Disable this setting if you run into mod conflicts."); maskedEnemyEmoteRandomDuration = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("MaskedEnemyEmotes - Beta", "RandomEmoteDuration", "2.0,4.0", "[Host only] Random range on how long Masked Enemies will emote for. This will extend the Masked Enemies' stop and stare duration by this amount. Only applies if OverrideStopAndStareDuration is true."); disableEmotesForSelf = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Emote Radial Menu", "DisableEmotingForSelf", false, "Disabling this will not convert your player's animator controller to an AnimatorOverrideController, and you will not be able to perform custom emotes. Disable this in case of specific mod conflicts. You will still be able to see other players emoting."); openEmoteMenuKeybind = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Emote Radial Menu", "OpenEmoteMenuKeybind", "<Keyboard>/backquote", "This setting will be ignored if InputUtils is installed and enabled. (I recommend running InputUtils to edit keybinds in the in-game settings)"); rotateCharacterInEmoteKeybind = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Emote Radial Menu", "RotateCharacterInEmoteKeybind", "<Keyboard>/leftAlt", "Keybind to hold to rotate character while performing a custom emote. This setting will be ignored if InputUtils is installed and enabled. (I recommend running InputUtils to edit keybinds in the in-game settings)"); toggleEmoteMenu = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Emote Radial Menu", "ToggleEmoteMenu", true, "If set to false, the emote menu will open upon pressing the related keybind, and close upon releasing, and will play the currently hovered emote."); reverseEmoteWheelScrollDirection = ((BaseUnityPlugin)Plugin.instance).Config.Bind<bool>("Emote Radial Menu", "ReverseEmoteWheelScrollDirection", false, "Reverses the page swapping direction in your emote when scrolling."); emoteNameColorTier0 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Accessibility", "CommonEmoteNameColor", "#00FF00", "The color of the [common] emote name in the terminal."); emoteNameColorTier1 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Accessibility", "UncommonEmoteNameColor", "#2828FF", "The color of the [uncommon] emote name in the terminal."); emoteNameColorTier2 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Accessibility", "RareEmoteNameColor", "#AA00EE", "The color of the [rare] emote name in the terminal."); emoteNameColorTier3 = ((BaseUnityPlugin)Plugin.instance).Config.Bind<string>("Accessibility", "LegendaryEmoteNameColor", "#FF2222", "The color of the [legendary] emote name in the terminal."); currentConfigEntries.Add(((ConfigEntryBase)unlockEverything).Definition.Key, (ConfigEntryBase)(object)unlockEverything); currentConfigEntries.Add(((ConfigEntryBase)shareEverything).Definition.Key, (ConfigEntryBase)(object)shareEverything); currentConfigEntries.Add(((ConfigEntryBase)syncUnsharedEmotes).Definition.Key, (ConfigEntryBase)(object)syncUnsharedEmotes); currentConfigEntries.Add(((ConfigEntryBase)disableRaritySystem).Definition.Key, (ConfigEntryBase)(object)disableRaritySystem); currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteRaritySystemDisabled).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteRaritySystemDisabled); currentConfigEntries.Add(((ConfigEntryBase)startingEmoteCredits).Definition.Key, (ConfigEntryBase)(object)startingEmoteCredits); currentConfigEntries.Add(((ConfigEntryBase)addEmoteCreditsMultiplier).Definition.Key, (ConfigEntryBase)(object)addEmoteCreditsMultiplier); currentConfigEntries.Add(((ConfigEntryBase)purchaseEmotesWithDefaultCurrency).Definition.Key, (ConfigEntryBase)(object)purchaseEmotesWithDefaultCurrency); currentConfigEntries.Add(((ConfigEntryBase)priceMultiplierEmotesStore).Definition.Key, (ConfigEntryBase)(object)priceMultiplierEmotesStore); currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteTier0).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteTier0); currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteTier1).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteTier1); currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteTier2).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteTier2); currentConfigEntries.Add(((ConfigEntryBase)basePriceEmoteTier3).Definition.Key, (ConfigEntryBase)(object)basePriceEmoteTier3); currentConfigEntries.Add(((ConfigEntryBase)numEmotesStoreRotation).Definition.Key, (ConfigEntryBase)(object)numEmotesStoreRotation); currentConfigEntries.Add(((ConfigEntryBase)rotationChanceEmoteTier0).Definition.Key, (ConfigEntryBase)(object)rotationChanceEmoteTier0); currentConfigEntries.Add(((ConfigEntryBase)rotationChanceEmoteTier1).Definition.Key, (ConfigEntryBase)(object)rotationChanceEmoteTier1); currentConfigEntries.Add(((ConfigEntryBase)rotationChanceEmoteTier2).Definition.Key, (ConfigEntryBase)(object)rotationChanceEmoteTier2); currentConfigEntries.Add(((ConfigEntryBase)rotationChanceEmoteTier3).Definition.Key, (ConfigEntryBase)(object)rotationChanceEmoteTier3); currentConfigEntries.Add(((ConfigEntryBase)enableMaskedEnemiesEmoting).Definition.Key, (ConfigEntryBase)(object)enableMaskedEnemiesEmoting); currentConfigEntries.Add(((ConfigEntryBase)maskedEnemiesEmoteChanceOnEncounter).Definition.Key, (ConfigEntryBase)(object)maskedEnemiesEmoteChanceOnEncounter); currentConfigEntries.Add(((ConfigEntryBase)maskedEnemiesAlwaysEmoteOnFirstEncounter).Definition.Key, (ConfigEntryBase)(object)maskedEnemiesAlwaysEmoteOnFirstEncounter); currentConfigEntries.Add(((ConfigEntryBase)enableSyncingEmotesWithMaskedEnemies).Definition.Key, (ConfigEntryBase)(object)enableSyncingEmotesWithMaskedEnemies); currentConfigEntries.Add(((ConfigEntryBase)overrideStopAndStareDuration).Definition.Key, (ConfigEntryBase)(object)overrideStopAndStareDuration); currentConfigEntries.Add(((ConfigEntryBase)maskedEnemyEmoteRandomDelay).Definition.Key, (ConfigEntryBase)(object)maskedEnemyEmoteRandomDelay); currentConfigEntries.Add(((ConfigEntryBase)maskedEnemyEmoteRandomDuration).Definition.Key, (ConfigEntryBase)(object)maskedEnemyEmoteRandomDuration); currentConfigEntries.Add(((ConfigEntryBase)disableEmotesForSelf).Definition.Key, (ConfigEntryBase)(object)disableEmotesForSelf); currentConfigEntries.Add(((ConfigEntryBase)openEmoteMenuKeybind).Definition.Key, (ConfigEntryBase)(object)openEmoteMenuKeybind); currentConfigEntries.Add(((ConfigEntryBase)rotateCharacterInEmoteKeybind).Definition.Key, (ConfigEntryBase)(object)rotateCharacterInEmoteKeybind); currentConfigEntries.Add(((ConfigEntryBase)toggleEmoteMenu).Definition.Key, (ConfigEntryBase)(object)toggleEmoteMenu); currentConfigEntries.Add(((ConfigEntryBase)reverseEmoteWheelScrollDirection).Definition.Key, (ConfigEntryBase)(object)reverseEmoteWheelScrollDirection); currentConfigEntries.Add(((ConfigEntryBase)emoteNameColorTier0).Definition.Key, (ConfigEntryBase)(object)emoteNameColorTier0); currentConfigEntries.Add(((ConfigEntryBase)emoteNameColorTier1).Definition.Key, (ConfigEntryBase)(object)emoteNameColorTier1); currentConfigEntries.Add(((ConfigEntryBase)emoteNameColorTier2).Definition.Key, (ConfigEntryBase)(object)emoteNameColorTier2); currentConfigEntries.Add(((ConfigEntryBase)emoteNameColorTier3).Definition.Key, (ConfigEntryBase)(object)emoteNameColorTier3); float value = rotationChanceEmoteTier0.Value; value += rotationChanceEmoteTier1.Value; value += rotationChanceEmoteTier2.Value; value += rotationChanceEmoteTier3.Value; if (value != 1f && value != 0f) { ConfigEntry<float> obj = rotationChanceEmoteTier0; obj.Value /= value; ConfigEntry<float> obj2 = rotationChanceEmoteTier1; obj2.Value /= value; ConfigEntry<float> obj3 = rotationChanceEmoteTier2; obj3.Value /= value; ConfigEntry<float> obj4 = rotationChanceEmoteTier3; obj4.Value /= value; ((BaseUnityPlugin)Plugin.instance).Config.Save(); } TryRemoveOldConfigSettings(); ConfigSync.BuildDefaultConfigSync(); } public static string GetDisplayName(string key) { key = key.Replace("<Keyboard>/", ""); key = key.Replace("<Mouse>/", ""); string text = key.ToLower(); text = text.Replace("leftalt", "Alt"); text = text.Replace("rightalt", "Alt"); text = text.Replace("leftctrl", "Ctrl"); text = text.Replace("rightctrl", "Ctrl"); text = text.Replace("leftshift", "Shift"); text = text.Replace("rightshift", "Shift"); text = text.Replace("leftbutton", "LMB"); text = text.Replace("rightbutton", "RMB"); text = text.Replace("middlebutton", "MMB"); text = text.Replace("backquote", "`"); try { text = char.ToUpper(text[0]) + text.Substring(1); } catch { } return text; } public static void TryRemoveOldConfigSettings() { HashSet<string> hashSet = new HashSet<string>(); HashSet<string> hashSet2 = new HashSet<string>(); foreach (ConfigEntryBase value in currentConfigEntries.Values) { hashSet.Add(value.Definition.Section); hashSet2.Add(value.Definition.Key); } try { Plugin.Log("Cleaning old config entries"); ConfigFile config = ((BaseUnityPlugin)Plugin.instance).Config; string configFilePath = config.ConfigFilePath; if (!File.Exists(configFilePath)) { return; } string text = File.ReadAllText(configFilePath); string[] array = File.ReadAllLines(configFilePath); string text2 = ""; for (int i = 0; i < array.Length; i++) { array[i] = array[i].Replace("\n", ""); if (array[i].Length <= 0) { continue; } if (array[i].StartsWith("[")) { if (text2 != "" && !hashSet.Contains(text2)) { text2 = "[" + text2 + "]"; int num = text.IndexOf(text2); int num2 = text.IndexOf(array[i]); text = text.Remove(num, num2 - num); } text2 = array[i].Replace("[", "").Replace("]", "").Trim(); } else { if (!(text2 != "")) { continue; } if (i <= array.Length - 4 && array[i].StartsWith("##")) { int j; for (j = 1; i + j < array.Length && array[i + j].Length > 3; j++) { } if (hashSet.Contains(text2)) { int num3 = array[i + j - 1].IndexOf("="); string item = array[i + j - 1].Substring(0, num3 - 1); if (!hashSet2.Contains(item)) { int num4 = text.IndexOf(array[i]); int num5 = text.IndexOf(array[i + j - 1]) + array[i + j - 1].Length; text = text.Remove(num4, num5 - num4); } } i += j - 1; } else if (array[i].Length > 3) { text = text.Replace(array[i], ""); } } } if (!hashSet.Contains(text2)) { text2 = "[" + text2 + "]"; int num6 = text.IndexOf(text2); text = text.Remove(num6, text.Length - num6); } while (text.Contains("\n\n\n")) { text = text.Replace("\n\n\n", "\n\n"); } File.WriteAllText(configFilePath, text); config.Reload(); } catch { } } } } namespace TooManyEmotes.Input { internal class IngameKeybinds : LcInputActions { internal static IngameKeybinds Instance = new IngameKeybinds(); [InputAction("<Keyboard>/backquote", Name = "[TooManyEmotes]\nOpen Emote Menu")] public InputAction OpenEmoteMenuHotkey { get; set; } [InputAction("<Keyboard>/leftAlt", Name = "[TooManyEmotes]\nRotate Character in Emote")] public InputAction RotateCharacterEmoteHotkey { get; set; } [InputAction("<Mouse>/middleButton", Name = "[TooManyEmotes]\nFavorite Emote")] public InputAction FavoriteEmoteHotkey { get; set; } internal static InputActionAsset GetAsset() { return ((LcInputActions)Instance).Asset; } } internal class InputUtilsCompat { internal static InputActionAsset Asset => IngameKeybinds.GetAsset(); internal static bool Enabled => Plugin.IsModLoaded("com.rune580.LethalCompanyInputUtils"); public static InputAction OpenEmoteMenuHotkey => IngameKeybinds.Instance.OpenEmoteMenuHotkey; public static InputAction RotateCharacterEmoteHotkey => IngameKeybinds.Instance.RotateCharacterEmoteHotkey; public static InputAction FavoriteEmoteHotkey => IngameKeybinds.Instance.FavoriteEmoteHotkey; } [HarmonyPatch] public static class Keybinds { public static InputActionAsset Asset; public static InputActionMap ActionMap; private static InputAction OpenEmoteMenuAction; private static InputAction RotatePlayerEmoteAction; private static InputAction FavoriteEmoteAction; private static InputAction SelectEmoteUIAction; private static InputAction NextEmotePageAction; private static InputAction PrevEmotePageAction; public static InputAction RawScrollAction; public static bool holdingRotatePlayerModifier; public static PlayerControllerB localPlayerController => StartOfRound.Instance?.localPlayerController; public static void InitKeybinds() { //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Expected O, but got Unknown //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Expected O, but got Unknown //IL_0042: 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_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown Plugin.Log("Initializing custom emote hotkeys."); Plugin.Log("InputUtilsLoaded: " + InputUtilsCompat.Enabled); if (InputUtilsCompat.Enabled) { Asset = InputUtilsCompat.Asset; ActionMap = Asset.actionMaps[0]; OpenEmoteMenuAction = InputUtilsCompat.OpenEmoteMenuHotkey; RotatePlayerEmoteAction = InputUtilsCompat.RotateCharacterEmoteHotkey; FavoriteEmoteAction = InputUtilsCompat.FavoriteEmoteHotkey; SelectEmoteUIAction = new InputAction("TooManyEmotes.SelectEmote", (InputActionType)0, "<Mouse>/leftButton", "Press", (string)null, (string)null); RawScrollAction = new InputAction("TooManyEmotes.ScrollEmoteMenu", (InputActionType)0, "<Mouse>/scroll", (string)null, (string)null, (string)null); } else { Asset = new InputActionAsset(); ActionMap = new InputActionMap("TooManyEmotes"); InputActionSetupExtensions.AddActionMap(Asset, ActionMap); OpenEmoteMenuAction = InputActionSetupExtensions.AddAction(ActionMap, "TooManyEmotes.OpenEmoteMenu", (InputActionType)0, ConfigSettings.openEmoteMenuKeybind.Value, "Press", (string)null, (string)null, (string)null); RotatePlayerEmoteAction = InputActionSetupExtensions.AddAction(ActionMap, "TooManyEmotes.RotatePlayerEmote", (InputActionType)0, ConfigSettings.rotateCharacterInEmoteKeybind.Value, "Press", (string)null, (string)null, (string)null); FavoriteEmoteAction = InputActionSetupExtensions.AddAction(ActionMap, "TooManyEmotes.FavoriteEmote", (InputActionType)0, "<Mouse>/middleButton", "Press", (string)null, (string)null, (string)null); SelectEmoteUIAction = new InputAction("TooManyEmotes.SelectEmote", (InputActionType)0, "<Mouse>/leftButton", "Press", (string)null, (string)null); RawScrollAction = new InputAction("TooManyEmotes.ScrollEmoteMenu", (InputActionType)0, "<Mouse>/scroll", (string)null, (string)null, (string)null); } } [HarmonyPatch(typeof(StartOfRound), "OnEnable")] [HarmonyPostfix] public static void OnEnable() { Asset.Enable(); OpenEmoteMenuAction.performed += OnPressOpenEmoteMenu; OpenEmoteMenuAction.canceled += OnPressOpenEmoteMenu; FavoriteEmoteAction.performed += OnFavoriteEmote; RotatePlayerEmoteAction.performed += OnUpdateRotatePlayerEmoteModifier; RotatePlayerEmoteAction.canceled += OnUpdateRotatePlayerEmoteModifier; SelectEmoteUIAction.Enable(); SelectEmoteUIAction.performed += OnSelectEmoteUI; } [HarmonyPatch(typeof(StartOfRound), "OnDisable")] [HarmonyPostfix] public static void OnDisable() { Asset.Disable(); OpenEmoteMenuAction.performed -= OnPressOpenEmoteMenu; OpenEmoteMenuAction.canceled -= OnPressOpenEmoteMenu; FavoriteEmoteAction.performed -= OnFavoriteEmote; RotatePlayerEmoteAction.performed -= OnUpdateRotatePlayerEmoteModifier; RotatePlayerEmoteAction.canceled -= OnUpdateRotatePlayerEmoteModifier; SelectEmoteUIAction.Disable(); SelectEmoteUIAction.performed -= OnSelectEmoteUI; } private static void OnPressOpenEmoteMenu(CallbackContext context) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)localPlayerController == (Object)null || ConfigSettings.disableEmotesForSelf.Value) { return; } if (!EmoteMenuManager.isMenuOpen) { if (((CallbackContext)(ref context)).performed && EmoteMenuManager.CanOpenEmoteMenu()) { EmoteMenuManager.OpenEmoteMenu(); } } else if (ConfigSettings.toggleEmoteMenu.Value) { if (((CallbackContext)(ref context)).performed) { EmoteMenuManager.CloseEmoteMenu(); } } else if (((CallbackContext)(ref context)).canceled) { if (EmoteMenuManager.hoveredEmoteIndex != -1) { PerformEmoteLocal(context); } EmoteMenuManager.CloseEmoteMenu(); } } private static void OnSelectEmoteUI(CallbackContext context) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && EmoteMenuManager.isMenuOpen) { if (EmoteMenuManager.hoveredLoadoutUIIndex != -1 && EmoteMenuManager.hoveredLoadoutUIIndex != EmoteMenuManager.currentLoadoutIndex) { EmoteMenuManager.SetCurrentEmoteLoadout(EmoteMenuManager.hoveredLoadoutUIIndex); } else if (EmoteMenuManager.hoveredEmoteIndex >= 0 && EmoteMenuManager.hoveredEmoteIndex < EmoteMenuManager.currentLoadoutEmotesList.Count) { PerformEmoteLocal(context); EmoteMenuManager.CloseEmoteMenu(); } } } private static void OnSwapPrevEmotePage(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && EmoteMenuManager.isMenuOpen && EmoteMenuManager.numPages > 1) { EmoteMenuManager.SwapPrevPage(); } } private static void OnSwapNextEmotePage(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && EmoteMenuManager.isMenuOpen && EmoteMenuManager.numPages > 1) { EmoteMenuManager.SwapNextPage(); } } public static void PerformEmoteLocal(CallbackContext context) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) if (EmoteMenuManager.hoveredEmoteIndex >= 0 && EmoteMenuManager.hoveredEmoteIndex < EmoteMenuManager.currentLoadoutEmotesList.Count && !ConfigSettings.disableEmotesForSelf.Value) { UnlockableEmote unlockableEmote = EmoteMenuManager.currentLoadoutEmotesList[EmoteMenuManager.hoveredEmoteIndex]; if (unlockableEmote != null) { localPlayerController.PerformEmote(context, -(unlockableEmote.emoteId + 1)); } } } public static void OnFavoriteEmote(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && EmoteMenuManager.isMenuOpen && EmoteMenuManager.hoveredEmoteUIIndex != -1 && EmoteMenuManager.previewingEmote != null) { EmoteMenuManager.ToggleFavoriteHoveredEmote(); } } public static void OnUpdateRotatePlayerEmoteModifier(CallbackContext context) { if (!((Object)(object)localPlayerController == (Object)null) && !ConfigSettings.disableEmotesForSelf.Value) { if (((CallbackContext)(ref context)).performed) { holdingRotatePlayerModifier = true; } else if (((CallbackContext)(ref context)).canceled) { holdingRotatePlayerModifier = false; } } } } } namespace TooManyEmotes.Networking { [Serializable] [HarmonyPatch] public class ConfigSync { public static bool isSynced; public static ConfigSync defaultConfig; public static ConfigSync instance; public bool syncUnlockEverything; public bool syncShareEverything; public bool syncSyncUnsharedEmotes; public bool syncDisableRaritySystem; public int syncStartingEmoteCredits; public float syncAddEmoteCreditsMultiplier; public bool syncPurchaseEmotesWithDefaultCurrency; public float syncPriceMultiplierEmotesStore; public int syncBasePriceEmoteTier0; public int syncBasePriceEmoteTier1; public int syncBasePriceEmoteTier2; public int syncBasePriceEmoteTier3; public int syncNumEmotesStoreRotation; public float syncRotationChanceEmoteTier0; public float syncRotationChanceEmoteTier1; public float syncRotationChanceEmoteTier2; public float syncRotationChanceEmoteTier3; public bool syncEnableMaskedEnemiesEmoting; public float syncMaskedEnemiesEmoteChanceOnEncounter; public bool syncMaskedEnemiesAlwaysEmoteOnFirstEncounter; public bool syncOverrideStopAndStareDuration; public float syncMaskedEnemyEmoteRandomDelayMin; public float syncMaskedEnemyEmoteRandomDelayMax; public float syncMaskedEnemyEmoteRandomDurationMin; public float syncMaskedEnemyEmoteRandomDurationMax; public static Vector2 syncMaskedEnemyEmoteRandomDelay; public static Vector2 syncMaskedEnemyEmoteRandomDuration; public static HashSet<ulong> syncedClients; public ConfigSync() { //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) syncUnlockEverything = ConfigSettings.unlockEverything.Value; syncShareEverything = ConfigSettings.shareEverything.Value; syncSyncUnsharedEmotes = ConfigSettings.syncUnsharedEmotes.Value; syncDisableRaritySystem = ConfigSettings.disableRaritySystem.Value; syncStartingEmoteCredits = ConfigSettings.startingEmoteCredits.Value; syncAddEmoteCreditsMultiplier = ConfigSettings.addEmoteCreditsMultiplier.Value; syncPurchaseEmotesWithDefaultCurrency = ConfigSettings.purchaseEmotesWithDefaultCurrency.Value; syncPriceMultiplierEmotesStore = ConfigSettings.priceMultiplierEmotesStore.Value; syncNumEmotesStoreRotation = ConfigSettings.numEmotesStoreRotation.Value; syncRotationChanceEmoteTier0 = ConfigSettings.rotationChanceEmoteTier0.Value; syncRotationChanceEmoteTier1 = ConfigSettings.rotationChanceEmoteTier1.Value; syncRotationChanceEmoteTier2 = ConfigSettings.rotationChanceEmoteTier2.Value; syncRotationChanceEmoteTier3 = ConfigSettings.rotationChanceEmoteTier3.Value; syncEnableMaskedEnemiesEmoting = ConfigSettings.enableMaskedEnemiesEmoting.Value; syncMaskedEnemiesEmoteChanceOnEncounter = ConfigSettings.maskedEnemiesEmoteChanceOnEncounter.Value; syncMaskedEnemiesAlwaysEmoteOnFirstEncounter = ConfigSettings.maskedEnemiesAlwaysEmoteOnFirstEncounter.Value; syncOverrideStopAndStareDuration = ConfigSettings.overrideStopAndStareDuration.Value; syncMaskedEnemyEmoteRandomDelay = ParseVector2FromString(ConfigSettings.maskedEnemyEmoteRandomDelay.Value); syncMaskedEnemyEmoteRandomDelayMin = syncMaskedEnemyEmoteRandomDelay.x; syncMaskedEnemyEmoteRandomDelayMax = syncMaskedEnemyEmoteRandomDelay.y; syncMaskedEnemyEmoteRandomDuration = ParseVector2FromString(ConfigSettings.maskedEnemyEmoteRandomDuration.Value); syncMaskedEnemyEmoteRandomDurationMin = syncMaskedEnemyEmoteRandomDuration.x; syncMaskedEnemyEmoteRandomDurationMax = syncMaskedEnemyEmoteRandomDuration.y; if (ConfigSettings.disableRaritySystem.Value) { syncBasePriceEmoteTier0 = ConfigSettings.basePriceEmoteRaritySystemDisabled.Value; syncBasePriceEmoteTier1 = ConfigSettings.basePriceEmoteRaritySystemDisabled.Value; syncBasePriceEmoteTier2 = ConfigSettings.basePriceEmoteRaritySystemDisabled.Value; syncBasePriceEmoteTier3 = ConfigSettings.basePriceEmoteRaritySystemDisabled.Value; } else { syncBasePriceEmoteTier0 = ConfigSettings.basePriceEmoteTier0.Value; syncBasePriceEmoteTier1 = ConfigSettings.basePriceEmoteTier1.Value; syncBasePriceEmoteTier2 = ConfigSettings.basePriceEmoteTier2.Value; syncBasePriceEmoteTier3 = ConfigSettings.basePriceEmoteTier3.Value; } } public Vector2 ParseVector2FromString(string str) { //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_008b: 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_0094: 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_0082: 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_0080: Unknown result type (might be due to invalid IL or missing references) Vector2 result = Vector2.zero; try { string[] array = str.Split(new char[1] { ',' }); if (float.TryParse(array[0].Trim(new char[1] { ' ' }), out var result2) && float.TryParse(array[1].Trim(new char[1] { ' ' }), out var result3)) { result = new Vector2(Mathf.Min(Mathf.Abs(result2), Mathf.Abs(result3)), Mathf.Max(Mathf.Abs(result2), Mathf.Abs(result3))); } return result; } catch { } return Vector2.zero; } public static void BuildDefaultConfigSync() { defaultConfig = new ConfigSync(); instance = new ConfigSync(); } [HarmonyPatch(typeof(StartOfRound), "Awake")] [HarmonyPostfix] public static void ResetValues() { isSynced = false; } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void Init(PlayerControllerB __instance) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Expected O, but got Unknown if (isSynced) { return; } isSynced = NetworkManager.Singleton.IsServer; EmoteSyncManager.isSynced = false; EmoteSyncManager.requestedSync = false; if (NetworkManager.Singleton.IsServer) { syncedClients = new HashSet<ulong>(); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRequestConfigSyncServerRpc", new HandleNamedMessageDelegate(OnRequestConfigSyncServerRpc)); if (!instance.syncUnlockEverything) { return; } { foreach (UnlockableEmote allUnlockableEmote in StartOfRoundPatcher.allUnlockableEmotes) { StartOfRoundPatcher.UnlockEmoteLocal(allUnlockableEmote); } return; } } foreach (UnlockableEmote allUnlockableEmote2 in StartOfRoundPatcher.allUnlockableEmotes) { StartOfRoundPatcher.UnlockEmoteLocal(allUnlockableEmote2); } NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRequestConfigSyncClientRpc", new HandleNamedMessageDelegate(OnRequestConfigSyncClientRpc)); RequestConfigSync(); } public static void RequestConfigSync() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { Plugin.Log("Requesting config sync from server"); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(0, (Allocator)2, -1); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnRequestConfigSyncServerRpc", 0uL, val, (NetworkDelivery)3); } else { Plugin.LogError("Failed to send unlocked emote update to server."); } } private static void OnRequestConfigSyncServerRpc(ulong clientId, FastBufferReader reader) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsServer) { Plugin.Log("Receiving config sync request from client: " + clientId); syncedClients.Add(clientId); EmoteSyncManager.syncedClients.Remove(clientId); byte[] array = SerializeConfigToByteArray(instance); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4 + array.Length, (Allocator)2, -1); int num = array.Length; ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnRequestConfigSyncClientRpc", clientId, val, (NetworkDelivery)3); } } private static void OnRequestConfigSyncClientRpc(ulong clientId, FastBufferReader reader) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsClient) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(4)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); if (((FastBufferReader)(ref reader)).TryBeginRead(num)) { Plugin.Log("Receiving config sync from server."); byte[] data = new byte[num]; ((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0); instance = DeserializeFromByteArray(data); syncMaskedEnemyEmoteRandomDelay = new Vector2(instance.syncMaskedEnemyEmoteRandomDelayMin, instance.syncMaskedEnemyEmoteRandomDelayMax); syncMaskedEnemyEmoteRandomDuration = new Vector2(instance.syncMaskedEnemyEmoteRandomDurationMin, instance.syncMaskedEnemyEmoteRandomDurationMax); isSynced = true; if (StartOfRoundPatcher.allUnlockableEmotes != null && StartOfRoundPatcher.unlockedEmotes != null) { StartOfRoundPatcher.ResetProgressLocal(); if (instance.syncUnlockEverything) { StartOfRoundPatcher.UnlockEmotesLocal(StartOfRoundPatcher.allUnlockableEmotes); } else { StartOfRoundPatcher.UnlockEmotesLocal(StartOfRoundPatcher.complementaryEmotes); } StartOfRoundPatcher.UpdateUnlockedFavoriteEmotes(); } } else { Plugin.LogError("Error receiving sync from server."); } } else { Plugin.LogError("Error receiving bytes length."); } } public static byte[] SerializeConfigToByteArray(ConfigSync config) { BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(); binaryFormatter.Serialize(memoryStream, config); return memoryStream.ToArray(); } public static ConfigSync DeserializeFromByteArray(byte[] data) { MemoryStream serializationStream = new MemoryStream(data); BinaryFormatter binaryFormatter = new BinaryFormatter(); return (ConfigSync)binaryFormatter.Deserialize(serializationStream); } } [HarmonyPatch] public static class EmoteSyncManager { public static bool requestedSync; public static bool isSynced; public static HashSet<ulong> syncedClients; [HarmonyPatch(typeof(StartOfRound), "Awake")] [HarmonyPostfix] public static void ResetValues() { isSynced = false; requestedSync = false; } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void Init() { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Expected O, but got Unknown //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown isSynced = NetworkManager.Singleton.IsServer; requestedSync = NetworkManager.Singleton.IsServer; if (NetworkManager.Singleton.IsServer) { syncedClients = new HashSet<ulong>(); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRequestSyncServerRpc", new HandleNamedMessageDelegate(OnRequestSyncServerRpc)); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnUnlockEmoteServerRpc", new HandleNamedMessageDelegate(OnUnlockEmoteServerRpc)); } else { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRequestSyncClientRpc", new HandleNamedMessageDelegate(OnRequestSyncClientRpc)); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnUnlockEmoteClientRpc", new HandleNamedMessageDelegate(OnUnlockEmoteClientRpc)); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("TooManyEmotes-OnRotateEmotesClientRpc", new HandleNamedMessageDelegate(RotateEmoteSelectionClientRpc)); } } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] public static void RequestSyncAfterConfigUpdate(PlayerControllerB __instance) { if (!isSynced && !requestedSync && ConfigSync.isSynced && (Object)(object)__instance == (Object)(object)StartOfRound.Instance.localPlayerController) { SendSyncRequest(); requestedSync = true; } } public static void SendSyncRequest() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { Plugin.Log("Sending sync request to server."); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(0, (Allocator)2, -1); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnRequestSyncServerRpc", 0uL, val, (NetworkDelivery)3); } } private static void OnRequestSyncServerRpc(ulong clientId, FastBufferReader reader) { if (NetworkManager.Singleton.IsServer) { Plugin.Log("Receiving sync request from client: " + clientId); ServerSendSyncToClient(clientId); } } public static void ServerSendSyncToClient(ulong clientId) { //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: 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_0208: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer || !ConfigSync.syncedClients.Contains(clientId)) { return; } PlayerControllerB playerController = null; StartOfRoundPatcher.TryGetPlayerByClientId(clientId, out playerController); if ((Object)(object)playerController != (Object)null) { if (!StartOfRoundPatcher.unlockedEmotesByPlayer.ContainsKey(playerController.playerUsername)) { StartOfRoundPatcher.unlockedEmotesByPlayer.Add(playerController.playerUsername, new List<UnlockableEmote>()); } if (!TerminalPatcher.currentEmoteCreditsByPlayer.ContainsKey(playerController.playerUsername)) { TerminalPatcher.currentEmoteCreditsByPlayer.Add(playerController.playerUsername, ConfigSync.instance.syncStartingEmoteCredits); } } List<UnlockableEmote> list = StartOfRoundPatcher.unlockedEmotes; int num = TerminalPatcher.currentEmoteCredits; if (!ConfigSync.instance.syncUnlockEverything && !ConfigSync.instance.syncShareEverything) { if ((Object)(object)playerController != (Object)null) { if (StartOfRoundPatcher.unlockedEmotesByPlayer.TryGetValue(playerController.playerUsername, out var value)) { Plugin.Log("Loading " + value.Count + " unlocked emotes for player: " + playerController.playerUsername); list = value; } if (TerminalPatcher.currentEmoteCreditsByPlayer.TryGetValue(playerController.playerUsername, out var value2)) { Plugin.Log("Loading " + value2 + " emote credits for player: " + playerController.playerUsername); num = value2; } } else { Plugin.LogError("Error loading custom emotes for player. Player with id: " + clientId + " does not exist?"); list = StartOfRoundPatcher.complementaryEmotes; num = ConfigSync.instance.syncStartingEmoteCredits; } } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(12 + 4 * list.Count, (Allocator)2, -1); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref TerminalPatcher.emoteStoreSeed, default(ForPrimitives)); int count = list.Count; ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref count, default(ForPrimitives)); for (int i = 0; i < list.Count; i++) { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref list[i].emoteId, default(ForPrimitives)); } NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnRequestSyncClientRpc", clientId, val, (NetworkDelivery)3); } private static void OnRequestSyncClientRpc(ulong clientId, FastBufferReader reader) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0065: 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_0079: 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_0118: 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) if (!NetworkManager.Singleton.IsClient || !ConfigSync.isSynced) { return; } isSynced = true; if (((FastBufferReader)(ref reader)).TryBeginRead(12)) { StartOfRoundPatcher.ResetProgressLocal(); ((FastBufferReader)(ref reader)).ReadValue<int>(ref TerminalPatcher.currentEmoteCredits, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValue<int>(ref TerminalPatcher.emoteStoreSeed, default(ForPrimitives)); int num = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives)); TerminalPatcher.RotateNewEmoteSelection(); Plugin.Log("Receiving sync from server. CurrentEmoteCredits: " + TerminalPatcher.currentEmoteCredits + " EmoteStoreSeed: " + TerminalPatcher.emoteStoreSeed + " NumEmotes: " + num); if (num <= 0) { if (num == -1) { StartOfRoundPatcher.ResetEmotesLocal(); } } else { if (!((FastBufferReader)(ref reader)).TryBeginRead(4 * num)) { Plugin.LogError("Error receiving emotes sync from server."); return; } int emoteId = default(int); for (int i = 0; i < num; i++) { ((FastBufferReader)(ref reader)).ReadValue<int>(ref emoteId, default(ForPrimitives)); StartOfRoundPatcher.UnlockEmoteLocal(emoteId); } } isSynced = true; Plugin.Log("Received sync from server."); } else { Plugin.LogError("Error receiving sync from server."); } } public static void SendOnUnlockEmoteUpdate(int emoteId, int newEmoteCredits = -1) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(12, (Allocator)2, -1); Plugin.Log("Sending unlocked emote update to server. Emote id: " + emoteId); ((FastBufferWriter)(ref val)).WriteValue<int>(ref newEmoteCredits, default(ForPrimitives)); int num = 1; ((FastBufferWriter)(ref val)).WriteValue<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValue<int>(ref emoteId, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnUnlockEmoteServerRpc", 0uL, val, (NetworkDelivery)3); } public static void SendOnUnlockEmoteUpdateMulti(int newEmoteCredits = -1) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_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_0076: 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_00ae: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(8 + 4 * StartOfRoundPatcher.unlockedEmotes.Count, (Allocator)2, -1); Plugin.Log("Sending all unlocked emotes update to server."); ((FastBufferWriter)(ref val)).WriteValue<int>(ref newEmoteCredits, default(ForPrimitives)); int count = StartOfRoundPatcher.unlockedEmotes.Count; ((FastBufferWriter)(ref val)).WriteValue<int>(ref count, default(ForPrimitives)); foreach (UnlockableEmote unlockedEmote in StartOfRoundPatcher.unlockedEmotes) { ((FastBufferWriter)(ref val)).WriteValue<int>(ref unlockedEmote.emoteId, default(ForPrimitives)); } NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("TooManyEmotes-OnUnlockEmoteServerRpc", 0uL, val, (NetworkDelivery)3); } private static void OnUnlockEmoteServerRpc(ulong clientId, FastBufferReader reader) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0041: 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_00e0: 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_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(8)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives)); int num2 = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num2, default(ForPrimitives)); PlayerControllerB playerController = null; StartOfRoundPatcher.TryGetPlayerByClientId(clientId, out playerController); if (num != -1) { if (!ConfigSync.instance.syncShareEverything && clientId != 0) { if ((Object)(object)playerController != (Object)null) { TerminalPatcher.currentEmoteCreditsByPlayer[playerController.playerUsername] = num; } } else { TerminalPatcher.currentEmoteCredits = num; } } Plugin.Log("Receiving unlocked emote update from client for " + num2 + " emotes."); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(16 + 4 * num2, (Allocator)2, -1); ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref clientId, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref TerminalPatcher.currentEmoteCredits, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num2, default(ForPrimitives)); if (((FastBufferReader)(ref reader)).TryBeginRead(4 * num2)) { int emoteId = default(int); for (int i = 0; i < num2; i++) { ((FastBufferReader)(ref reader)).ReadValue<int>(ref emoteId, default(ForPrimitives)); if (!ConfigSync.instance.syncShareEverything && clientId != 0) { if ((Object)(object)playerController != (Object)null) { StartOfRoundPatcher.UnlockEmoteLocal(emoteId, playerController.playerUsername); } } else { StartOfRoundPatcher.UnlockEmoteLocal(emoteId); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref emoteId, default(ForPrimitives)); } } NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("TooManyEmotes-OnUnlockEmoteClientRpc", val, (NetworkDelivery)3); } else { Plugin.LogError("Failed to receive unlocked emote updates from client. Expected updates: " + num2); } } else { Plugin.LogError("Failed to receive unlocked emote update from client."); } } private static void OnUnlockEmoteClientRpc(ulong clientId, FastBufferReader reader) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0062: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsClient || NetworkManager.Singleton.IsServer) { return; } if (((FastBufferReader)(ref reader)).TryBeginRead(16)) { ulong clientId2 = default(ulong); ((FastBufferReader)(ref reader)).ReadValue<ulong>(ref clientId2, default(ForPrimitives)); int num = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num, default(ForPrimitives)); int num2 = default(int); ((FastBufferReader)(ref reader)).ReadValue<int>(ref num2, default(ForPrimitives)); PlayerControllerB playerController = null; if (!ConfigSync.instance.syncShareEverything && !StartOfRoundPatcher.TryGetPlayerByClientId(clientId2, out playerController)) { return; } if (num != -1) { TerminalPatcher.currentEmoteCredits = num; } if (((FastBufferReader)(ref reader)).TryBeginRead(4 * num2)) { int emoteId = default(int); for (int i = 0; i < num2; i++) { ((FastBufferReader)(ref reader)).ReadValue<int>(ref emoteId, default(ForPrimitives)); Plugin.Log("Receiving unlocked emote update from server. Emote id: " + emoteId); if (ConfigSync.instance.syncShareEverything) { StartOfRoundPatcher.UnlockEmoteLocal(emoteId); } else { StartOfRoundPatcher.UnlockEmoteLocal(emoteId, playerController.playerUsername); } } } else { Plugin.LogError("Failed to receive unlocked emote updates from client. Expected updates: " + num2); } } else { Plugin.LogError("Failed to receive unlocked emote update from client."); } } public static void RotateEmoteSelectionServerRpc(int overrideSeed = 0) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost) { TerminalPatcher.emoteStoreSeed = ((overrideSeed == 0) ? Random.Range(0, 1000000000) : overrideSeed); TerminalPatcher.RotateNewEmoteSelection(); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); ((FastBufferWriter)(ref val)).WriteValue<int>(ref TerminalPatcher.emoteStoreSeed, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("TooManyEmotes-OnRotateEmotesClientRpc", val, (NetworkDelivery)3); } } private static void RotateEmoteSelectionClientRpc(ulong clientId, FastBufferReader reader) { //IL_0036: 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) if (NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsServer && ((FastBufferReader)(ref reader)).TryBeginRead(4)) { ((FastBufferReader)(ref reader)).ReadValue<int>(ref TerminalPatcher.emoteStoreSeed, default(ForPrimitives)); TerminalPatcher.RotateNewEmoteSelection(); } } } } namespace TooManyEmotes.CompatibilityPatcher { [HarmonyPatch] internal class MoreEmotesPatcher { public static bool loadedMoreEmotes; [HarmonyPatch(typeof(PreInitSceneScript), "Awake")] [HarmonyPostfix] public static void ApplyPatch() { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Expected O, but got Unknown if (!Plugin.IsModLoaded("MoreEmotes") || !Chainloader.PluginInfos.TryGetValue("MoreEmotes", out var value)) { return; } Assembly assembly = ((object)value.Instance).GetType().Assembly; if (assembly != null) { Plugin.Log("Applying compatibility patch for More_Emotes"); Type type = assembly.GetType("MoreEmotes.Patch.EmotePatch"); FieldInfo field = type.GetField("local", BindingFlags.Static | BindingFlags.Public); RuntimeAnimatorController val = (RuntimeAnimatorController)field.GetValue(null); if ((Object)(object)val != (Object)null && !(val is AnimatorOverrideController)) { field.SetValue(null, (object?)new AnimatorOverrideController(val)); } FieldInfo field2 = type.GetField("others", BindingFlags.Static | BindingFlags.Public); RuntimeAnimatorController val2 = (RuntimeAnimatorController)field2.GetValue(null); if ((Object)(object)val2 != (Object)null && !(val2 is AnimatorOverrideController)) { field2.SetValue(null, (object?)new AnimatorOverrideController(val2)); } } } } [HarmonyPatch] internal class BetterEmotesPatcher { public static bool loadedBetterEmotes; [HarmonyPatch(typeof(PreInitSceneScript), "Awake")] [HarmonyPostfix] public static void ApplyPatch() { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Expected O, but got Unknown if (!Plugin.IsModLoaded("BetterEmotes") || !Chainloader.PluginInfos.TryGetValue("BetterEmotes", out var value)) { return; } Assembly assembly = ((object)value.Instance).GetType().Assembly; if (assembly != null) { Plugin.Log("Applying compatibility patch for BetterEmotes"); Type type = assembly.GetType("BetterEmote.EmotePatch"); FieldInfo field = type.GetField("local", BindingFlags.Static | BindingFlags.Public); RuntimeAnimatorController val = (RuntimeAnimatorController)field.GetValue(null); if ((Object)(object)val != (Object)null && !(val is AnimatorOverrideController)) { field.SetValue(null, (object?)new AnimatorOverrideController(val)); } FieldInfo field2 = type.GetField("others", BindingFlags.Static | BindingFlags.Public); RuntimeAnimatorController val2 = (RuntimeAnimatorController)field2.GetValue(null); if ((Object)(object)val2 != (Object)null && !(val2 is AnimatorOverrideController)) { field2.SetValue(null, (object?)new AnimatorOverrideController(val2)); } } } } internal class BiggerLobbyPatcher { public static bool loadedBiggerLobby; [HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")] [HarmonyPostfix] public static void ApplyPatch() { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown if (!Plugin.IsModLoaded("BiggerLobby")) { return; } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return; } for (int i = 0; i < instance.allPlayerScripts.Length; i++) { PlayerControllerB obj = instance.allPlayerScripts[i]; object obj2; if (obj == null) { obj2 = null; } else { Animator playerBodyAnimator = obj.playerBodyAnimator; obj2 = ((playerBodyAnimator != null) ? playerBodyAnimator.runtimeAnimatorController : null); } if ((Object)obj2 != (Object)null) { instance.allPlayerScripts[i].playerBodyAnimator.runtimeAnimatorController = (RuntimeAnimatorController)new AnimatorOverrideController(instance.otherClientsAnimatorController); } } loadedBiggerLobby = true; } } [HarmonyPatch] internal class MoreCompanyPatcher { public static bool loadedMoreCompany = false; public static List<GameObject> cosmeticInstances = new List<GameObject>(); [HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageClientRpc")] [HarmonyPostfix] public static void ApplyPatch() { //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) if (!Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany")) { return; } CosmeticApplication val = Object.FindObjectOfType<CosmeticApplication>(); if (CosmeticRegistry.locallySelectedCosmetics.Count <= 0 || val.spawnedCosmetics.Count > 0) { return; } foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics) { val.ApplyCosmetic(locallySelectedCosmetic, true); } foreach (CosmeticInstance spawnedCosmetic in val.spawnedCosmetics) { Transform transform = ((Component)spawnedCosmetic).transform; transform.localScale *= 0.38f; SetAllChildrenLayer(((Component)spawnedCosmetic).transform, 23); } } private static void SetAllChildrenLayer(Transform transform, int layer) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown ((Component)transform).gameObject.layer = layer; foreach (Transform item in transform) { Transform transform2 = item; SetAllChildrenLayer(transform2, layer); } } } [HarmonyPatch] internal class MirrorDecorPatcher { public static bool loadedMirrorDecor; [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPrefix] public static void ApplyPatch() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (Plugin.IsModLoaded("quackandcheese.mirrordecor")) { loadedMirrorDecor = true; ThirdPersonEmoteController.localPlayerBodyLayer = 23; ThirdPersonEmoteController.defaultShadowCastingMode = (ShadowCastingMode)1; Plugin.Log("Applied patch for MirrorDecor"); } } } } namespace TooManyEmotes.Patches { [HarmonyPatch] public static class BoomboxMusicPlayer { public static List<BoomboxItem> allBoomboxes = new List<BoomboxItem>(); [HarmonyPatch(typeof(BoomboxItem), "Start")] [HarmonyPostfix] public static void AddBoomboxToPool(BoomboxItem __instance) { } public static void OnPlayEmoteWithMusic(UnlockableEmote emote, PlayerControllerB playerController) { if (Plugin.musicClips.ContainsKey(emote.emoteName)) {
plugins/TooManySuits.dll
Decompiled a year agousing System; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using MoreSuits; using TMPro; using TooManySuits.Helper; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("TooManySuits")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("TooManySuits")] [assembly: AssemblyTitle("TooManySuits")] [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 TooManySuits { [BepInPlugin("verity.TooManySuits", "Too Many Suits", "1.0.4")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public static ManualLogSource LogSource; public static ConfigEntry<string> NextButton; public static ConfigEntry<string> BackButton; public static ConfigEntry<float> TextScale; private void Awake() { //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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown LogSource = ((BaseUnityPlugin)this).Logger; NextButton = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Next-Page-Keybind", "<Keyboard>/n", "Next page button."); BackButton = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Back-Page-Keybind", "<Keyboard>/b", "Back page button."); TextScale = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Text-Scale", 0.003f, "Size of the text above the suit rack."); GameObject val = new GameObject("TooManySuits"); val.AddComponent<PluginLoader>(); ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)val); } } public class PluginLoader : MonoBehaviour { private class Hooks { public static bool SetUI; public static GameObject SuitPanel; public static void HookStartGame() { Plugin.LogSource.LogInfo((object)"StartOfRound!"); Object.Instantiate<GameObject>(suitSelectBundle.LoadAsset<GameObject>("SuitSelect")); SuitPanel = GameObject.Find("SuitPanel"); SuitPanel.SetActive(false); SetUI = true; } } private readonly Harmony Harmony = new Harmony("TooManySuits"); private InputAction moveRightAction; private InputAction moveLeftAction; private int currentPage; private int suitsPerPage = 13; private int suitsLength; private UnlockableSuit[] allSuits; private static AssetBundle suitSelectBundle; private void Awake() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Expected O, but got Unknown //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Expected O, but got Unknown Plugin.LogSource.LogInfo((object)"TooManySuits Mod Loaded."); moveRightAction = new InputAction((string)null, (InputActionType)0, Plugin.NextButton.Value, (string)null, (string)null, (string)null); moveRightAction.performed += MoveRightAction; moveRightAction.Enable(); moveLeftAction = new InputAction((string)null, (InputActionType)0, Plugin.BackButton.Value, (string)null, (string)null, (string)null); moveLeftAction.performed += MoveLeftAction; moveLeftAction.Enable(); MethodInfo method = typeof(StartOfRound).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic); MethodInfo method2 = typeof(Hooks).GetMethod("HookStartGame"); Harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); MethodInfo method3 = typeof(PlayerControllerB).GetMethod("Start", BindingFlags.Instance | BindingFlags.NonPublic); MethodInfo method4 = typeof(LocalPlayer).GetMethod("PlayerControllerStart"); Harmony.Patch((MethodBase)method3, (HarmonyMethod)null, new HarmonyMethod(method4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); suitSelectBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "suitselect")); if (MoreSuitsMod.MakeSuitsFitOnRack) { suitsPerPage = 20; } } private void Update() { if (!((Object)(object)StartOfRound.Instance == (Object)null)) { allSuits = (from suit in Resources.FindObjectsOfTypeAll<UnlockableSuit>() orderby suit.syncedSuitID.Value select suit).ToArray(); DisplaySuits(); } } private void DisplaySuits() { //IL_023b: 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_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0280: 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_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_013d: 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_0147: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) if (allSuits.Length == 0) { return; } int num = currentPage * suitsPerPage; int num2 = Mathf.Min(num + suitsPerPage, allSuits.Length); int num3 = 0; for (int i = 0; i < allSuits.Length; i++) { UnlockableSuit val = allSuits[i]; AutoParentToShip component = ((Component)val).gameObject.GetComponent<AutoParentToShip>(); if ((Object)(object)component == (Object)null) { continue; } bool flag = i >= num && i < num2; ((Component)val).gameObject.SetActive(flag); if (flag) { component.overrideOffset = true; if (MoreSuitsMod.MakeSuitsFitOnRack && suitsLength > 13) { float num4 = 0.18f; num4 /= (float)Math.Min(suitsLength, 20) / 12f; component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + StartOfRound.Instance.rightmostSuitPosition.forward * (num4 * (float)num3); component.rotationOffset = new Vector3(0f, 90f, 0f); } else { component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + StartOfRound.Instance.rightmostSuitPosition.forward * (0.18f * (float)num3); component.rotationOffset = new Vector3(0f, 90f, 0f); } num3++; } } suitsLength = allSuits.Length; if (!LocalPlayer.isActive()) { return; } if (LocalPlayer.localPlayer.isInHangarShipRoom) { ((TMP_Text)Hooks.SuitPanel.GetComponentInChildren<TextMeshProUGUI>()).text = $"Page {currentPage + 1}/{suitsLength / suitsPerPage + 1}"; Hooks.SuitPanel.SetActive(true); return; } Hooks.SuitPanel.SetActive(false); if (Hooks.SetUI) { Hooks.SetUI = false; Hooks.SuitPanel.GetComponentInParent<Canvas>().renderMode = (RenderMode)2; Hooks.SuitPanel.GetComponentInParent<Canvas>().worldCamera = LocalPlayer.localPlayer.gameplayCamera; Transform transform = Hooks.SuitPanel.transform; Bounds bounds = StartOfRound.Instance.shipBounds.bounds; transform.position = ((Bounds)(ref bounds)).center - new Vector3(2.8992f, 0.7998f, 2f); Hooks.SuitPanel.transform.rotation = Quaternion.Euler(0f, 180f, 0f); Hooks.SuitPanel.transform.localScale = new Vector3(Plugin.TextScale.Value, Plugin.TextScale.Value, Plugin.TextScale.Value); Hooks.SuitPanel.SetActive(true); } } private void MoveRightAction(CallbackContext obj) { currentPage = Mathf.Min(currentPage + 1, Mathf.CeilToInt((float)suitsLength / (float)suitsPerPage) - 1); } private void MoveLeftAction(CallbackContext obj) { currentPage = Mathf.Max(currentPage - 1, 0); } } } namespace TooManySuits.Helper { public class LocalPlayer { public static PlayerControllerB localPlayer; public static bool isActive() { return (Object)(object)localPlayer != (Object)null; } public static void PlayerControllerStart(PlayerControllerB __instance) { if (NetworkManager.Singleton.LocalClientId == __instance.playerClientId) { localPlayer = __instance; } } } }
plugins/WeatherMultipliers.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Collections; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("WeatherMultipliers")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Lethal Company mod adding scrap multipliers to moon weather")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0")] [assembly: AssemblyProduct("WeatherMultipliers")] [assembly: AssemblyTitle("WeatherMultipliers")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace WeatherMultipliers { [Serializable] public class Config : SyncedInstance<Config> { [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__OnRequestSync; public static HandleNamedMessageDelegate <1>__OnReceiveSync; } public Dictionary<LevelWeatherType, float> ValueMultipliers = new Dictionary<LevelWeatherType, float>(); private static readonly Dictionary<LevelWeatherType, float> defaultValueMultipliers = new Dictionary<LevelWeatherType, float> { { (LevelWeatherType)1, 1.05f }, { (LevelWeatherType)2, 1.2f }, { (LevelWeatherType)3, 1.15f }, { (LevelWeatherType)4, 1.25f }, { (LevelWeatherType)5, 1.5f } }; public Config(ConfigFile cfg) { //IL_0035: 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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) InitInstance(this); foreach (KeyValuePair<LevelWeatherType, float> defaultValueMultiplier in defaultValueMultipliers) { Dictionary<LevelWeatherType, float> valueMultipliers = ValueMultipliers; LevelWeatherType key = defaultValueMultiplier.Key; LevelWeatherType key2 = defaultValueMultiplier.Key; valueMultipliers[key] = cfg.Bind<float>("Multipliers", ((object)(LevelWeatherType)(ref key2)).ToString(), Mathf.Clamp(defaultValueMultiplier.Value, 1f, 1000f), $"Scrap value multiplier for {defaultValueMultiplier.Key} weather").Value; } } public static void RequestSync() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (!SyncedInstance<Config>.IsClient) { return; } Plugin.Logger.LogInfo((object)"Attempting to sync config with host"); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(SyncedInstance<Config>.IntSize, (Allocator)2, -1); try { SyncedInstance<Config>.MessageManager.SendNamedMessage("WeatherMultipliers_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3); } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } public static void OnRequestSync(ulong clientId, FastBufferReader _) { //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_0068: Unknown result type (might be due to invalid IL or missing references) if (!SyncedInstance<Config>.IsHost) { return; } Plugin.Logger.LogInfo((object)$"Config sync request received from client: {clientId}"); byte[] array = SyncedInstance<Config>.SerializeToBytes(SyncedInstance<Config>.Instance); int num = array.Length; FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<Config>.IntSize, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0); SyncedInstance<Config>.MessageManager.SendNamedMessage("WeatherMultipliers_OnReceiveConfigSync", clientId, val, (NetworkDelivery)4); } catch (Exception arg) { Plugin.Logger.LogError((object)$"Error occurred syncing config with client: {clientId}\n{arg}"); } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } public static void OnReceiveSync(ulong _, FastBufferReader reader) { //IL_0024: 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) if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<Config>.IntSize)) { Plugin.Logger.LogError((object)"Config sync error: Could not begin reading buffer."); return; } int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); if (!((FastBufferReader)(ref reader)).TryBeginRead(num)) { Plugin.Logger.LogError((object)"Config sync error: Host could not sync."); return; } byte[] data = new byte[num]; ((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0); SyncedInstance<Config>.SyncInstance(data); Plugin.Logger.LogInfo((object)"Successfully synced config with host."); } [HarmonyPostfix] [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] public static void InitializeLocalPlayer() { //IL_0058: 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 //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_002c: Expected O, but got Unknown if (SyncedInstance<Config>.IsHost) { CustomMessagingManager messageManager = SyncedInstance<Config>.MessageManager; object obj = <>O.<0>__OnRequestSync; if (obj == null) { HandleNamedMessageDelegate val = OnRequestSync; <>O.<0>__OnRequestSync = val; obj = (object)val; } messageManager.RegisterNamedMessageHandler("WeatherMultipliers_OnRequestConfigSync", (HandleNamedMessageDelegate)obj); SyncedInstance<Config>.Synced = true; return; } SyncedInstance<Config>.Synced = false; CustomMessagingManager messageManager2 = SyncedInstance<Config>.MessageManager; object obj2 = <>O.<1>__OnReceiveSync; if (obj2 == null) { HandleNamedMessageDelegate val2 = OnReceiveSync; <>O.<1>__OnReceiveSync = val2; obj2 = (object)val2; } messageManager2.RegisterNamedMessageHandler("WeatherMultipliers_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2); RequestSync(); } [HarmonyPostfix] [HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")] public static void PlayerLeave() { SyncedInstance<Config>.RevertSync(); } } [Serializable] public class SyncedInstance<T> { [NonSerialized] protected static int IntSize = 4; internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager; internal static bool IsClient => NetworkManager.Singleton.IsClient; internal static bool IsHost => NetworkManager.Singleton.IsHost; public static T Default { get; private set; } public static T Instance { get; private set; } public static bool Synced { get; internal set; } protected void InitInstance(T instance) { Default = instance; Instance = instance; IntSize = 4; } internal static void SyncInstance(byte[] data) { Instance = DeserializeFromBytes(data); Synced = true; } internal static void RevertSync() { Instance = Default; Synced = false; } public static byte[] SerializeToBytes(T val) { BinaryFormatter binaryFormatter = new BinaryFormatter(); using MemoryStream memoryStream = new MemoryStream(); try { binaryFormatter.Serialize(memoryStream, val); return memoryStream.ToArray(); } catch (Exception arg) { Plugin.Logger.LogError((object)$"Error serializing instance: {arg}"); return null; } } public static T DeserializeFromBytes(byte[] data) { BinaryFormatter binaryFormatter = new BinaryFormatter(); using MemoryStream serializationStream = new MemoryStream(data); try { return (T)binaryFormatter.Deserialize(serializationStream); } catch (Exception arg) { Plugin.Logger.LogError((object)$"Error deserializing instance: {arg}"); return default(T); } } } [BepInPlugin("WeatherMultipliers", "WeatherMultipliers", "1.1.0")] public class Plugin : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("WeatherMultipliers"); public static Config Config { get; internal set; } internal static ManualLogSource Logger { get; private set; } private void Awake() { Config = new Config(((BaseUnityPlugin)this).Config); Logger = ((BaseUnityPlugin)this).Logger; harmony.PatchAll(); harmony.PatchAll(typeof(Config)); Logger.LogInfo((object)"Plugin WeatherMultipliers is loaded!"); } } public static class PluginInfo { public const string PLUGIN_GUID = "WeatherMultipliers"; public const string PLUGIN_NAME = "WeatherMultipliers"; public const string PLUGIN_VERSION = "1.1.0"; } } namespace WeatherMultipliers.patches { [HarmonyPatch(typeof(LungProp), "DisconnectFromMachinery")] public class ApparatusPatch { private static readonly ManualLogSource logger = Logger.CreateLogSource("WeatherMultipliers.ApparatusPatch"); private static void Prefix(LungProp __instance) { //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_002d: 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) LevelWeatherType currentWeather = __instance.roundManager.currentLevel.currentWeather; if (SyncedInstance<Config>.Instance.ValueMultipliers.ContainsKey(currentWeather)) { float num = SyncedInstance<Config>.Instance.ValueMultipliers[currentWeather]; ((GrabbableObject)__instance).scrapValue = (int)(num * (float)((GrabbableObject)__instance).scrapValue); logger.LogInfo((object)$"Adjusting LungProp (Apparatus) value for weather {currentWeather}: {((GrabbableObject)__instance).scrapValue}"); } } } [HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")] public class ScrapGeneration { private static readonly ManualLogSource logger = Logger.CreateLogSource("WeatherMultipliers.ScrapGeneration"); private static void Prefix(RoundManager __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) LevelWeatherType currentWeather = __instance.currentLevel.currentWeather; if (SyncedInstance<Config>.Instance.ValueMultipliers.ContainsKey(currentWeather)) { float num = SyncedInstance<Config>.Instance.ValueMultipliers[__instance.currentLevel.currentWeather]; __instance.scrapValueMultiplier *= num; logger.LogInfo((object)$"Set scrap value multiplier ({num}) for current weather \"{currentWeather}\""); } else { logger.LogInfo((object)$"No weather multiplier found for \"{currentWeather}\""); } } private static void Postfix(RoundManager __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) LevelWeatherType currentWeather = __instance.currentLevel.currentWeather; if (SyncedInstance<Config>.Instance.ValueMultipliers.ContainsKey(currentWeather)) { float num = SyncedInstance<Config>.Instance.ValueMultipliers[__instance.currentLevel.currentWeather]; __instance.scrapValueMultiplier /= num; logger.LogInfo((object)$"Scrap generated, resetting scrap value multiplier to its original value of {__instance.scrapValueMultiplier}"); } } } }
plugins/YippeeMod.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using YippeeMod.Patches; [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("YippeeMod")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("YippeeMod")] [assembly: AssemblyTitle("YippeeMod")] [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 YippeeMod { [BepInPlugin("sunnobunno.YippeeMod", "Yippee tbh mod", "1.2.2")] public class YippeeModBase : BaseUnityPlugin { private const string modGUID = "sunnobunno.YippeeMod"; private const string modName = "Yippee tbh mod"; private const string modVersion = "1.2.2"; private readonly Harmony harmony = new Harmony("sunnobunno.YippeeMod"); private static YippeeModBase? Instance; internal ManualLogSource? mls; internal static AudioClip[]? newSFX; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("sunnobunno.YippeeMod"); mls.LogInfo((object)"sunnobunno.YippeeMod is loading."); string location = ((BaseUnityPlugin)Instance).Info.Location; string text = "YippeeMod.dll"; string text2 = location.TrimEnd(text.ToCharArray()); string text3 = text2 + "yippeesound"; AssetBundle val = AssetBundle.LoadFromFile(text3); if ((Object)(object)val == (Object)null) { mls.LogError((object)"Failed to load audio assets!"); return; } newSFX = val.LoadAssetWithSubAssets<AudioClip>("assets/yippee-tbh.mp3"); harmony.PatchAll(typeof(HoarderBugPatch)); mls.LogInfo((object)"sunnobunno.YippeeMod is loaded. Yippee!!!"); } } } namespace YippeeMod.Patches { [HarmonyPatch(typeof(HoarderBugAI))] internal class HoarderBugPatch { [HarmonyPatch("Start")] [HarmonyPostfix] public static void hoarderBugAudioPatch(ref AudioClip[] ___chitterSFX) { AudioClip[] newSFX = YippeeModBase.newSFX; ___chitterSFX = newSFX; } } }
plugins/YoutubeBoombox.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using LC_API.ClientAPI; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using YoutubeBoombox.Providers; using YoutubeDLSharp; using YoutubeDLSharp.Converters; using YoutubeDLSharp.Helpers; using YoutubeDLSharp.Metadata; using YoutubeDLSharp.Options; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("YoutubeBoombox")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("YoutubeBoombox")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("50a0e49b-1441-46da-9fbf-11bd9a8df0fd")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] internal class <Module> { static <Module>() { } } public sealed class HttpUtility { private sealed class HttpQSCollection : NameValueCollection { public override string ToString() { int count = Count; if (count == 0) { return ""; } StringBuilder stringBuilder = new StringBuilder(); string[] allKeys = AllKeys; for (int i = 0; i < count; i++) { stringBuilder.AppendFormat("{0}={1}&", allKeys[i], UrlEncode(base[allKeys[i]])); } if (stringBuilder.Length > 0) { stringBuilder.Length--; } return stringBuilder.ToString(); } } public class HttpEncoder { private static char[] hexChars; private static object entitiesLock; private static SortedDictionary<string, char> entities; private static Lazy<HttpEncoder> defaultEncoder; private static Lazy<HttpEncoder> currentEncoderLazy; private static HttpEncoder currentEncoder; private static IDictionary<string, char> Entities { get { lock (entitiesLock) { if (entities == null) { InitEntities(); } return entities; } } } public static HttpEncoder Current { get { if (currentEncoder == null) { currentEncoder = currentEncoderLazy.Value; } return currentEncoder; } set { if (value == null) { throw new ArgumentNullException("value"); } currentEncoder = value; } } public static HttpEncoder Default => defaultEncoder.Value; static HttpEncoder() { hexChars = "0123456789abcdef".ToCharArray(); entitiesLock = new object(); defaultEncoder = new Lazy<HttpEncoder>(() => new HttpEncoder()); currentEncoderLazy = new Lazy<HttpEncoder>(GetCustomEncoderFromConfig); } protected internal virtual void HeaderNameValueEncode(string headerName, string headerValue, out string encodedHeaderName, out string encodedHeaderValue) { if (string.IsNullOrEmpty(headerName)) { encodedHeaderName = headerName; } else { encodedHeaderName = EncodeHeaderString(headerName); } if (string.IsNullOrEmpty(headerValue)) { encodedHeaderValue = headerValue; } else { encodedHeaderValue = EncodeHeaderString(headerValue); } } private static void StringBuilderAppend(string s, ref StringBuilder sb) { if (sb == null) { sb = new StringBuilder(s); } else { sb.Append(s); } } private static string EncodeHeaderString(string input) { StringBuilder sb = null; foreach (char c in input) { if ((c < ' ' && c != '\t') || c == '\u007f') { StringBuilderAppend($"%{(int)c:x2}", ref sb); } } if (sb != null) { return sb.ToString(); } return input; } protected internal virtual void HtmlAttributeEncode(string value, TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } if (!string.IsNullOrEmpty(value)) { output.Write(HtmlAttributeEncode(value)); } } protected internal virtual void HtmlDecode(string value, TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } output.Write(HtmlDecode(value)); } protected internal virtual void HtmlEncode(string value, TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } output.Write(HtmlEncode(value)); } protected internal virtual byte[] UrlEncode(byte[] bytes, int offset, int count) { return UrlEncodeToBytes(bytes, offset, count); } private static HttpEncoder GetCustomEncoderFromConfig() { return defaultEncoder.Value; } protected internal virtual string UrlPathEncode(string value) { if (string.IsNullOrEmpty(value)) { return value; } MemoryStream memoryStream = new MemoryStream(); int length = value.Length; for (int i = 0; i < length; i++) { UrlPathEncodeChar(value[i], memoryStream); } return Encoding.ASCII.GetString(memoryStream.ToArray()); } internal static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count) { if (bytes == null) { throw new ArgumentNullException("bytes"); } int num = bytes.Length; if (num == 0) { return new byte[0]; } if (offset < 0 || offset >= num) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || count > num - offset) { throw new ArgumentOutOfRangeException("count"); } MemoryStream memoryStream = new MemoryStream(count); int num2 = offset + count; for (int i = offset; i < num2; i++) { UrlEncodeChar((char)bytes[i], memoryStream, isUnicode: false); } return memoryStream.ToArray(); } internal static string HtmlEncode(string s) { if (s == null) { return null; } if (s.Length == 0) { return string.Empty; } bool flag = false; foreach (char c in s) { if (c == '&' || c == '"' || c == '<' || c == '>' || c > '\u009f' || c == '\'') { flag = true; break; } } if (!flag) { return s; } StringBuilder stringBuilder = new StringBuilder(); int length = s.Length; for (int j = 0; j < length; j++) { char c2 = s[j]; switch (c2) { case '&': stringBuilder.Append("&"); continue; case '>': stringBuilder.Append(">"); continue; case '<': stringBuilder.Append("<"); continue; case '"': stringBuilder.Append("""); continue; case '\'': stringBuilder.Append("'"); continue; case '<': stringBuilder.Append("<"); continue; case '>': stringBuilder.Append(">"); continue; } if (c2 > '\u009f' && c2 < 'Ā') { stringBuilder.Append("&#"); int num = c2; stringBuilder.Append(num.ToString(Helpers.InvariantCulture)); stringBuilder.Append(";"); } else { stringBuilder.Append(c2); } } return stringBuilder.ToString(); } internal static string HtmlAttributeEncode(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } bool flag = false; foreach (char c in s) { if (c == '&' || c == '"' || c == '<' || c == '\'') { flag = true; break; } } if (!flag) { return s; } StringBuilder stringBuilder = new StringBuilder(); int length = s.Length; for (int j = 0; j < length; j++) { char c2 = s[j]; switch (c2) { case '&': stringBuilder.Append("&"); break; case '"': stringBuilder.Append("""); break; case '<': stringBuilder.Append("<"); break; case '\'': stringBuilder.Append("'"); break; default: stringBuilder.Append(c2); break; } } return stringBuilder.ToString(); } internal static string HtmlDecode(string s) { if (s == null) { return null; } if (s.Length == 0) { return string.Empty; } if (s.IndexOf('&') == -1) { return s; } StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); StringBuilder stringBuilder3 = new StringBuilder(); int length = s.Length; int num = 0; int num2 = 0; bool flag = false; bool flag2 = false; for (int i = 0; i < length; i++) { char c = s[i]; if (num == 0) { if (c == '&') { stringBuilder2.Append(c); stringBuilder.Append(c); num = 1; } else { stringBuilder3.Append(c); } continue; } if (c == '&') { num = 1; if (flag2) { stringBuilder2.Append(num2.ToString(Helpers.InvariantCulture)); flag2 = false; } stringBuilder3.Append(stringBuilder2.ToString()); stringBuilder2.Length = 0; stringBuilder2.Append('&'); continue; } switch (num) { case 1: if (c == ';') { num = 0; stringBuilder3.Append(stringBuilder2.ToString()); stringBuilder3.Append(c); stringBuilder2.Length = 0; } else { num2 = 0; flag = false; num = ((c == '#') ? 3 : 2); stringBuilder2.Append(c); stringBuilder.Append(c); } break; case 2: stringBuilder2.Append(c); if (c == ';') { string text = stringBuilder2.ToString(); if (text.Length > 1 && Entities.ContainsKey(text.Substring(1, text.Length - 2))) { text = Entities[text.Substring(1, text.Length - 2)].ToString(); } stringBuilder3.Append(text); num = 0; stringBuilder2.Length = 0; stringBuilder.Length = 0; } break; case 3: if (c == ';') { if (num2 == 0) { stringBuilder3.Append(stringBuilder.ToString() + ";"); } else if (num2 > 65535) { stringBuilder3.Append("&#"); stringBuilder3.Append(num2.ToString(Helpers.InvariantCulture)); stringBuilder3.Append(";"); } else { stringBuilder3.Append((char)num2); } num = 0; stringBuilder2.Length = 0; stringBuilder.Length = 0; flag2 = false; } else if (flag && Uri.IsHexDigit(c)) { num2 = num2 * 16 + Uri.FromHex(c); flag2 = true; stringBuilder.Append(c); } else if (char.IsDigit(c)) { num2 = num2 * 10 + (c - 48); flag2 = true; stringBuilder.Append(c); } else if (num2 == 0 && (c == 'x' || c == 'X')) { flag = true; stringBuilder.Append(c); } else { num = 2; if (flag2) { stringBuilder2.Append(num2.ToString(Helpers.InvariantCulture)); flag2 = false; } stringBuilder2.Append(c); } break; } } if (stringBuilder2.Length > 0) { stringBuilder3.Append(stringBuilder2.ToString()); } else if (flag2) { stringBuilder3.Append(num2.ToString(Helpers.InvariantCulture)); } return stringBuilder3.ToString(); } internal static bool NotEncoded(char c) { if (c != '!' && c != '(' && c != ')' && c != '*' && c != '-' && c != '.') { return c == '_'; } return true; } internal static void UrlEncodeChar(char c, Stream result, bool isUnicode) { if (c > 'ÿ') { result.WriteByte(37); result.WriteByte(117); int num = (int)c >> 12; result.WriteByte((byte)hexChars[num]); num = ((int)c >> 8) & 0xF; result.WriteByte((byte)hexChars[num]); num = ((int)c >> 4) & 0xF; result.WriteByte((byte)hexChars[num]); num = c & 0xF; result.WriteByte((byte)hexChars[num]); } else if (c > ' ' && NotEncoded(c)) { result.WriteByte((byte)c); } else if (c == ' ') { result.WriteByte(43); } else if (c < '0' || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || c > 'z') { if (isUnicode && c > '\u007f') { result.WriteByte(37); result.WriteByte(117); result.WriteByte(48); result.WriteByte(48); } else { result.WriteByte(37); } int num2 = (int)c >> 4; result.WriteByte((byte)hexChars[num2]); num2 = c & 0xF; result.WriteByte((byte)hexChars[num2]); } else { result.WriteByte((byte)c); } } internal static void UrlPathEncodeChar(char c, Stream result) { if (c < '!' || c > '~') { byte[] bytes = Encoding.UTF8.GetBytes(c.ToString()); for (int i = 0; i < bytes.Length; i++) { result.WriteByte(37); int num = bytes[i] >> 4; result.WriteByte((byte)hexChars[num]); num = bytes[i] & 0xF; result.WriteByte((byte)hexChars[num]); } } else if (c == ' ') { result.WriteByte(37); result.WriteByte(50); result.WriteByte(48); } else { result.WriteByte((byte)c); } } private static void InitEntities() { entities = new SortedDictionary<string, char>(StringComparer.Ordinal); entities.Add("nbsp", '\u00a0'); entities.Add("iexcl", '¡'); entities.Add("cent", '¢'); entities.Add("pound", '£'); entities.Add("curren", '¤'); entities.Add("yen", '¥'); entities.Add("brvbar", '¦'); entities.Add("sect", '§'); entities.Add("uml", '\u00a8'); entities.Add("copy", '©'); entities.Add("ordf", 'ª'); entities.Add("laquo", '«'); entities.Add("not", '¬'); entities.Add("shy", '\u00ad'); entities.Add("reg", '®'); entities.Add("macr", '\u00af'); entities.Add("deg", '°'); entities.Add("plusmn", '±'); entities.Add("sup2", '²'); entities.Add("sup3", '³'); entities.Add("acute", '\u00b4'); entities.Add("micro", 'µ'); entities.Add("para", '¶'); entities.Add("middot", '·'); entities.Add("cedil", '\u00b8'); entities.Add("sup1", '¹'); entities.Add("ordm", 'º'); entities.Add("raquo", '»'); entities.Add("frac14", '¼'); entities.Add("frac12", '½'); entities.Add("frac34", '¾'); entities.Add("iquest", '¿'); entities.Add("Agrave", 'À'); entities.Add("Aacute", 'Á'); entities.Add("Acirc", 'Â'); entities.Add("Atilde", 'Ã'); entities.Add("Auml", 'Ä'); entities.Add("Aring", 'Å'); entities.Add("AElig", 'Æ'); entities.Add("Ccedil", 'Ç'); entities.Add("Egrave", 'È'); entities.Add("Eacute", 'É'); entities.Add("Ecirc", 'Ê'); entities.Add("Euml", 'Ë'); entities.Add("Igrave", 'Ì'); entities.Add("Iacute", 'Í'); entities.Add("Icirc", 'Î'); entities.Add("Iuml", 'Ï'); entities.Add("ETH", 'Ð'); entities.Add("Ntilde", 'Ñ'); entities.Add("Ograve", 'Ò'); entities.Add("Oacute", 'Ó'); entities.Add("Ocirc", 'Ô'); entities.Add("Otilde", 'Õ'); entities.Add("Ouml", 'Ö'); entities.Add("times", '×'); entities.Add("Oslash", 'Ø'); entities.Add("Ugrave", 'Ù'); entities.Add("Uacute", 'Ú'); entities.Add("Ucirc", 'Û'); entities.Add("Uuml", 'Ü'); entities.Add("Yacute", 'Ý'); entities.Add("THORN", 'Þ'); entities.Add("szlig", 'ß'); entities.Add("agrave", 'à'); entities.Add("aacute", 'á'); entities.Add("acirc", 'â'); entities.Add("atilde", 'ã'); entities.Add("auml", 'ä'); entities.Add("aring", 'å'); entities.Add("aelig", 'æ'); entities.Add("ccedil", 'ç'); entities.Add("egrave", 'è'); entities.Add("eacute", 'é'); entities.Add("ecirc", 'ê'); entities.Add("euml", 'ë'); entities.Add("igrave", 'ì'); entities.Add("iacute", 'í'); entities.Add("icirc", 'î'); entities.Add("iuml", 'ï'); entities.Add("eth", 'ð'); entities.Add("ntilde", 'ñ'); entities.Add("ograve", 'ò'); entities.Add("oacute", 'ó'); entities.Add("ocirc", 'ô'); entities.Add("otilde", 'õ'); entities.Add("ouml", 'ö'); entities.Add("divide", '÷'); entities.Add("oslash", 'ø'); entities.Add("ugrave", 'ù'); entities.Add("uacute", 'ú'); entities.Add("ucirc", 'û'); entities.Add("uuml", 'ü'); entities.Add("yacute", 'ý'); entities.Add("thorn", 'þ'); entities.Add("yuml", 'ÿ'); entities.Add("fnof", 'ƒ'); entities.Add("Alpha", 'Α'); entities.Add("Beta", 'Β'); entities.Add("Gamma", 'Γ'); entities.Add("Delta", 'Δ'); entities.Add("Epsilon", 'Ε'); entities.Add("Zeta", 'Ζ'); entities.Add("Eta", 'Η'); entities.Add("Theta", 'Θ'); entities.Add("Iota", 'Ι'); entities.Add("Kappa", 'Κ'); entities.Add("Lambda", 'Λ'); entities.Add("Mu", 'Μ'); entities.Add("Nu", 'Ν'); entities.Add("Xi", 'Ξ'); entities.Add("Omicron", 'Ο'); entities.Add("Pi", 'Π'); entities.Add("Rho", 'Ρ'); entities.Add("Sigma", 'Σ'); entities.Add("Tau", 'Τ'); entities.Add("Upsilon", 'Υ'); entities.Add("Phi", 'Φ'); entities.Add("Chi", 'Χ'); entities.Add("Psi", 'Ψ'); entities.Add("Omega", 'Ω'); entities.Add("alpha", 'α'); entities.Add("beta", 'β'); entities.Add("gamma", 'γ'); entities.Add("delta", 'δ'); entities.Add("epsilon", 'ε'); entities.Add("zeta", 'ζ'); entities.Add("eta", 'η'); entities.Add("theta", 'θ'); entities.Add("iota", 'ι'); entities.Add("kappa", 'κ'); entities.Add("lambda", 'λ'); entities.Add("mu", 'μ'); entities.Add("nu", 'ν'); entities.Add("xi", 'ξ'); entities.Add("omicron", 'ο'); entities.Add("pi", 'π'); entities.Add("rho", 'ρ'); entities.Add("sigmaf", 'ς'); entities.Add("sigma", 'σ'); entities.Add("tau", 'τ'); entities.Add("upsilon", 'υ'); entities.Add("phi", 'φ'); entities.Add("chi", 'χ'); entities.Add("psi", 'ψ'); entities.Add("omega", 'ω'); entities.Add("thetasym", 'ϑ'); entities.Add("upsih", 'ϒ'); entities.Add("piv", 'ϖ'); entities.Add("bull", '•'); entities.Add("hellip", '…'); entities.Add("prime", '′'); entities.Add("Prime", '″'); entities.Add("oline", '‾'); entities.Add("frasl", '⁄'); entities.Add("weierp", '℘'); entities.Add("image", 'ℑ'); entities.Add("real", 'ℜ'); entities.Add("trade", '™'); entities.Add("alefsym", 'ℵ'); entities.Add("larr", '←'); entities.Add("uarr", '↑'); entities.Add("rarr", '→'); entities.Add("darr", '↓'); entities.Add("harr", '↔'); entities.Add("crarr", '↵'); entities.Add("lArr", '⇐'); entities.Add("uArr", '⇑'); entities.Add("rArr", '⇒'); entities.Add("dArr", '⇓'); entities.Add("hArr", '⇔'); entities.Add("forall", '∀'); entities.Add("part", '∂'); entities.Add("exist", '∃'); entities.Add("empty", '∅'); entities.Add("nabla", '∇'); entities.Add("isin", '∈'); entities.Add("notin", '∉'); entities.Add("ni", '∋'); entities.Add("prod", '∏'); entities.Add("sum", '∑'); entities.Add("minus", '−'); entities.Add("lowast", '∗'); entities.Add("radic", '√'); entities.Add("prop", '∝'); entities.Add("infin", '∞'); entities.Add("ang", '∠'); entities.Add("and", '∧'); entities.Add("or", '∨'); entities.Add("cap", '∩'); entities.Add("cup", '∪'); entities.Add("int", '∫'); entities.Add("there4", '∴'); entities.Add("sim", '∼'); entities.Add("cong", '≅'); entities.Add("asymp", '≈'); entities.Add("ne", '≠'); entities.Add("equiv", '≡'); entities.Add("le", '≤'); entities.Add("ge", '≥'); entities.Add("sub", '⊂'); entities.Add("sup", '⊃'); entities.Add("nsub", '⊄'); entities.Add("sube", '⊆'); entities.Add("supe", '⊇'); entities.Add("oplus", '⊕'); entities.Add("otimes", '⊗'); entities.Add("perp", '⊥'); entities.Add("sdot", '⋅'); entities.Add("lceil", '⌈'); entities.Add("rceil", '⌉'); entities.Add("lfloor", '⌊'); entities.Add("rfloor", '⌋'); entities.Add("lang", '〈'); entities.Add("rang", '〉'); entities.Add("loz", '◊'); entities.Add("spades", '♠'); entities.Add("clubs", '♣'); entities.Add("hearts", '♥'); entities.Add("diams", '♦'); entities.Add("quot", '"'); entities.Add("amp", '&'); entities.Add("lt", '<'); entities.Add("gt", '>'); entities.Add("OElig", 'Œ'); entities.Add("oelig", 'œ'); entities.Add("Scaron", 'Š'); entities.Add("scaron", 'š'); entities.Add("Yuml", 'Ÿ'); entities.Add("circ", 'ˆ'); entities.Add("tilde", '\u02dc'); entities.Add("ensp", '\u2002'); entities.Add("emsp", '\u2003'); entities.Add("thinsp", '\u2009'); entities.Add("zwnj", '\u200c'); entities.Add("zwj", '\u200d'); entities.Add("lrm", '\u200e'); entities.Add("rlm", '\u200f'); entities.Add("ndash", '–'); entities.Add("mdash", '—'); entities.Add("lsquo", '‘'); entities.Add("rsquo", '’'); entities.Add("sbquo", '‚'); entities.Add("ldquo", '“'); entities.Add("rdquo", '”'); entities.Add("bdquo", '„'); entities.Add("dagger", '†'); entities.Add("Dagger", '‡'); entities.Add("permil", '‰'); entities.Add("lsaquo", '‹'); entities.Add("rsaquo", '›'); entities.Add("euro", '€'); } } private class Helpers { public static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture; } public interface IHtmlString { string ToHtmlString(); } public static void HtmlAttributeEncode(string s, TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } HttpEncoder.Current.HtmlAttributeEncode(s, output); } public static string HtmlAttributeEncode(string s) { if (s == null) { return null; } using StringWriter stringWriter = new StringWriter(); HttpEncoder.Current.HtmlAttributeEncode(s, stringWriter); return stringWriter.ToString(); } public static string UrlDecode(string str) { return UrlDecode(str, Encoding.UTF8); } private static char[] GetChars(MemoryStream b, Encoding e) { return e.GetChars(b.GetBuffer(), 0, (int)b.Length); } private static void WriteCharBytes(IList buf, char ch, Encoding e) { if (ch > 'ÿ') { byte[] bytes = e.GetBytes(new char[1] { ch }); foreach (byte b in bytes) { buf.Add(b); } } else { buf.Add((byte)ch); } } public static string UrlDecode(string s, Encoding e) { if (s == null) { return null; } if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1) { return s; } if (e == null) { e = Encoding.UTF8; } long num = s.Length; List<byte> list = new List<byte>(); for (int i = 0; i < num; i++) { char c = s[i]; if (c == '%' && i + 2 < num && s[i + 1] != '%') { int @char; if (s[i + 1] == 'u' && i + 5 < num) { @char = GetChar(s, i + 2, 4); if (@char != -1) { WriteCharBytes(list, (char)@char, e); i += 5; } else { WriteCharBytes(list, '%', e); } } else if ((@char = GetChar(s, i + 1, 2)) != -1) { WriteCharBytes(list, (char)@char, e); i += 2; } else { WriteCharBytes(list, '%', e); } } else if (c == '+') { WriteCharBytes(list, ' ', e); } else { WriteCharBytes(list, c, e); } } byte[] bytes = list.ToArray(); list = null; return e.GetString(bytes); } public static string UrlDecode(byte[] bytes, Encoding e) { if (bytes == null) { return null; } return UrlDecode(bytes, 0, bytes.Length, e); } private static int GetInt(byte b) { char c = (char)b; if (c >= '0' && c <= '9') { return c - 48; } if (c >= 'a' && c <= 'f') { return c - 97 + 10; } if (c >= 'A' && c <= 'F') { return c - 65 + 10; } return -1; } private static int GetChar(byte[] bytes, int offset, int length) { int num = 0; int num2 = length + offset; for (int i = offset; i < num2; i++) { int @int = GetInt(bytes[i]); if (@int == -1) { return -1; } num = (num << 4) + @int; } return num; } private static int GetChar(string str, int offset, int length) { int num = 0; int num2 = length + offset; for (int i = offset; i < num2; i++) { char c = str[i]; if (c > '\u007f') { return -1; } int @int = GetInt((byte)c); if (@int == -1) { return -1; } num = (num << 4) + @int; } return num; } public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e) { if (bytes == null) { return null; } if (count == 0) { return string.Empty; } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > bytes.Length) { throw new ArgumentOutOfRangeException("count"); } StringBuilder stringBuilder = new StringBuilder(); MemoryStream memoryStream = new MemoryStream(); int num = count + offset; for (int i = offset; i < num; i++) { if (bytes[i] == 37 && i + 2 < count && bytes[i + 1] != 37) { int @char; if (bytes[i + 1] == 117 && i + 5 < num) { if (memoryStream.Length > 0) { stringBuilder.Append(GetChars(memoryStream, e)); memoryStream.SetLength(0L); } @char = GetChar(bytes, i + 2, 4); if (@char != -1) { stringBuilder.Append((char)@char); i += 5; continue; } } else if ((@char = GetChar(bytes, i + 1, 2)) != -1) { memoryStream.WriteByte((byte)@char); i += 2; continue; } } if (memoryStream.Length > 0) { stringBuilder.Append(GetChars(memoryStream, e)); memoryStream.SetLength(0L); } if (bytes[i] == 43) { stringBuilder.Append(' '); } else { stringBuilder.Append((char)bytes[i]); } } if (memoryStream.Length > 0) { stringBuilder.Append(GetChars(memoryStream, e)); } memoryStream = null; return stringBuilder.ToString(); } public static byte[] UrlDecodeToBytes(byte[] bytes) { if (bytes == null) { return null; } return UrlDecodeToBytes(bytes, 0, bytes.Length); } public static byte[] UrlDecodeToBytes(string str) { return UrlDecodeToBytes(str, Encoding.UTF8); } public static byte[] UrlDecodeToBytes(string str, Encoding e) { if (str == null) { return null; } if (e == null) { throw new ArgumentNullException("e"); } return UrlDecodeToBytes(e.GetBytes(str)); } public static byte[] UrlDecodeToBytes(byte[] bytes, int offset, int count) { if (bytes == null) { return null; } if (count == 0) { return new byte[0]; } int num = bytes.Length; if (offset < 0 || offset >= num) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset > num - count) { throw new ArgumentOutOfRangeException("count"); } MemoryStream memoryStream = new MemoryStream(); int num2 = offset + count; for (int i = offset; i < num2; i++) { char c = (char)bytes[i]; switch (c) { case '+': c = ' '; break; case '%': if (i < num2 - 2) { int @char = GetChar(bytes, i + 1, 2); if (@char != -1) { c = (char)@char; i += 2; } } break; } memoryStream.WriteByte((byte)c); } return memoryStream.ToArray(); } public static string UrlEncode(string str) { return UrlEncode(str, Encoding.UTF8); } public static string UrlEncode(string s, Encoding Enc) { if (s == null) { return null; } if (s == string.Empty) { return string.Empty; } bool flag = false; int length = s.Length; for (int i = 0; i < length; i++) { char c = s[i]; if ((c < '0' || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || c > 'z') && !HttpEncoder.NotEncoded(c)) { flag = true; break; } } if (!flag) { return s; } byte[] bytes = new byte[Enc.GetMaxByteCount(s.Length)]; int bytes2 = Enc.GetBytes(s, 0, s.Length, bytes, 0); return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, bytes2)); } public static string UrlEncode(byte[] bytes) { if (bytes == null) { return null; } if (bytes.Length == 0) { return string.Empty; } return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, bytes.Length)); } public static string UrlEncode(byte[] bytes, int offset, int count) { if (bytes == null) { return null; } if (bytes.Length == 0) { return string.Empty; } return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, offset, count)); } public static byte[] UrlEncodeToBytes(string str) { return UrlEncodeToBytes(str, Encoding.UTF8); } public static byte[] UrlEncodeToBytes(string str, Encoding e) { if (str == null) { return null; } if (str.Length == 0) { return new byte[0]; } byte[] bytes = e.GetBytes(str); return UrlEncodeToBytes(bytes, 0, bytes.Length); } public static byte[] UrlEncodeToBytes(byte[] bytes) { if (bytes == null) { return null; } if (bytes.Length == 0) { return new byte[0]; } return UrlEncodeToBytes(bytes, 0, bytes.Length); } public static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count) { if (bytes == null) { return null; } return HttpEncoder.Current.UrlEncode(bytes, offset, count); } public static string UrlEncodeUnicode(string str) { if (str == null) { return null; } return Encoding.ASCII.GetString(UrlEncodeUnicodeToBytes(str)); } public static byte[] UrlEncodeUnicodeToBytes(string str) { if (str == null) { return null; } if (str.Length == 0) { return new byte[0]; } MemoryStream memoryStream = new MemoryStream(str.Length); foreach (char c in str) { HttpEncoder.UrlEncodeChar(c, memoryStream, isUnicode: true); } return memoryStream.ToArray(); } public static string HtmlDecode(string s) { if (s == null) { return null; } using StringWriter stringWriter = new StringWriter(); HttpEncoder.Current.HtmlDecode(s, stringWriter); return stringWriter.ToString(); } public static void HtmlDecode(string s, TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } if (!string.IsNullOrEmpty(s)) { HttpEncoder.Current.HtmlDecode(s, output); } } public static string HtmlEncode(string s) { if (s == null) { return null; } using StringWriter stringWriter = new StringWriter(); HttpEncoder.Current.HtmlEncode(s, stringWriter); return stringWriter.ToString(); } public static void HtmlEncode(string s, TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } if (!string.IsNullOrEmpty(s)) { HttpEncoder.Current.HtmlEncode(s, output); } } public static string HtmlEncode(object value) { if (value == null) { return null; } if (value is IHtmlString htmlString) { return htmlString.ToHtmlString(); } return HtmlEncode(value.ToString()); } public static string JavaScriptStringEncode(string value) { return JavaScriptStringEncode(value, addDoubleQuotes: false); } public static string JavaScriptStringEncode(string value, bool addDoubleQuotes) { if (string.IsNullOrEmpty(value)) { if (!addDoubleQuotes) { return string.Empty; } return "\"\""; } int length = value.Length; bool flag = false; for (int i = 0; i < length; i++) { char c = value[i]; if ((c >= '\0' && c <= '\u001f') || c == '"' || c == '\'' || c == '<' || c == '>' || c == '\\') { flag = true; break; } } if (!flag) { if (!addDoubleQuotes) { return value; } return "\"" + value + "\""; } StringBuilder stringBuilder = new StringBuilder(); if (addDoubleQuotes) { stringBuilder.Append('"'); } for (int j = 0; j < length; j++) { char c = value[j]; if (c < '\0' || c > '\a') { switch (c) { default: if (c != '\'' && c != '<' && c != '>') { switch (c) { case '\b': stringBuilder.Append("\\b"); break; case '\t': stringBuilder.Append("\\t"); break; case '\n': stringBuilder.Append("\\n"); break; case '\f': stringBuilder.Append("\\f"); break; case '\r': stringBuilder.Append("\\r"); break; case '"': stringBuilder.Append("\\\""); break; case '\\': stringBuilder.Append("\\\\"); break; default: stringBuilder.Append(c); break; } continue; } break; case '\v': case '\u000e': case '\u000f': case '\u0010': case '\u0011': case '\u0012': case '\u0013': case '\u0014': case '\u0015': case '\u0016': case '\u0017': case '\u0018': case '\u0019': case '\u001a': case '\u001b': case '\u001c': case '\u001d': case '\u001e': case '\u001f': break; } } stringBuilder.AppendFormat("\\u{0:x4}", (int)c); } if (addDoubleQuotes) { stringBuilder.Append('"'); } return stringBuilder.ToString(); } public static string UrlPathEncode(string s) { return HttpEncoder.Current.UrlPathEncode(s); } public static NameValueCollection ParseQueryString(string query) { return ParseQueryString(query, Encoding.UTF8); } public static NameValueCollection ParseQueryString(string query, Encoding encoding) { if (query == null) { throw new ArgumentNullException("query"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (query.Length == 0 || (query.Length == 1 && query[0] == '?')) { return new HttpQSCollection(); } if (query[0] == '?') { query = query.Substring(1); } NameValueCollection result = new HttpQSCollection(); ParseQueryString(query, encoding, result); return result; } internal static void ParseQueryString(string query, Encoding encoding, NameValueCollection result) { if (query.Length == 0) { return; } string text = HtmlDecode(query); int length = text.Length; int num = 0; bool flag = true; while (num <= length) { int num2 = -1; int num3 = -1; for (int i = num; i < length; i++) { if (num2 == -1 && text[i] == '=') { num2 = i + 1; } else if (text[i] == '&') { num3 = i; break; } } if (flag) { flag = false; if (text[num] == '?') { num++; } } string name; if (num2 == -1) { name = null; num2 = num; } else { name = UrlDecode(text.Substring(num, num2 - num - 1), encoding); } if (num3 < 0) { num = -1; num3 = text.Length; } else { num = num3 + 1; } string value = UrlDecode(text.Substring(num2, num3 - num2), encoding); result.Add(name, value); if (num == -1) { break; } } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } } namespace YoutubeDLSharp { public enum DownloadState { None, PreProcessing, Downloading, PostProcessing, Error, Success } public class DownloadProgress { public DownloadState State { get; } public float Progress { get; } public string TotalDownloadSize { get; } public string DownloadSpeed { get; } public string ETA { get; } public int VideoIndex { get; } public string Data { get; } public DownloadProgress(DownloadState status, float progress = 0f, string totalDownloadSize = null, string downloadSpeed = null, string eta = null, int index = 1, string data = null) { State = status; Progress = progress; TotalDownloadSize = totalDownloadSize; DownloadSpeed = downloadSpeed; ETA = eta; VideoIndex = index; Data = data; } } public class RunResult<T> { public bool Success { get; } public string[] ErrorOutput { get; } public T Data { get; } public RunResult(bool success, string[] error, T result) { Success = success; ErrorOutput = error; Data = result; } } public static class Utils { internal class FFmpegApi { public class Root { [JsonProperty("version")] public string Version { get; set; } [JsonProperty("permalink")] public string Permalink { get; set; } [JsonProperty("bin")] public Bin Bin { get; set; } } public class Bin { [JsonProperty("windows-64")] public OsBinVersion Windows64 { get; set; } [JsonProperty("linux-64")] public OsBinVersion Linux64 { get; set; } [JsonProperty("osx-64")] public OsBinVersion Osx64 { get; set; } } public class OsBinVersion { [JsonProperty("ffmpeg")] public string Ffmpeg { get; set; } [JsonProperty("ffprobe")] public string Ffprobe { get; set; } } public enum BinaryType { [EnumMember(Value = "ffmpeg")] FFmpeg, [EnumMember(Value = "ffprobe")] FFprobe } } private static readonly HttpClient _client = new HttpClient(); private static readonly Regex rgxTimestamp = new Regex("[0-9]+(?::[0-9]+)+", RegexOptions.Compiled); private static readonly Dictionary<char, string> accentChars = "ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ".Zip(new string[68] { "A", "A", "A", "A", "A", "A", "AE", "C", "E", "E", "E", "E", "I", "I", "I", "I", "D", "N", "O", "O", "O", "O", "O", "O", "O", "OE", "U", "U", "U", "U", "U", "Y", "P", "ss", "a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i", "o", "n", "o", "o", "o", "o", "o", "o", "o", "oe", "u", "u", "u", "u", "u", "y", "p", "y" }, (char c, string s) => new { Key = c, Val = s }).ToDictionary(o => o.Key, o => o.Val); public static string YtDlpBinaryName => GetYtDlpBinaryName(); public static string FfmpegBinaryName => GetFfmpegBinaryName(); public static string FfprobeBinaryName => GetFfprobeBinaryName(); public static string Sanitize(string s, bool restricted = false) { rgxTimestamp.Replace(s, (Match m) => m.Groups[0].Value.Replace(':', '_')); string text = string.Join("", s.Select((char c) => sanitizeChar(c, restricted))); text = text.Replace("__", "_").Trim(new char[1] { '_' }); if (restricted && text.StartsWith("-_")) { text = text.Substring(2); } if (text.StartsWith("-")) { text = "_" + text.Substring(1); } text = text.TrimStart(new char[1] { '.' }); if (string.IsNullOrWhiteSpace(text)) { text = "_"; } return text; } private static string sanitizeChar(char c, bool restricted) { if (restricted && accentChars.ContainsKey(c)) { return accentChars[c]; } if (c != '?' && c >= ' ') { switch (c) { case '\u007f': break; case '"': if (!restricted) { return "'"; } return ""; case ':': if (!restricted) { return " -"; } return "_-"; default: if (Enumerable.Contains("\\/|*<>", c)) { return "_"; } if (restricted && Enumerable.Contains("!&'()[]{}$;`^,# ", c)) { return "_"; } if (restricted && c > '\u007f') { return "_"; } return c.ToString(); } } return ""; } public static string GetFullPath(string fileName) { if (File.Exists(fileName)) { return Path.GetFullPath(fileName); } string environmentVariable = Environment.GetEnvironmentVariable("PATH"); string[] array = environmentVariable.Split(new char[1] { Path.PathSeparator }); foreach (string path in array) { string text = Path.Combine(path, fileName); if (File.Exists(text)) { return text; } } return null; } public static async Task DownloadBinaries(bool skipExisting = true, string directoryPath = "") { if (skipExisting) { if (!File.Exists(Path.Combine(directoryPath, GetYtDlpBinaryName()))) { await DownloadYtDlp(directoryPath); } if (!File.Exists(Path.Combine(directoryPath, GetFfmpegBinaryName()))) { await DownloadFFmpeg(directoryPath); } if (!File.Exists(Path.Combine(directoryPath, GetFfprobeBinaryName()))) { await DownloadFFprobe(directoryPath); } } else { await DownloadYtDlp(directoryPath); await DownloadFFmpeg(directoryPath); await DownloadFFprobe(directoryPath); } } private static string GetYtDlpDownloadUrl() { return OSHelper.GetOSVersion() switch { OSVersion.Windows => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe", OSVersion.OSX => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos", OSVersion.Linux => "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp", _ => throw new Exception("Your OS isn't supported"), }; } private static string GetYtDlpBinaryName() { string ytDlpDownloadUrl = GetYtDlpDownloadUrl(); return Path.GetFileName(ytDlpDownloadUrl); } private static string GetFfmpegBinaryName() { switch (OSHelper.GetOSVersion()) { case OSVersion.Windows: return "ffmpeg.exe"; case OSVersion.OSX: case OSVersion.Linux: return "ffmpeg"; default: throw new Exception("Your OS isn't supported"); } } private static string GetFfprobeBinaryName() { switch (OSHelper.GetOSVersion()) { case OSVersion.Windows: return "ffprobe.exe"; case OSVersion.OSX: case OSVersion.Linux: return "ffprobe"; default: throw new Exception("Your OS isn't supported"); } } public static async Task DownloadYtDlp(string directoryPath = "") { string ytDlpDownloadUrl = GetYtDlpDownloadUrl(); if (string.IsNullOrEmpty(directoryPath)) { directoryPath = Directory.GetCurrentDirectory(); } string downloadLocation = Path.Combine(directoryPath, Path.GetFileName(ytDlpDownloadUrl)); File.WriteAllBytes(downloadLocation, await DownloadFileBytesAsync(ytDlpDownloadUrl)); } public static async Task DownloadFFmpeg(string directoryPath = "") { await FFDownloader(directoryPath); } public static async Task DownloadFFprobe(string directoryPath = "") { await FFDownloader(directoryPath, FFmpegApi.BinaryType.FFprobe); } private static async Task FFDownloader(string directoryPath = "", FFmpegApi.BinaryType binary = FFmpegApi.BinaryType.FFmpeg) { if (string.IsNullOrEmpty(directoryPath)) { directoryPath = Directory.GetCurrentDirectory(); } FFmpegApi.Root root = JsonConvert.DeserializeObject<FFmpegApi.Root>(await (await _client.GetAsync("https://ffbinaries.com/api/v1/version/latest")).Content.ReadAsStringAsync()); FFmpegApi.OsBinVersion osBinVersion = OSHelper.GetOSVersion() switch { OSVersion.Windows => root?.Bin.Windows64, OSVersion.OSX => root?.Bin.Osx64, OSVersion.Linux => root?.Bin.Linux64, _ => throw new NotImplementedException("Your OS isn't supported"), }; string uri = ((binary == FFmpegApi.BinaryType.FFmpeg) ? osBinVersion.Ffmpeg : osBinVersion.Ffprobe); using MemoryStream stream = new MemoryStream(await DownloadFileBytesAsync(uri)); using ZipArchive zipArchive = new ZipArchive(stream, ZipArchiveMode.Read); if (zipArchive.Entries.Count > 0) { zipArchive.Entries[0].ExtractToFile(Path.Combine(directoryPath, zipArchive.Entries[0].FullName), overwrite: true); } } private static async Task<byte[]> DownloadFileBytesAsync(string uri) { if (!Uri.TryCreate(uri, UriKind.Absolute, out Uri _)) { throw new InvalidOperationException("URI is invalid."); } return await _client.GetByteArrayAsync(uri); } } public class YoutubeDL { private static readonly Regex rgxFile = new Regex("^outfile:\\s\\\"?(.*)\\\"?", RegexOptions.Compiled); private static Regex rgxFilePostProc = new Regex("\\[download\\] Destination: [a-zA-Z]:\\\\\\S+\\.\\S{3,}", RegexOptions.Compiled); protected ProcessRunner runner; public string YoutubeDLPath { get; set; } = Utils.YtDlpBinaryName; public string FFmpegPath { get; set; } = Utils.FfmpegBinaryName; public string OutputFolder { get; set; } = Environment.CurrentDirectory; public string OutputFileTemplate { get; set; } = "%(title)s [%(id)s].%(ext)s"; public bool RestrictFilenames { get; set; } public bool OverwriteFiles { get; set; } = true; public bool IgnoreDownloadErrors { get; set; } = true; public string Version => FileVersionInfo.GetVersionInfo(Utils.GetFullPath(YoutubeDLPath)).FileVersion; public YoutubeDL(byte maxNumberOfProcesses = 4) { runner = new ProcessRunner(maxNumberOfProcesses); } public async Task SetMaxNumberOfProcesses(byte count) { await runner.SetTotalCount(count); } public async Task<RunResult<string[]>> RunWithOptions(string[] urls, OptionSet options, CancellationToken ct) { List<string> output = new List<string>(); YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { output.Add(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, urls, options, ct); return new RunResult<string[]>(num == 0, error, output.ToArray()); } public async Task<RunResult<string>> RunWithOptions(string url, OptionSet options, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, bool showArgs = true) { string outFile = string.Empty; YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath); if (showArgs) { output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, options) + "\n"); } else { output?.Report("Starting Download: " + url); } youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFilePostProc.Match(e.Data); if (match.Success) { outFile = match.Groups[0].ToString().Replace("[download] Destination:", "").Replace(" ", ""); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outFile)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, options, ct, progress); return new RunResult<string>(num == 0, error, outFile); } public async Task<string> RunUpdate() { string output = string.Empty; YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { output = e.Data; }; await youtubeDLProcess.RunAsync(null, new OptionSet { Update = true }); return output; } public async Task<RunResult<VideoData>> RunVideoDataFetch(string url, CancellationToken ct = default(CancellationToken), bool flat = true, bool fetchComments = false, OptionSet overrideOptions = null) { OptionSet optionSet = GetDownloadOptions(); optionSet.DumpSingleJson = true; optionSet.FlatPlaylist = flat; optionSet.WriteComments = fetchComments; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } VideoData videoData = null; YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { videoData = JsonConvert.DeserializeObject<VideoData>(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct); return new RunResult<VideoData>(num == 0, error, videoData); } public async Task<RunResult<string>> RunVideoDownload(string url, string format = "bestvideo+bestaudio/best", DownloadMergeFormat mergeFormat = DownloadMergeFormat.Unspecified, VideoRecodeFormat recodeFormat = VideoRecodeFormat.None, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null) { OptionSet optionSet = GetDownloadOptions(); optionSet.Format = format; optionSet.MergeOutputFormat = mergeFormat; optionSet.RecodeVideo = recodeFormat; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } string outputFile = string.Empty; YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath); output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n"); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFile.Match(e.Data); if (match.Success) { outputFile = match.Groups[1].ToString().Trim(new char[1] { '"' }); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outputFile)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress); return new RunResult<string>(num == 0, error, outputFile); } public async Task<RunResult<string[]>> RunVideoPlaylistDownload(string url, int? start = 1, int? end = null, int[] items = null, string format = "bestvideo+bestaudio/best", VideoRecodeFormat recodeFormat = VideoRecodeFormat.None, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null) { OptionSet optionSet = GetDownloadOptions(); optionSet.NoPlaylist = false; optionSet.PlaylistStart = start; optionSet.PlaylistEnd = end; if (items != null) { optionSet.PlaylistItems = string.Join(",", items); } optionSet.Format = format; optionSet.RecodeVideo = recodeFormat; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } List<string> outputFiles = new List<string>(); YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath); output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n"); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFile.Match(e.Data); if (match.Success) { string text = match.Groups[1].ToString().Trim(new char[1] { '"' }); outputFiles.Add(text); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, text)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress); return new RunResult<string[]>(num == 0, error, outputFiles.ToArray()); } public async Task<RunResult<string>> RunAudioDownload(string url, AudioConversionFormat format = AudioConversionFormat.Best, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null) { OptionSet optionSet = GetDownloadOptions(); optionSet.Format = "bestaudio/best"; optionSet.ExtractAudio = true; optionSet.AudioFormat = format; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } string outputFile = string.Empty; new List<string>(); YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath); output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n"); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFile.Match(e.Data); if (match.Success) { outputFile = match.Groups[1].ToString().Trim(new char[1] { '"' }); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, outputFile)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress); return new RunResult<string>(num == 0, error, outputFile); } public async Task<RunResult<string[]>> RunAudioPlaylistDownload(string url, int? start = 1, int? end = null, int[] items = null, AudioConversionFormat format = AudioConversionFormat.Best, CancellationToken ct = default(CancellationToken), IProgress<DownloadProgress> progress = null, IProgress<string> output = null, OptionSet overrideOptions = null) { List<string> outputFiles = new List<string>(); OptionSet optionSet = GetDownloadOptions(); optionSet.NoPlaylist = false; optionSet.PlaylistStart = start; optionSet.PlaylistEnd = end; if (items != null) { optionSet.PlaylistItems = string.Join(",", items); } optionSet.Format = "bestaudio/best"; optionSet.ExtractAudio = true; optionSet.AudioFormat = format; if (overrideOptions != null) { optionSet = optionSet.OverrideOptions(overrideOptions); } YoutubeDLProcess youtubeDLProcess = new YoutubeDLProcess(YoutubeDLPath); output?.Report("Arguments: " + youtubeDLProcess.ConvertToArgs(new string[1] { url }, optionSet) + "\n"); youtubeDLProcess.OutputReceived += delegate(object o, DataReceivedEventArgs e) { Match match = rgxFile.Match(e.Data); if (match.Success) { string text = match.Groups[1].ToString().Trim(new char[1] { '"' }); outputFiles.Add(text); progress?.Report(new DownloadProgress(DownloadState.Success, 0f, null, null, null, 1, text)); } output?.Report(e.Data); }; var (num, error) = await runner.RunThrottled(youtubeDLProcess, new string[1] { url }, optionSet, ct, progress); return new RunResult<string[]>(num == 0, error, outputFiles.ToArray()); } protected virtual OptionSet GetDownloadOptions() { return new OptionSet { IgnoreErrors = IgnoreDownloadErrors, IgnoreConfig = true, NoPlaylist = true, Downloader = "m3u8:native", DownloaderArgs = "ffmpeg:-nostats -loglevel 0", Output = Path.Combine(OutputFolder, OutputFileTemplate), RestrictFilenames = RestrictFilenames, ForceOverwrites = OverwriteFiles, NoOverwrites = !OverwriteFiles, NoPart = true, FfmpegLocation = Utils.GetFullPath(FFmpegPath), Exec = "echo outfile: {}" }; } } public class YoutubeDLProcess { private static readonly Regex rgxPlaylist = new Regex("Downloading video (\\d+) of (\\d+)", RegexOptions.Compiled); private static readonly Regex rgxProgress = new Regex("\\[download\\]\\s+(?:(?<percent>[\\d\\.]+)%(?:\\s+of\\s+\\~?\\s*(?<total>[\\d\\.\\w]+))?\\s+at\\s+(?:(?<speed>[\\d\\.\\w]+\\/s)|[\\w\\s]+)\\s+ETA\\s(?<eta>[\\d\\:]+))?", RegexOptions.Compiled); private static readonly Regex rgxPost = new Regex("\\[(\\w+)\\]\\s+", RegexOptions.Compiled); public string PythonPath { get; set; } public string ExecutablePath { get; set; } public bool UseWindowsEncodingWorkaround { get; set; } = true; public event EventHandler<DataReceivedEventArgs> OutputReceived; public event EventHandler<DataReceivedEventArgs> ErrorReceived; public YoutubeDLProcess(string executablePath = "yt-dlp.exe") { ExecutablePath = executablePath; } internal string ConvertToArgs(string[] urls, OptionSet options) { return ((urls != null) ? string.Join(" ", urls.Select((string s) => "\"" + s + "\"")) : string.Empty) + options.ToString(); } public async Task<int> RunAsync(string[] urls, OptionSet options) { return await RunAsync(urls, options, CancellationToken.None); } public async Task<int> RunAsync(string[] urls, OptionSet options, CancellationToken ct, IProgress<DownloadProgress> progress = null) { TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(); Process process = new Process(); ProcessStartInfo processStartInfo = new ProcessStartInfo { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8 }; if (OSHelper.IsWindows && UseWindowsEncodingWorkaround) { processStartInfo.FileName = "cmd.exe"; string text = (string.IsNullOrEmpty(PythonPath) ? ("\"" + ExecutablePath + "\" " + ConvertToArgs(urls, options)) : (PythonPath + " \"" + ExecutablePath + "\" " + ConvertToArgs(urls, options))); processStartInfo.Arguments = "/C chcp 65001 >nul 2>&1 && " + text; } else if (!string.IsNullOrEmpty(PythonPath)) { processStartInfo.FileName = PythonPath; processStartInfo.Arguments = "\"" + ExecutablePath + "\" " + ConvertToArgs(urls, options); } else { processStartInfo.FileName = ExecutablePath; processStartInfo.Arguments = ConvertToArgs(urls, options); } process.EnableRaisingEvents = true; process.StartInfo = processStartInfo; TaskCompletionSource<bool> tcsOut = new TaskCompletionSource<bool>(); bool isDownloading = false; process.OutputDataReceived += delegate(object o, DataReceivedEventArgs e) { if (e.Data == null) { tcsOut.SetResult(result: true); } else { Match match; if ((match = rgxProgress.Match(e.Data)).Success) { if (match.Groups.Count > 1 && match.Groups[1].Length > 0) { float progress2 = float.Parse(match.Groups[1].ToString(), CultureInfo.InvariantCulture) / 100f; Group group = match.Groups["total"]; string totalDownloadSize = (group.Success ? group.Value : null); Group group2 = match.Groups["speed"]; string downloadSpeed = (group2.Success ? group2.Value : null); Group group3 = match.Groups["eta"]; string eta = (group3.Success ? group3.Value : null); progress?.Report(new DownloadProgress(DownloadState.Downloading, progress2, totalDownloadSize, downloadSpeed, eta)); } else { progress?.Report(new DownloadProgress(DownloadState.Downloading)); } isDownloading = true; } else if ((match = rgxPlaylist.Match(e.Data)).Success) { int index = int.Parse(match.Groups[1].Value); progress?.Report(new DownloadProgress(DownloadState.PreProcessing, 0f, null, null, null, index)); isDownloading = false; } else if (isDownloading && (match = rgxPost.Match(e.Data)).Success) { progress?.Report(new DownloadProgress(DownloadState.PostProcessing, 1f)); isDownloading = false; } this.OutputReceived?.Invoke(this, e); } }; TaskCompletionSource<bool> tcsError = new TaskCompletionSource<bool>(); process.ErrorDataReceived += delegate(object o, DataReceivedEventArgs e) { if (e.Data == null) { tcsError.SetResult(result: true); } else { progress?.Report(new DownloadProgress(DownloadState.Error, 0f, null, null, null, 1, e.Data)); this.ErrorReceived?.Invoke(this, e); } }; process.Exited += async delegate { await tcsOut.Task; await tcsError.Task; tcs.TrySetResult(process.ExitCode); process.Dispose(); }; ct.Register(delegate { if (!tcs.Task.IsCompleted) { tcs.TrySetCanceled(); } try { if (!process.HasExited) { process.KillTree(); } } catch { } }); if (!(await Task.Run(() => process.Start()))) { tcs.TrySetException(new InvalidOperationException("Failed to start yt-dlp process.")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); progress?.Report(new DownloadProgress(DownloadState.PreProcessing)); return await tcs.Task; } } } namespace YoutubeDLSharp.Options { public enum DownloadMergeFormat { Unspecified, Mp4, Mkv, Ogg, Webm, Flv } public enum AudioConversionFormat { Best, Aac, Flac, Mp3, M4a, Opus, Vorbis, Wav } public enum VideoRecodeFormat { None, Mp4, Mkv, Ogg, Webm, Flv, Avi } public interface IOption { string DefaultOptionString { get; } string[] OptionStrings { get; } bool IsSet { get; } bool IsCustom { get; } void SetFromString(string s); IEnumerable<string> ToStringCollection(); } public class MultiOption<T> : IOption { private MultiValue<T> value; public string DefaultOptionString => OptionStrings.Last(); public string[] OptionStrings { get; } public bool IsSet { get; private set; } public bool IsCustom { get; } public MultiValue<T> Value { get { return value; } set { IsSet = !object.Equals(value, default(T)); this.value = value; } } public MultiOption(params string[] optionStrings) { OptionStrings = optionStrings; IsSet = false; } public MultiOption(bool isCustom, params string[] optionStrings) { OptionStrings = optionStrings; IsSet = false; IsCustom = isCustom; } public void SetFromString(string s) { string[] array = s.Split(new char[1] { ' ' }); string stringValue = s.Substring(array[0].Length).Trim().Trim(new char[1] { '"' }); if (!OptionStrings.Contains(array[0])) { throw new ArgumentException("Given string does not match required format."); } T val = Utils.OptionValueFromString<T>(stringValue); if (!IsSet) { Value = val; } else { Value.Values.Add(val); } } public override string ToString() { return string.Join(" ", ToStringCollection()); } public IEnumerable<string> ToStringCollection() { if (!IsSet) { return new string[1] { "" }; } List<string> list = new List<string>(); foreach (T value in Value.Values) { list.Add(DefaultOptionString + Utils.OptionValueToString(value)); } return list; } } public class MultiValue<T> { private readonly List<T> values; public List<T> Values => values; public MultiValue(params T[] values) { this.values = values.ToList(); } public static implicit operator MultiValue<T>(T value) { return new MultiValue<T>(value); } public static implicit operator MultiValue<T>(T[] values) { return new MultiValue<T>(values); } public static explicit operator T(MultiValue<T> value) { if (value.Values.Count == 1) { return value.Values[0]; } throw new InvalidCastException($"Cannot cast sequence of values to {typeof(T)}."); } public static explicit operator T[](MultiValue<T> value) { return value.Values.ToArray(); } } public class Option<T> : IOption { private T value; public string DefaultOptionString => OptionStrings.Last(); public string[] OptionStrings { get; } public bool IsSet { get; private set; } public T Value { get { return value; } set { IsSet = !object.Equals(value, default(T)); this.value = value; } } public bool IsCustom { get; } public Option(params string[] optionStrings) { OptionStrings = optionStrings; IsSet = false; } public Option(bool isCustom, params string[] optionStrings) { OptionStrings = optionStrings; IsSet = false; IsCustom = isCustom; } public void SetFromString(string s) { string[] array = s.Split(new char[1] { ' ' }); string stringValue = s.Substring(array[0].Length).Trim().Trim(new char[1] { '"' }); if (!OptionStrings.Contains(array[0])) { throw new ArgumentException("Given string does not match required format."); } Value = Utils.OptionValueFromString<T>(stringValue); } public override string ToString() { if (!IsSet) { return string.Empty; } string text = Utils.OptionValueToString(Value); return DefaultOptionString + text; } public IEnumerable<string> ToStringCollection() { return new string[1] { ToString() }; } } internal class OptionComparer : IEqualityComparer<IOption> { public bool Equals(IOption x, IOption y) { if (x != null) { if (y != null) { return x.ToString().Equals(y.ToString()); } return false; } return y == null; } public int GetHashCode(IOption obj) { return obj.ToString().GetHashCode(); } } public class OptionSet : ICloneable { private Option<string> username = new Option<string>("-u", "--username"); private Option<string> password = new Option<string>("-p", "--password"); private Option<string> twoFactor = new Option<string>("-2", "--twofactor"); private Option<bool> netrc = new Option<bool>("-n", "--netrc"); private Option<string> netrcLocation = new Option<string>("--netrc-location"); private Option<string> videoPassword = new Option<string>("--video-password"); private Option<string> apMso = new Option<string>("--ap-mso"); private Option<string> apUsername = new Option<string>("--ap-username"); private Option<string> apPassword = new Option<string>("--ap-password"); private Option<bool> apListMso = new Option<bool>("--ap-list-mso"); private Option<string> clientCertificate = new Option<string>("--client-certificate"); private Option<string> clientCertificateKey = new Option<string>("--client-certificate-key"); private Option<string> clientCertificatePassword = new Option<string>("--client-certificate-password"); private static readonly OptionComparer Comparer = new OptionComparer(); public static readonly OptionSet Default = new OptionSet(); private Option<bool> getDescription = new Option<bool>("--get-description"); private Option<bool> getDuration = new Option<bool>("--get-duration"); private Option<bool> getFilename = new Option<bool>("--get-filename"); private Option<bool> getFormat = new Option<bool>("--get-format"); private Option<bool> getId = new Option<bool>("--get-id"); private Option<bool> getThumbnail = new Option<bool>("--get-thumbnail"); private Option<bool> getTitle = new Option<bool>("-e", "--get-title"); private Option<bool> getUrl = new Option<bool>("-g", "--get-url"); private Option<string> matchTitle = new Option<string>("--match-title"); private Option<string> rejectTitle = new Option<string>("--reject-title"); private Option<long?> minViews = new Option<long?>("--min-views"); private Option<long?> maxViews = new Option<long?>("--max-views"); private Option<string> userAgent = new Option<string>("--user-agent"); private Option<string> referer = new Option<string>("--referer"); private Option<int?> playlistStart = new Option<int?>("--playlist-start"); private Option<int?> playlistEnd = new Option<int?>("--playlist-end"); private Option<bool> playlistReverse = new Option<bool>("--playlist-reverse"); private Option<bool> forceGenericExtractor = new Option<bool>("--force-generic-extractor"); private Option<string> execBeforeDownload = new Option<string>("--exec-before-download"); private Option<bool> noExecBeforeDownload = new Option<bool>("--no-exec-before-download"); private Option<bool> allFormats = new Option<bool>("--all-formats"); private Option<bool> allSubs = new Option<bool>("--all-subs"); private Option<bool> printJson = new Option<bool>("--print-json"); private Option<string> autonumberSize = new Option<string>("--autonumber-size"); private Option<int?> autonumberStart = new Option<int?>("--autonumber-start"); private Option<bool> id = new Option<bool>("--id"); private Option<string> metadataFromTitle = new Option<string>("--metadata-from-title"); private Option<bool> hlsPreferNative = new Option<bool>("--hls-prefer-native"); private Option<bool> hlsPreferFfmpeg = new Option<bool>("--hls-prefer-ffmpeg"); private Option<bool> listFormatsOld = new Option<bool>("--list-formats-old"); private Option<bool> listFormatsAsTable = new Option<bool>("--list-formats-as-table"); private Option<bool> youtubeSkipDashManifest = new Option<bool>("--youtube-skip-dash-manifest"); private Option<bool> youtubeSkipHlsManifest = new Option<bool>("--youtube-skip-hls-manifest"); private Option<int?> concurrentFragments = new Option<int?>("-N", "--concurrent-fragments"); private Option<long?> limitRate = new Option<long?>("-r", "--limit-rate"); private Option<long?> throttledRate = new Option<long?>("--throttled-rate"); private Option<int?> retries = new Option<int?>("-R", "--retries"); private Option<int?> fileAccessRetries = new Option<int?>("--file-access-retries"); private Option<int?> fragmentRetries = new Option<int?>("--fragment-retries"); private MultiOption<string> retrySleep = new MultiOption<string>("--retry-sleep"); private Option<bool> skipUnavailableFragments = new Option<bool>("--skip-unavailable-fragments"); private Option<bool> abortOnUnavailableFragment = new Option<bool>("--abort-on-unavailable-fragment"); private Option<bool> keepFragments = new Option<bool>("--keep-fragments"); private Option<bool> noKeepFragments = new Option<bool>("--no-keep-fragments"); private Option<long?> bufferSize = new Option<long?>("--buffer-size"); private Option<bool> resizeBuffer = new Option<bool>("--resize-buffer"); private Option<bool> noResizeBuffer = new Option<bool>("--no-resize-buffer"); private Option<long?> httpChunkSize = new Option<long?>("--http-chunk-size"); private Option<bool> playlistRandom = new Option<bool>("--playlist-random"); private Option<bool> lazyPlaylist = new Option<bool>("--lazy-playlist"); private Option<bool> noLazyPlaylist = new Option<bool>("--no-lazy-playlist"); private Option<bool> xattrSetFilesize = new Option<bool>("--xattr-set-filesize"); private Option<bool> hlsUseMpegts = new Option<bool>("--hls-use-mpegts"); private Option<bool> noHlsUseMpegts = new Option<bool>("--no-hls-use-mpegts"); private MultiOption<string> downloadSections = new MultiOption<string>("--download-sections"); private MultiOption<string> downloader = new MultiOption<string>("--downloader", "--external-downloader"); private MultiOption<string> downloaderArgs = new MultiOption<string>("--downloader-args", "--external-downloader-args"); private Option<int?> extractorRetries = new Option<int?>("--extractor-retries"); private Option<bool> allowDynamicMpd = new Option<bool>("--allow-dynamic-mpd"); private Option<bool> ignoreDynamicMpd = new Option<bool>("--ignore-dynamic-mpd"); private Option<bool> hlsSplitDiscontinuity = new Option<bool>("--hls-split-discontinuity"); private Option<bool> noHlsSplitDiscontinuity = new Option<bool>("--no-hls-split-discontinuity"); private MultiOption<string> extractorArgs = new MultiOption<string>("--extractor-args"); private Option<string> batchFile = new Option<string>("-a", "--batch-file"); private Option<bool> noBatchFile = new Option<bool>("--no-batch-file"); private Option<string> paths = new Option<string>("-P", "--paths"); private Option<string> output = new Option<string>("-o", "--output"); private Option<string> outputNaPlaceholder = new Option<string>("--output-na-placeholder"); private Option<bool> restrictFilenames = new Option<bool>("--restrict-filenames"); private Option<bool> noRestrictFilenames = new Option<bool>("--no-restrict-filenames"); private Option<bool> windowsFilenames = new Option<bool>("--windows-filenames"); private Option<bool> noWindowsFilenames = new Option<bool>("--no-windows-filenames"); private Option<int?> trimFilenames = new Option<int?>("--trim-filenames"); private Option<bool> noOverwrites = new Option<bool>("-w", "--no-overwrites"); private Option<bool> forceOverwrites = new Option<bool>("--force-overwrites"); private Option<bool> noForceOverwrites = new Option<bool>("--no-force-overwrites"); private Option<bool> doContinue = new Option<bool>("-c", "--continue"); private Option<bool> noContinue = new Option<bool>("--no-continue"); private Option<bool> part = new Option<bool>("--part"); private Option<bool> noPart = new Option<bool>("--no-part"); private Option<bool> mtime = new Option<bool>("--mtime"); private Option<bool> noMtime = new Option<bool>("--no-mtime"); private Option<bool> writeDescription = new Option<bool>("--write-description"); private Option<bool> noWriteDescription = new Option<bool>("--no-write-description"); private Option<bool> writeInfoJson = new Option<bool>("--write-info-json"); private Option<bool> noWriteInfoJson = new Option<bool>("--no-write-info-json"); private Option<bool> writePlaylistMetafiles = new Option<bool>("--write-playlist-metafiles"); private Option<bool> noWritePlaylistMetafiles = new Option<bool>("--no-write-playlist-metafiles"); private Option<bool> cleanInfoJson = new Option<bool>("--clean-info-json"); private Option<bool> noCleanInfoJson = new Option<bool>("--no-clean-info-json"); private Option<bool> writeComments = new Option<bool>("--write-comments"); private Option<bool> noWriteComments = new Option<bool>("--no-write-comments"); private Option<string> loadInfoJson = new Option<string>("--load-info-json"); private Option<string> cookies = new Option<string>("--cookies"); private Option<bool> noCookies = new Option<bool>("--no-cookies"); private Option<string> cookiesFromBrowser = new Option<string>("--cookies-from-browser"); private Option<bool> noCookiesFromBrowser = new Option<bool>("--no-cookies-from-browser"); private Option<string> cacheDir = new Option<string>("--cache-dir"); private Option<bool> noCacheDir = new Option<bool>("--no-cache-dir"); private Option<bool> removeCacheDir = new Option<bool>("--rm-cache-dir"); private Option<bool> help = new Option<bool>("-h", "--help"); private Option<bool> version = new Option<bool>("--version"); private Option<bool> update = new Option<bool>("-U", "--update"); private Option<bool> noUpdate = new Option<bool>("--no-update"); private Option<bool> ignoreErrors = new Option<bool>("-i", "--ignore-errors"); private Option<bool> noAbortOnError = new Option<bool>("--no-abort-on-error"); private Option<bool> abortOnError = new Option<bool>("--abort-on-error"); private Option<bool> dumpUserAgent = new Option<bool>("--dump-user-agent"); private Option<bool> listExtractors = new Option<bool>("--list-extractors"); private Option<bool> extractorDescriptions = new Option<bool>("--extractor-descriptions"); private Option<string> useExtractors = new Option<string>("--use-extractors"); private Option<string> defaultSearch = new Option<string>("--default-search"); private Option<bool> ignoreConfig = new Option<bool>("--ignore-config"); private Option<bool> noConfigLocations = new Option<bool>("--no-config-locations"); private MultiOption<string> configLocations = new MultiOption<string>("--config-locations"); private Option<bool> flatPlaylist = new Option<bool>("--flat-playlist"); private Option<bool> noFlatPlaylist = new Option<bool>("--no-flat-playlist"); private Option<bool> liveFromStart = new Option<bool>("--live-from-start"); private Option<bool> noLiveFromStart = new Option<bool>("--no-live-from-start"); private Option<string> waitForVideo = new Option<string>("--wait-for-video"); private Option<bool> noWaitForVideo = new Option<bool>("--no-wait-for-video"); private Option<bool> markWatched = new Option<bool>("--mark-watched"); private Option<bool> noMarkWatched = new Option<bool>("--no-mark-watched"); private Option<bool> noColors = new Option<bool>("--no-colors"); private Option<string> compatOptions = new Option<string>("--compat-options"); private Option<string> alias = new Option<string>("--alias"); private Option<string> geoVerificationProxy = new Option<string>("--geo-verification-proxy"); private Option<bool> geoBypass = new Option<bool>("--geo-bypass"); private Option<bool> noGeoBypass = new Option<bool>("--no-geo-bypass"); private Option<string> geoBypassCountry = new Option<string>("--geo-bypass-country"); private Option<string> geoBypassIpBlock = new Option<string>("--geo-bypass-ip-block"); private Option<bool> writeLink = new Option<bool>("--write-link"); private Option<bool> writeUrlLink = new Option<bool>("--write-url-link"); private Option<bool> writeWeblocLink = new Option<bool>("--write-webloc-link"); private Option<bool> writeDesktopLink = new Option<bool>("--write-desktop-link"); private Option<string> proxy = new Option<string>("--proxy"); private Option<int?> socketTimeout = new Option<int?>("--socket-timeout"); private Option<string> sourceAddress = new Option<string>("--source-address"); private Option<bool> forceIPv4 = new Option<bool>("-4", "--force-ipv4"); private Option<bool> forceIPv6 = new Option<bool>("-6", "--force-ipv6"); private Option<bool> extractAudio = new Option<bool>("-x", "--extract-audio"); private Option<AudioConversionFormat> audioFormat = new Option<AudioConversionFormat>("--audio-format"); private Option<byte?> audioQuality = new Option<byte?>("--audio-quality"); private Option<string> remuxVideo = new Option<string>("--remux-video"); private Option<VideoRecodeFormat> recodeVideo = new Option<VideoRecodeFormat>("--recode-video"); private MultiOption<string> postprocessorArgs = new MultiOption<string>("--postprocessor-args"); private Option<bool> keepVideo = new Option<bool>("-k", "--keep-video"); private Option<bool> noKeepVideo = new Option<bool>("--no-keep-video"); private Option<bool> postOverwrites = new Option<bool>("--post-overwrites"); private Option<bool> noPostOverwrites = new Option<bool>("--no-post-overwrites"); private Option<bool> embedSubs = new Option<bool>("--embed-subs"); private Option<bool> noEmbedSubs = new Option<bool>("--no-embed-subs"); private Option<bool> embedThumbnail = new Option<bool>("--embed-thumbnail"); private Option<bool> noEmbedThumbnail = new Option<bool>("--no-embed-thumbnail"); private Option<bool> embedMetadata = new Option<bool>("--embed-metadata"); private Option<bool> noEmbedMetadata = new Option<bool>("--no-embed-metadata"); private Option<bool> embedChapters = new Option<bool>("--embed-chapters"); private Option<bool> noEmbedChapters = new Option<bool>("--no-embed-chapters"); private Option<bool> embedInfoJson = new Option<bool>("--embed-info-json"); private Option<bool> noEmbedInfoJson = new Option<bool>("--no-embed-info-json"); private Option<string> parseMetadata = new Option<string>("--parse-metadata"); private MultiOption<string> replaceInMetadata = new MultiOption<string>("--replace-in-metadata"); private Option<bool> xattrs = new Option<bool>("--xattrs"); private Option<string> concatPlaylist = new Option<string>("--concat-playlist"); private Option<string> fixup = new Option<string>("--fixup"); private Option<string> ffmpegLocation = new Option<string>("--ffmpeg-location"); private MultiOption<string> exec = new MultiOption<string>("--exec"); private Option<bool> noExec = new Option<bool>("--no-exec"); private Option<string> convertSubs = new Option<string>("--convert-subs"); private Option<string> convertThumbnails = new Option<string>("--convert-thumbnails"); private Option<bool> splitChapters = new Option<bool>("--split-chapters"); private Option<bool> noSplitChapters = new Option<bool>("--no-split-chapters"); private MultiOption<string> removeChapters = new MultiOption<string>("--remove-chapters"); private Option<bool> noRemoveChapters = new Option<bool>("--no-remove-chapters"); private Option<bool> forceKeyframesAtCuts = new Option<bool>("--force-keyframes-at-cuts"); private Option<bool> noForceKeyframesAtCuts = new Option<bool>("--no-force-keyframes-at-cuts"); private MultiOption<string> usePostprocessor = new MultiOption<string>("--use-postprocessor"); private Option<string> sponsorblockMark = new Option<string>("--sponsorblock-mark"); private Option<string> sponsorblockRemove = new Option<string>("--sponsorblock-remove"); private Option<string> sponsorblockChapterTitle = new Option<string>("--sponsorblock-chapter-title"); private Option<bool> noSponsorblock = new Option<bool>("--no-sponsorblock"); private Option<string> sponsorblockApi = new Option<string>("--sponsorblock-api"); private Option<bool> writeSubs = new Option<bool>("--write-subs"); private Option<bool> noWriteSubs = new Option<bool>("--no-write-subs"); private Option<bool> writeAutoSubs = new Option<bool>("--write-auto-subs"); private Option<bool> noWriteAutoSubs = new Option<bool>("--no-write-auto-subs"); private Option<bool> listSubs = new Option<bool>("--list-subs"); private Option<string> subFormat = new Option<string>("--sub-format"); private Option<string> subLangs = new Option<string>("--sub-langs"); private Option<bool> writeThumbnail = new Option<bool>("--write-thumbnail"); private Option<bool> noWriteThumbnail = new Option<bool>("--no-write-thumbnail"); private Option<bool> writeAllThumbnails = new Option<bool>("--write-all-thumbnails"); private Option<bool> listThumbnails = new Option<bool>("--list-thumbnails"); private Option<bool> quiet = new Option<bool>("-q", "--quiet"); private Option<bool> noWarnings = new Option<bool>("--no-warnings"); private Option<bool> simulate = new Option<bool>("-s", "--simulate"); private Option<bool> noSimulate = new Option<bool>("--no-simulate"); private Option<bool> ignoreNoFormatsError = new Option<bool>("--ignore-no-formats-error"); private Option<bool> noIgnoreNoFormatsError = new Option<bool>("--no-ignore-no-formats-error"); private Option<bool> skipDownload = new Option<bool>("--skip-download"); private MultiOption<string> print = new MultiOption<string>("-O", "--print"); private MultiOption<string> printToFile = new MultiOption<string>("--print-to-file"); private Option<bool> dumpJson = new Option<bool>("-j", "--dump-json"); private Option<bool> dumpSingleJson = new Option<bool>("-J", "--dump-single-json"); private Option<bool> forceWriteArchive = new Option<bool>("--force-write-archive"); private Option<bool> newline = new Option<bool>("--newline"); private Option<bool> noProgress = new Option<bool>("--no-progress"); private Option<bool> progress = new Option<bool>("--progress"); private Option<bool> consoleTitle = new Option<bool>("--console-title"); private Option<string> progressTemplate = new Option<string>("--progress-template"); private Option<bool> verbose = new Option<bool>("-v", "--verbose"); private Option<bool> dumpPages = new Option<bool>("--dump-pages"); private Option<bool> writePages = new Option<bool>("--write-pages"); private Option<bool> printTraffic = new Option<bool>("--print-traffic"); private Option<string> format = new Option<string>("-f", "--format"); private Option<string> formatSort = new Option<string>("-S", "--format-sort"); private Option<bool> formatSortForce = new Option<bool>("--format-sort-force"); private Option<bool> noFormatSortForce = new Option<bool>("--no-format-sort-force"); private Option<bool> videoMultistreams = new Option<bool>("--video-multistreams"); private Option<bool> noVideoMultistreams = new Option<bool>("--no-video-multistreams"); private Option<bool> audioMultistreams = new Option<bool>("--audio-multistreams"); private Option<bool> noAudioMultistreams = new Option<bool>("--no-audio-multistreams"); private Option<bool> preferFreeFormats = new Option<bool>("--prefer-free-formats"); private Option<bool> noPreferFreeFormats = new Option<bool>("--no-prefer-free-formats"); private Option<bool> checkFormats = new Option<bool>("--check-formats"); private Option<bool> checkAllFormats = new Option<bool>("--check-all-formats"); private Option<bool> noCheckFormats = new Option<bool>("--no-check-formats"); private Option<bool> listFormats = new Option<bool>("-F", "--list-formats"); private Option<DownloadMergeFormat> mergeOutputFormat = new Option<DownloadMergeFormat>("--merge-output-format"); private Option<string> playlistItems = new Option<string>("-I", "--playlist-items"); private Option<string> minFilesize = new Option<string>("--min-filesize"); private Option<string> maxFilesize = new Option<string>("--max-filesize"); private Option<DateTime> date = new Option<DateTime>("--date"); private Option<DateTime> dateBefore = new Option<DateTime>("--datebefore"); private Option<DateTime> dateAfter = new Option<DateTime>("--dateafter"); private MultiOption<string> matchFilters = new MultiOption<string>("--match-filters"); private Option<bool> noMatchFilter = new Option<bool>("--no-match-filter"); private Option<bool> noPlaylist = new Option<bool>("--no-playlist"); private Option<bool> yesPlaylist = new Option<bool>("--yes-playlist"); private Option<byte?> ageLimit = new Option<byte?>("--age-limit"); private Option<string> downloadArchive = new Option<string>("--download-archive"); private Option<bool> noDownloadArchive = new Option<bool>("--no-download-archive"); private Option<int?> maxDownloads = new Option<int?>("--max-downloads"); private Option<bool> breakOnExisting = new Option<bool>("--break-on-existing"); private Option<bool> breakOnReject = new Option<bool>("--break-on-reject"); private Option<bool> breakPerInput = new Option<bool>("--break-per-input"); private Option<bool> noBreakPerInput = new Option<bool>("--no-break-per-input"); private Option<int?> skipPlaylistAfterErrors = new Option<int?>("--skip-playlist-after-errors"); private Option<string> encoding = new Option<string>("--encoding"); private Option<bool> legacyServerConnect = new Option<bool>("--legacy-server-connect"); private Option<bool> noCheckCertificates = new Option<bool>("--no-check-certificates"); private Option<bool> preferInsecure = new Option<bool>("--prefer-insecure"); private MultiOption<string> addHeader = new MultiOption<string>("--add-header"); private Option<bool> bidiWorkaround = new Option<bool>("--bidi-workaround"); private Option<int?> sleepRequests = new Option<int?>("--sleep-requests"); private Option<int?> sleepInterval = new Option<int?>("--sleep-interval"); private Option<int?> maxSleepInterval = new Option<int?>("--max-sleep-interval"); private Option<int?> sleepSubtitles = new Option<int?>("--sleep-subtitles"); public string Username { get { return username.Value; } set { username.Value = value; } } public string Password { get { return password.Value; } set { password.Value = value; } } public string TwoFactor { get { return twoFactor.Value; } set { twoFactor.Value = value; } } public bool Netrc { get { return netrc.Value; } set { netrc.Value = value; } } public string NetrcLocation { get { return netrcLocation.Value; } set { netrcLocation.Value = value; } } public string VideoPassword { get { return videoPassword.Value; } set { videoPassword.Value = value; } } public string ApMso { get { return apMso.Value; } set { apMso.Value = value; } } public string ApUsername { get { return apUsername.Value; } set { apUsername.Value = value; } } public string ApPassword { get { return apPassword.Value; } set { apPassword.Value = value; } } public bool ApListMso { get { return apListMso.Value; } set { apListMso.Value = value; } } public string ClientCertificate { get { return clientCertificate.Value; } set { clientCertificate.Value = value; } } public string ClientCertificateKey { get { return clientCertificateKey.Value; } set { clientCertificateKey.Value = value; } } public string ClientCertificatePassword { get { return clientCertificatePassword.Value; } set { clientCertificatePassword.Value = value; } } public IOption[] CustomOptions { get; set; } = new IOption[0]; [Obsolete("Deprecated in favor of: --print description.")] public bool GetDescription { get { return getDescription.Value; } set { getDescription.Value = value; } } [Obsolete("Deprecated in favor of: --print duration_string.")] public bool GetDuration { get { return getDuration.Value; } set { getDuration.Value = value; } } [Obsolete("Deprecated in favor of: --print filename.")] public bool GetFilename { get { return getFilename.Value; } set { getFilename.Value = value; } } [Obsolete("Deprecated in favor of: --print format.")] public bool GetFormat { get { return getFormat.Value; } set { getFormat.Value = value; } } [Obsolete("Deprecated in favor of: --print id.")] public bool GetId { get { return getId.Value; } set { getId.Value = value; } } [Obsolete("Deprecated in favor of: --print thumbnail.")] public bool GetThumbnail { get { return getThumbnail.Value; } set { getThumbnail.Value = value; } } [Obsolete("Deprecated in favor of: --print title.")] public bool GetTitle { get { return getTitle.Value; } set { getTitle.Value = value; } } [Obsolete("Deprecated in favor of: --print urls.")] public bool GetUrl { get { return getUrl.Value; } set { getUrl.Value = value; } } [Obsolete("Deprecated in favor of: --match-filter \"title ~= (?i)REGEX\".")] public string MatchTitle { get { return matchTitle.Value; } set { matchTitle.Value = value; } } [Obsolete("Deprecated in favor of: --match-filter \"title !~= (?i)REGEX\".")] public string RejectTitle { get { return rejectTitle.Value; } set { rejectTitle.Value = value; } } [Obsolete("Deprecated in favor of: --match-filter \"view_count >=? COUNT\".")] public long? MinViews { get { return minViews.Value; } set { minViews.Value = value; } } [Obsolete("Deprecated in favor of: --match-filter \"view_count <=? COUNT\".")] public long? MaxViews { get { return maxViews.Value; } set { maxViews.Value = value; } } [Obsolete("Deprecated in favor of: --add-header \"User-Agent:UA\".")] public string UserAgent { get { return userAgent.Value; } set { userAgent.Value = value; } } [Obsolete("Deprecated in favor of: --add-header \"Referer:URL\".")] public string Referer { get { return referer.Value; } set { referer.Value = value; } } [Obsolete("Deprecated in favor of: -I NUMBER:.")] public int? PlaylistStart { get { return playlistStart.Value; } set { playlistStart.Value = value; } } [Obsolete("Deprecated in favor of: -I :NUMBER.")] public int? PlaylistEnd { get { return playlistEnd.Value; } set { playlistEnd.Value = value; } } [Obsolete("Deprecated in favor of: -I ::-1.")] public bool PlaylistReverse { get { return playlistReverse.Value; } set { playlistReverse.Value = value; } } [Obsolete("Deprecated in favor of: --ies generic,default.")] public bool ForceGenericExtractor { get { return forceGenericExtractor.Value; } set { forceGenericExtractor.Value = value; } } [Obsolete("Deprecated in favor of: --exec \"before_dl:CMD\".")] public string ExecBeforeDownload { get { return execBeforeDownload.Value; } set { execBeforeDownload.Value = value; } } [Obsolete("Deprecated in favor of: --no-exec.")] public bool NoExecBeforeDownload { get { return noExecBeforeDownload.Value; } set { noExecBeforeDownload.Value = value; } } [Obsolete("Deprecated in favor of: -f all.")] public bool AllFormats { get { return allFormats.Value; } set { allFormats.Value = value; } } [Obsolete("Deprecated in favor of: --sub-langs all --write-subs.")] public bool AllSubs { get { return allSubs.Value; } set { allSubs.Value = value; } } [Obsolete("Deprecated in favor of: -j --no-simulate.")] public bool PrintJson { get { return printJson.Value; } set { printJson.Value = value; } } [Obsolete("Deprecated in favor of: Use string formatting, e.g. %(autonumber)03d.")] public string AutonumberSize { get { return autonumberSize.Value; } set { autonumberSize.Value = value; } } [Obsolete("Deprecated in favor of: Use internal field formatting like %(autonumber+NUMBER)s.")] public int? AutonumberStart { get { return autonumberStart.Value; } set { autonumberStart.Value = value; } } [Obsolete("Deprecated in favor of: -o \"%(id)s.%(ext)s\".")] public bool Id { get { return id.Value; } set { id.Value = value; } } [Obsolete("Deprecated in favor of: --parse-metadata \"%(title)s:FORMAT\".")] public string MetadataFromTitle { get { return metadataFromTitle.Value; } set { metadataFromTitle.Value = value; } } [Obsolete("Deprecated in favor of: --downloader \"m3u8:native\".")] public bool HlsPreferNative { get { return hlsPreferNative.Value; } set { hlsPreferNative.Value = value; } } [Obsolete("Deprecated in favor of: --downloader \"m3u8:ffmpeg\".")] public bool HlsPreferFfmpeg { get { return hlsPreferFfmpeg.Value; } set { hlsPreferFfmpeg.Value = value; } } [Obsolete("Deprecated in favor of: --compat-options list-formats (Alias: --no-list-formats-as-table).")] public bool ListFormatsOld { get { return listFormatsOld.Value; } set { listFormatsOld.Value = value; } } [Obsolete("Deprecated in favor of: --compat-options -list-formats [Default] (Alias: --no-list-formats-old).")] public bool ListFormatsAsTable { get { return listFormatsAsTable.Value; } set { listFormatsAsTable.Value = value; } } [Obsolete("Deprecated in favor of: --extractor-args \"youtube:skip=dash\" (Alias: --no-youtube-include-dash-manifest).")] public bool YoutubeSkipDashManifest { get { return youtubeSkipDashManifest.Value; } set { youtubeSkipDashManifest.Value = value; } } [Obsolete("Deprecated in favor of: --extractor-args \"youtube:skip=hls\" (Alias: --no-youtube-include-hls-manifest).")] public bool YoutubeSkipHlsManifest { get { return youtubeSkipHlsManifest.Value; } set { youtubeSkipHlsManifest.Value = value; } } public int? ConcurrentFragments { get { return concurrentFragments.Value; } set { concurrentFragments.Value = value; } } public long? LimitRate { get { return limitRate.Value; } set { limitRate.Value = value; } } public long? ThrottledRate { get { return throttledRate.Value; } set { throttledRate.Value = value; } } public int? Retries { get { return retries.Value; } set { retries.Value = value; } } public int? FileAccessRetries { get { return fileAccessRetries.Value; } set { fileAccessRetries.Value = value; } } public int? FragmentRetries { get { return fragmentRetries.Value; } set { fragmentRetries.Value = value; } } public MultiValue<string> RetrySleep { get { return retrySleep.Value; } set { retrySleep.Value = value; } } public bool SkipUnavailableFragments { get { return skipUnavailableFragments.Value; } set { skipUnavailableFragments.Value = value; } } public bool AbortOnUnavailableFragment { get { return abortOnUnavailableFragment.Value; } set { abortOnUnavailableFragment.Value = value; } } public bool KeepFragments { get { return keepFragments.Value; } set { keepFragments.Value = value; } } public bool NoKeepFragments { get { return noKeepFragments.Value; } set { noKeepFragments.Value = value; } } public long? BufferSize { get { return bufferSize.Value; } set { bufferSize.Value = value; } } public bool ResizeBuffer { get { return resizeBuffer.Value; } set { resizeBuffer.Value = value; } } public bool NoResizeBuffer { get { return noResizeBuffer.Value; } set { noResizeBuffer.Value = value; } } public long? HttpChunkSize { get { return httpChunkSize.Value; } set { httpChunkSize.Value = value; } } public bool PlaylistRandom { get { return playlistRandom.Value; } set { playlistRandom.Value = value; } } public bool LazyPlaylist { get { return lazyPlaylist.Value; } set { lazyPlaylist.Value = value; } } public bool NoLazyPlaylist { get { return noLazyPlaylist.Value; } set { noLazyPlaylist.Value = value; } } public bool XattrSetFilesize { get { return xattrSetFilesize.Value; } set { xattrSetFilesize.Value = value; } } public bool HlsUseMpegts { get { return hlsUseMpegts.Value; } set { hlsUseMpegts.Value = value; } } public bool NoHlsUseMpegts { get { return noHlsUseMpegts.Value; } set { noHlsUseMpegts.Value = value; } } public MultiValue<string> DownloadSections { get { return downloadSections.Value; } set { downloadSections.Value = value; } } public MultiValue<string> Downloader { get { return downloader.Value; } set { downloader.Value = value; } } public MultiValue<string> DownloaderArgs { get { return downloaderArgs.Value; } set { downloaderArgs.Value = value; } } public int? ExtractorRetries { get { return extractorRetries.Value; } set { extractorRetries.Value = value; } } public bool AllowDynamicMpd { get { return allowDynamicMpd.Value; } set { allowDynamicMpd.Value = value; } } public bool IgnoreDynamicMpd { get { return ignoreDynamicMpd.Value; } set { ignoreDynamicMpd.Value = value; } } public bool HlsSplitDiscontinuity { get { return hlsSplitDiscontinuity.Value; } set { hlsSplitDiscontinuity.Value = value; } } public bool NoHlsSplitDiscontinuity { get { return noHlsSplitDiscontinuity.Value; } set { noHlsSplitDiscontinuity.Value = value; } } public MultiValue<string> ExtractorArgs { get { return extractorArgs.Value; } set { extractorArgs.Value = value; } } public string BatchFile { get { return batchFile.Value; } set { batchFile.Value = value; } } public bool NoBatchFile { get { return noBatchFile.Value; } set { noBatchFile.Value = value; } } public string Paths { get { return paths.Value; } set { paths.Value = value; } } public string Output { get { return output.Value; } set { output.Value = value; } } public string OutputNaPlaceholder { get { return outputNaPlaceholder.Value; } set { outputNaPlaceholder.Value = value; } } public bool RestrictFilenames { get { return restrictFilenames.Value; } set { restrictFilenames.Value = value; } } public bool NoRestrictFilenames { get { return noRestrictFilenames.Value; } set { noRestrictFilenames.Value = value; } } public bool WindowsFilenames { get { return windowsFilenames.Value; } set { windowsFilenames.Value = value; } } public bool NoWindowsFilenames { get { return noWindowsFilenames.Value; } set { noWindowsFilenames.Value = value; } } public int? TrimFilenames { get { return trimFilenames.Value; } set { trimFilenames.Value = value; } } public bool NoOverwrites { get { return noOverwrites.Value; } set { noOverwrites.Value = value; } } public bool ForceOverwrites { get { return forceOverwrites.Value; } set { forceOverwrites.Value = value; } } public bool NoForceOverwrites { get { return noForceOverwrites.Value; } set { noForceOverwrites.Value = value; } } public bool Continue { get { return doContinue.Value; } set { doContinue.Value = value; } } public bool NoContinue { get { return noContinue.Value; } set { noContinue.Value = value; } } public bool Part { get { return part.Value; } set { part.Value = value; } } public bool NoPart { get { return noPart.Value; } set { noPart.Value = value; } } public bool Mtime { get { return mtime.Value; } set { mtime.Value = value; } }