Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of REPOLib v4.5.1
plugins/REPOLib.dll
Decompiled 2 weeks 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.Diagnostics.CodeAnalysis; 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 System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using ExitGames.Client.Photon; using HarmonyLib; using Microsoft.CodeAnalysis; using Photon.Pun; using Photon.Realtime; using Platforms; using REPOLib.Extensions; using REPOLib.Modules; using REPOLib.Objects; using REPOLib.Objects.Sdk; using REPOLib.Patches; using TMPro; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.Audio; using UnityEngine.Localization; using UnityEngine.Localization.Settings; using UnityEngine.Localization.Tables; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.ResourceManagement.ResourceProviders; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Zehs")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2026 Zehs")] [assembly: AssemblyDescription("Library for adding content to R.E.P.O.")] [assembly: AssemblyFileVersion("4.5.1.0")] [assembly: AssemblyInformationalVersion("4.5.1+9f7dc3f58d6055e35d37b35b9bc6bdea87c31287")] [assembly: AssemblyProduct("REPOLib")] [assembly: AssemblyTitle("REPOLib")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ZehsTeam/REPOLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace REPOLib { public static class BundleLoader { private class LoadOperation { public enum State { LoadingBundle, LoadingContent } public string Path { get; } public DateTime StartTime { get; } public State CurrentState { get; set; } public bool LoadContents { get; } public Func<AssetBundle, IEnumerator>? OnBundleLoaded { get; } public AssetBundleCreateRequest BundleRequest { get; } public TimeSpan ElapsedTime => DateTime.Now - StartTime; public string FileName => System.IO.Path.GetFileNameWithoutExtension(Path); public LoadOperation(string path, Func<AssetBundle, IEnumerator>? onBundleLoaded = null, bool loadContents = true) { Path = path; StartTime = DateTime.Now; LoadContents = loadContents; OnBundleLoaded = onBundleLoaded; BundleRequest = AssetBundle.LoadFromFileAsync(path); base..ctor(); } } private static readonly List<LoadOperation> _operations = new List<LoadOperation>(); internal static bool AllBundlesLoaded { get; private set; } public static event Action? OnAllBundlesLoaded; internal static void LoadAllBundles(string root, string withExtension) { Logger.LogInfo("Loading all bundles with extension " + withExtension + " from root " + root, extended: true); string[] files = Directory.GetFiles(root, "*" + withExtension, SearchOption.AllDirectories); string[] array = files; foreach (string path in array) { LoadBundleAndContent(path); } } public static void LoadBundleAndContent(string path) { LoadBundle(path, (Func<AssetBundle, IEnumerator>?)null, loadContents: true); } public static void LoadBundle(string path, Action<AssetBundle> onLoaded, bool loadContents = false) { LoadBundle(path, (Func<AssetBundle, IEnumerator>?)OnLoaded, loadContents); IEnumerator OnLoaded(AssetBundle bundle) { try { onLoaded(bundle); } catch (Exception arg) { Logger.LogError($"BundleLoader failed to invoke onLoaded method for AssetBundle at \"{path}\" {arg}"); } yield break; } } public static void LoadBundle(string path, Func<AssetBundle, IEnumerator>? onLoaded = null, bool loadContents = false) { Logger.LogInfo("Loading bundle at " + path + "..."); _operations.Add(new LoadOperation(path, onLoaded, loadContents)); } internal static void FinishLoadOperations(MonoBehaviour behaviour) { behaviour.StartCoroutine(FinishLoadOperationsRoutine(behaviour)); } private static IEnumerator FinishLoadOperationsRoutine(MonoBehaviour behaviour) { yield return null; AllBundlesLoaded = false; LoadOperation[] array = _operations.ToArray(); foreach (LoadOperation operation in array) { behaviour.StartCoroutine(FinishLoadOperation(operation)); } BundleLoaderLoadingText.Create(); float lastUpdate = Time.time; while (_operations.Count > 0) { if (Time.time - lastUpdate > 1f) { lastUpdate = Time.time; string arg = ((_operations.Count == 1) ? "bundle" : "bundles"); BundleLoaderLoadingText.SetText($"REPOLib: Waiting for {_operations.Count} {arg} to load..."); if (!ConfigManager.ExtendedLogging.Value) { continue; } foreach (LoadOperation operation2 in _operations) { string text = $"Loading {operation2.FileName}: {operation2.CurrentState}"; float? num = ((operation2.CurrentState != LoadOperation.State.LoadingBundle) ? ((float?)null) : new float?(((AsyncOperation)operation2.BundleRequest).progress)); float? num2 = num; if (num2.HasValue) { text += $" {num2.Value:P0}"; } Logger.LogDebug(text); } } yield return null; } Logger.LogInfo("Finished loading bundles."); BundleLoaderLoadingText.Hide(); AllBundlesLoaded = true; Utilities.SafeInvokeEvent(BundleLoader.OnAllBundlesLoaded); } private static IEnumerator FinishLoadOperation(LoadOperation operation) { yield return operation.BundleRequest; AssetBundle bundle = operation.BundleRequest.assetBundle; if ((Object)(object)bundle == (Object)null) { Logger.LogError("Failed to load bundle " + operation.FileName + "!"); Finish(); yield break; } HashSet<Object> legacyTextAssetSnapshot = FontAssetMaterialPatch.BeginLegacyBundle(operation.Path, bundle); yield return Localization.RegisterBundleStringTables(bundle); yield return PrefabRefResolver.ResolveBundle(bundle); if (operation.LoadContents) { yield return LoadBundleContent(operation, bundle); } if (operation.OnBundleLoaded != null) { yield return operation.OnBundleLoaded(bundle); } yield return Localization.FixLocalizedAssets(); if (legacyTextAssetSnapshot != null) { FontAssetMaterialPatch.EndLegacyBundle(operation.Path, bundle, legacyTextAssetSnapshot); } if (ConfigManager.ExtendedLogging.Value) { Logger.LogInfo($"Loaded bundle {operation.FileName} in {operation.ElapsedTime.TotalSeconds:N1}s"); } Finish(); void Finish() { _operations.Remove(operation); } } private static IEnumerator LoadBundleContent(LoadOperation operation, AssetBundle bundle) { operation.CurrentState = LoadOperation.State.LoadingContent; AssetBundleRequest assetRequest = bundle.LoadAllAssetsAsync<ScriptableObject>(); yield return assetRequest; Object[] allAssets = assetRequest.allAssets; Mod[] array = allAssets.OfType<Mod>().ToArray(); int num = array.Length; if (num <= 1) { if (num != 0) { Mod mod = array[0]; { foreach (Content item in allAssets.OfType<Content>().OrderByTypeFirst<Content, LevelContent>()) { try { item.Bundle = bundle; item.Initialize(mod); } catch (Exception ex) { Logger.LogError($"Failed to load {item.Name} ({((object)item).GetType().Name}) from bundle {operation.FileName} ({mod.Identifier}): {ex}"); } } yield break; } } Logger.LogError("Bundle " + operation.FileName + " contains no mods!"); } else { Logger.LogError("Bundle " + operation.FileName + " contains more than one mod!"); } } [Obsolete("Use LoadBundleAndContent instead")] public static void LoadBundle(string path, string relativePath) { LoadBundleAndContent(path); } } internal static class BundleLoaderLoadingText { private static TMP_Text? _text; public static void Create() { //IL_003b: 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_0076: 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_008c: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("HUD Canvas"); TMP_Text val2 = Object.FindObjectOfType<TMP_Text>(); _text = Object.Instantiate<TMP_Text>(val2, val.transform); ((Object)((Component)_text).gameObject).name = "REPOLibText"; ((Graphic)_text).color = Color.white; _text.fontStyle = (FontStyles)1; _text.alignment = (TextAlignmentOptions)514; RectTransform component = ((Component)_text).GetComponent<RectTransform>(); component.anchoredPosition = Vector2.zero; component.anchorMin = Vector2.zero; component.anchorMax = Vector2.one; component.sizeDelta = Vector2.zero; ((Component)_text).gameObject.SetActive(false); SetText("REPOLib is loading bundles... Hang tight!"); } public static void Show() { VideoOverlay.Instance.Override(999f, 0.02f, 2f); TMP_Text? text = _text; if (text != null) { ((Component)text).gameObject.SetActive(true); } } public static void Hide() { VideoOverlay.Instance.Override(0f, 0.02f, 2f); TMP_Text? text = _text; if (text != null) { ((Component)text).gameObject.SetActive(false); } } public static void SetText(string value) { if (!((Object)(object)_text == (Object)null)) { _text.text = value; } } } internal static class ConfigManager { public static ConfigFile ConfigFile { get; private set; } public static ConfigEntry<bool> ExtendedLogging { get; private set; } public static ConfigEntry<bool> DeveloperMode { get; private set; } public static ConfigEntry<bool> VanillaDeveloperMode { get; private set; } public static void Initialize(ConfigFile configFile) { ConfigFile = configFile; BindConfigs(); } private static void BindConfigs() { ExtendedLogging = ConfigFile.Bind<bool>("General", "ExtendedLogging", false, "Enable extended logging."); DeveloperMode = ConfigFile.Bind<bool>("General", "DeveloperMode", false, "Enable developer mode chat commands for testing."); VanillaDeveloperMode = ConfigFile.Bind<bool>("General", "VanillaDeveloperMode", false, "Enable vanilla developer mode cheats and chat commands for testing."); VanillaDeveloperMode.SettingChanged += delegate { PlatformManagerPatch.UpdateDeveloperMode(); }; } } internal static class Logger { public static ManualLogSource ManualLogSource { get; private set; } public static void Initialize(ManualLogSource manualLogSource) { ManualLogSource = manualLogSource; } public static void LogDebug(object data, bool extended = false) { Log((LogLevel)32, data, extended); } public static void LogInfo(object data, bool extended = false) { Log((LogLevel)16, data, extended); } public static void LogMessage(object data, bool extended = false) { Log((LogLevel)8, data, extended); } public static void LogWarning(object data, bool extended = false) { Log((LogLevel)4, data, extended); } public static void LogError(object data, bool extended = false) { Log((LogLevel)2, data, extended); } public static void LogFatal(object data, bool extended = false) { Log((LogLevel)1, data, extended); } public static void Log(LogLevel logLevel, object data, bool extended = false) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (!extended || IsExtendedLoggingEnabled()) { ManualLogSource manualLogSource = ManualLogSource; if (manualLogSource != null) { manualLogSource.Log(logLevel, data); } } } public static bool IsExtendedLoggingEnabled() { return ConfigManager.ExtendedLogging?.Value ?? false; } } [BepInPlugin("REPOLib", "REPOLib", "4.5.1")] public class Plugin : BaseUnityPlugin { private readonly Harmony _harmony = new Harmony("REPOLib"); public static Plugin Instance { get; private set; } private void Awake() { Instance = this; Logger.Initialize(Logger.CreateLogSource("REPOLib")); Logger.LogInfo("REPOLib has awoken!"); try { _harmony.PatchAll(typeof(RunManagerPatch)); _harmony.PatchAll(typeof(EnemyDirectorPatch)); _harmony.PatchAll(typeof(StatsManagerPatch)); _harmony.PatchAll(typeof(SemiFuncPatch)); _harmony.PatchAll(typeof(AudioManagerPatch)); _harmony.PatchAll(typeof(PlatformManagerPatch)); _harmony.PatchAll(typeof(PlayerControllerPatch)); _harmony.PatchAll(typeof(DebugCommandHandlerPatch)); _harmony.PatchAll(typeof(ResourcesPatch)); _harmony.PatchAll(typeof(SplashScreenPatch)); _harmony.PatchAll(typeof(MetaManagerPatch)); _harmony.PatchAll(typeof(PlayerCosmeticsPatch)); _harmony.PatchAll(typeof(FontAssetMaterialPatch)); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)ex); } ConfigManager.Initialize(((BaseUnityPlugin)this).Config); Upgrades.Initialize(); BundleLoader.LoadAllBundles(Paths.PluginPath, ".repobundle"); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "REPOLib"; public const string PLUGIN_NAME = "REPOLib"; public const string PLUGIN_VERSION = "4.5.1"; } } namespace REPOLib.Patches { [HarmonyPatch(typeof(AudioManager))] internal static class AudioManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch() { Utilities.FixAudioMixerGroupsOnPrefabs(); LevelAmbiences.RegisterLevelAmbiences(); } } [HarmonyPatch(typeof(DebugCommandHandler))] internal static class DebugCommandHandlerPatch { [HarmonyPatch("Start")] [HarmonyPrefix] private static void StartPatch() { Commands.RegisterCommands(); } } [HarmonyPatch(typeof(EnemyDirector))] internal static class EnemyDirectorPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void AwakePatch() { Enemies.RegisterEnemies(); } } [HarmonyPatch] internal static class FontAssetMaterialPatch { private static readonly HashSet<Object> _legacyAssets = new HashSet<Object>(); private static readonly Dictionary<string, Object?> _gameAssetCache = new Dictionary<string, Object>(); private static readonly HashSet<TMP_FontAsset> _checkedFontAssets = new HashSet<TMP_FontAsset>(); private static readonly int _mainTexId = Shader.PropertyToID("_MainTex"); private static readonly FieldRef<TMP_Text, TMP_FontAsset> _fontAssetRef = AccessTools.FieldRefAccess<TMP_Text, TMP_FontAsset>("m_fontAsset"); private static readonly FieldRef<TMP_Text, Material> _sharedMaterialRef = AccessTools.FieldRefAccess<TMP_Text, Material>("m_sharedMaterial"); private static readonly Regex _duplicateSuffixRegex = new Regex("\\s+(\\d+|\\(\\d+\\))$"); internal static HashSet<Object>? BeginLegacyBundle(string path, AssetBundle bundle) { if (bundle.isStreamedSceneAssetBundle) { return null; } string text = ReadBundleUnityVersion(path); if (ConfigManager.ExtendedLogging.Value) { Logger.LogInfo("Bundle \"" + Path.GetFileName(path) + "\" was built with Unity " + (text ?? "unknown") + "."); } if (text == null || !IsLegacyUnityVersion(text)) { return null; } HashSet<Object> hashSet = new HashSet<Object>(); foreach (Object loadedTextAsset in GetLoadedTextAssets()) { hashSet.Add(loadedTextAsset); } return hashSet; } internal static void EndLegacyBundle(string path, AssetBundle bundle, HashSet<Object> snapshot) { List<Object> list = (from asset in GetLoadedTextAssets().Concat((IEnumerable<Object>)(object)bundle.LoadAllAssets<TMP_FontAsset>()).Concat((IEnumerable<Object>)(object)bundle.LoadAllAssets<TMP_SpriteAsset>()) where !snapshot.Contains(asset) select asset).ToList(); _legacyAssets.UnionWith(list); Logger.LogDebug("Replacing TMP assets in bundle \"" + Path.GetFileName(path) + "\" with the game's: " + ((list.Count > 0) ? string.Join(", ", list.Select((Object asset) => "\"" + asset.name + "\"").Distinct()) : "none found"), extended: true); } private static IEnumerable<Object> GetLoadedTextAssets() { return ((IEnumerable<Object>)(object)Resources.FindObjectsOfTypeAll<TMP_FontAsset>()).Concat((IEnumerable<Object>)(object)Resources.FindObjectsOfTypeAll<TMP_SpriteAsset>()); } [HarmonyPatch(typeof(TextMeshPro), "LoadFontAsset")] [HarmonyPatch(typeof(TextMeshProUGUI), "LoadFontAsset")] [HarmonyPrefix] private static void LoadFontAssetPrefix(TMP_Text __instance) { ReplaceLegacyAssets(__instance); RestoreMaterial(__instance.font); } private static void ReplaceLegacyAssets(TMP_Text text) { if (_legacyAssets.Count == 0) { return; } TMP_FontAsset font = text.font; if ((Object)(object)font != (Object)null && _legacyAssets.Contains((Object)(object)font)) { TMP_FontAsset gameAsset = GetGameAsset<TMP_FontAsset>(((Object)font).name); if ((Object)(object)gameAsset != (Object)null) { _fontAssetRef.Invoke(text) = gameAsset; _sharedMaterialRef.Invoke(text) = ((TMP_Asset)gameAsset).material; } } TMP_SpriteAsset spriteAsset = text.spriteAsset; if ((Object)(object)spriteAsset != (Object)null && _legacyAssets.Contains((Object)(object)spriteAsset)) { text.spriteAsset = GetGameAsset<TMP_SpriteAsset>(((Object)spriteAsset).name); } } private static T? GetGameAsset<T>(string name) where T : Object { string text = NormalizeName(name); string key = typeof(T).Name + ":" + text; if (_gameAssetCache.TryGetValue(key, out Object value)) { return (T)(object)((value is T) ? value : null); } T val = FindGameAsset(Resources.FindObjectsOfTypeAll<T>(), text) ?? FindGameAsset(Resources.LoadAll<T>(string.Empty), text); if ((Object)(object)val != (Object)null) { Logger.LogInfo("Replaced legacy " + typeof(T).Name + " \"" + name + "\" with \"" + ((Object)val).name + "\"."); } else { Logger.LogWarning("Could not find a game " + typeof(T).Name + " matching legacy \"" + name + "\"."); } _gameAssetCache[key] = (Object)(object)val; return val; } private static T? FindGameAsset<T>(T[] assets, string normalizedName) where T : Object { return assets.Where((T asset) => (Object)(object)asset != (Object)null && !_legacyAssets.Contains((Object)(object)asset)).FirstOrDefault((T asset) => NormalizeName(((Object)asset).name) == normalizedName); } private static string NormalizeName(string name) { return _duplicateSuffixRegex.Replace(name, string.Empty); } private static bool IsLegacyUnityVersion(string unityVersion) { string s = unityVersion.Split('.')[0]; if (int.TryParse(s, out var result)) { return result < 6000; } return false; } private static string? ReadBundleUnityVersion(string path) { try { using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)); string text = ReadNullTerminatedString(binaryReader); if (!text.StartsWith("Unity")) { return null; } binaryReader.ReadUInt32(); ReadNullTerminatedString(binaryReader); return ReadNullTerminatedString(binaryReader); } catch (Exception ex) { Logger.LogWarning("Failed to read Unity version of bundle \"" + path + "\": " + ex.Message); return null; } } private static string ReadNullTerminatedString(BinaryReader reader) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 64; i++) { byte b = reader.ReadByte(); if (b == 0) { break; } stringBuilder.Append((char)b); } return stringBuilder.ToString(); } private static void RestoreMaterial(TMP_FontAsset? fontAsset) { if ((Object)(object)fontAsset == (Object)null || !_checkedFontAssets.Add(fontAsset)) { return; } if ((Object)(object)((TMP_Asset)fontAsset).material == (Object)null) { Material val = FindMaterial(fontAsset); if ((Object)(object)val != (Object)null) { ((TMP_Asset)fontAsset).material = val; Logger.LogInfo("Restored missing material \"" + ((Object)val).name + "\" on font asset \"" + ((Object)fontAsset).name + "\"."); } else { Logger.LogWarning("Font asset \"" + ((Object)fontAsset).name + "\" has no material and no matching material could be found."); } } if (fontAsset.fallbackFontAssetTable == null) { return; } foreach (TMP_FontAsset item in fontAsset.fallbackFontAssetTable) { RestoreMaterial(item); } } private static Material? FindMaterial(TMP_FontAsset fontAsset) { Material val = FindMaterial(fontAsset, Resources.FindObjectsOfTypeAll<Material>()); if ((Object)(object)val != (Object)null) { return val; } foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if (!allLoadedAssetBundle.isStreamedSceneAssetBundle) { val = FindMaterial(fontAsset, allLoadedAssetBundle.LoadAllAssets<Material>()); if ((Object)(object)val != (Object)null) { return val; } } } return null; } private static Material? FindMaterial(TMP_FontAsset fontAsset, Material[] materials) { Texture2D[] atlasTextures = fontAsset.atlasTextures; Texture2D val = ((atlasTextures != null && atlasTextures.Length > 0) ? fontAsset.atlasTexture : null); string text = ((Object)fontAsset).name + " Material"; Material val2 = null; Material val3 = null; foreach (Material val4 in materials) { if (!((Object)(object)val4 == (Object)null)) { bool flag = ((Object)val4).name == text; bool flag2 = (Object)(object)val != (Object)null && val4.HasProperty(_mainTexId) && (Object)(object)val4.GetTexture(_mainTexId) == (Object)(object)val; if (flag && flag2) { return val4; } if (flag2 && (Object)(object)val2 == (Object)null) { val2 = val4; } if (flag && (Object)(object)val3 == (Object)null) { val3 = val4; } } } if (!((Object)(object)val2 != (Object)null)) { return val3; } return val2; } } [HarmonyPatch(typeof(MetaManager))] internal static class MetaManagerPatch { private static List<string> missingCosmeticUnlocks = new List<string>(); private static List<string> missingCosmeticHistory = new List<string>(); private static List<string> missingCosmeticEquipped = new List<string>(); private static List<List<string>> missingCosmeticPresets = new List<List<string>>(); private static bool moddedSaveAllowed; private const int FileRetryAttempts = 5; private const int FileRetryDelay = 200; private const int BackupsKept = 3; private static string ModdedSavePath => MetaManager.instance.savePath + "Modded"; private static string SavePathVanilla => Path.Combine(Application.persistentDataPath, MetaManager.instance.savePath + ".es3"); private static string SavePathFull => Path.Combine(Application.persistentDataPath, ModdedSavePath + ".es3"); private static string SavePathLegacyBackup => Path.Combine(Application.persistentDataPath, ModdedSavePath + ".bak"); private static string SavePathLegacyTemp => Path.Combine(Application.persistentDataPath, ModdedSavePath + ".tmp"); [HarmonyPatch("Awake")] [HarmonyPrefix] private static void AwakePrefix(MetaManager __instance) { __instance.presetCacheFolder += "Modded"; } [HarmonyPatch("Awake")] [HarmonyPostfix] private static void AwakePatch(MetaManager __instance) { if ((Object)(object)__instance != (Object)(object)MetaManager.instance) { return; } if (BundleLoader.AllBundlesLoaded) { Cosmetics.RegisterCosmetics(); } else { BundleLoader.OnAllBundlesLoaded += Cosmetics.RegisterCosmetics; } string path = Path.Combine(Application.persistentDataPath, "Cache", "Icons", "Cosmetics"); if (!Directory.Exists(path)) { return; } int deletedCount = 0; int totalCount = 0; List<string> _cosmeticNames = new List<string>(from x in __instance.cosmeticAssets where (Object)(object)x != (Object)null && !Cosmetics.RegisteredCosmetics.Contains(x) select ((Object)x).name.ToLowerInvariant()); Directory.GetFiles(path).ToList().ForEach(delegate(string f) { if (!_cosmeticNames.Contains(Path.GetFileNameWithoutExtension(f).ToLowerInvariant())) { totalCount++; try { File.Delete(f); deletedCount++; } catch (Exception ex) { Logger.LogWarning("Could not delete file " + f + ": " + ex.Message); } } }); if (totalCount > 0) { Logger.LogInfo($"Deleted {deletedCount}/{totalCount} files for cosmetics icon cache"); } } [HarmonyPatch("PresetsInitialize")] [HarmonyPostfix] private static void PresetsInitializePatch(MetaManager __instance) { missingCosmeticPresets.Clear(); for (int i = 0; i < __instance.cosmeticPresets.Count; i++) { missingCosmeticPresets.Add(new List<string>()); } } [HarmonyPatch("Reset")] [HarmonyPrefix] private static void ResetPatch() { missingCosmeticUnlocks.Clear(); missingCosmeticHistory.Clear(); missingCosmeticEquipped.Clear(); missingCosmeticPresets.ForEach(delegate(List<string> x) { x.Clear(); }); SemiFunc.DeleteFileSafe(SavePathFull); SemiFunc.DeleteFileSafe(SavePathLegacyBackup); SemiFunc.DeleteFileSafe(SavePathLegacyTemp); foreach (string moddedBackup in GetModdedBackups()) { SemiFunc.DeleteFileSafe(moddedBackup); } } [HarmonyPatch("CosmeticPresetSet")] [HarmonyPrefix] private static void CosmeticPresetSetPatch(int _index, List<int> _cosmeticEquipped, List<int> _colorsEquipped) { if (_index >= 0 && _index < missingCosmeticPresets.Count) { missingCosmeticPresets[_index].Clear(); } } [HarmonyPatch("Save")] [HarmonyPrefix] private static bool SavePatch(MetaManager __instance) { if (!SemiFunc.IsMainEditor() || !__instance.saveAllowed) { return false; } try { ES3Settings val = __instance.MakeSettings(SavePathVanilla); val.location = (Location)4; if (File.Exists(SavePathVanilla)) { ES3.CacheFile(val); } else { ES3File.RemoveCachedFile(val); ES3.Save<List<int>>("cosmeticEquipped", __instance.cosmeticEquipped.Where(IsValidVanillaCosmetic).ToList(), val); ES3.Save<List<List<int>>>("cosmeticPresets", __instance.cosmeticPresets.Select((List<int> x) => x.Where(IsValidVanillaCosmetic).ToList()).ToList(), val); ES3.Save<List<List<int>>>("colorPresets", __instance.colorPresets, val); ES3.Save<int[]>("colorsEquipped", __instance.colorsEquipped, val); } ES3.Save<List<int>>("cosmeticTokens", __instance.cosmeticTokens, val); ES3.Save<List<int>>("cosmeticUnlocks", __instance.cosmeticUnlocks.Where(IsValidVanillaCosmetic).ToList(), val); ES3.Save<List<int>>("cosmeticHistory", __instance.cosmeticHistory.Where(IsValidVanillaCosmetic).ToList(), val); ES3.StoreCachedFile(val); } catch (Exception arg) { Logger.LogError($"[MetaSave] Save failed: {arg}"); } if (!moddedSaveAllowed) { return false; } try { ES3Settings val2 = __instance.MakeSettings(SavePathFull); val2.location = (Location)4; ES3.Save<List<string>>("cosmeticUnlocks", (from x in __instance.cosmeticUnlocks.Where(IsValidModdedCosmetic) select __instance.cosmeticAssets[x].assetId).Concat(missingCosmeticUnlocks).ToList(), val2); ES3.Save<List<string>>("cosmeticHistory", (from x in __instance.cosmeticHistory.Where(IsValidModdedCosmetic) select __instance.cosmeticAssets[x].assetId).Concat(missingCosmeticHistory).ToList(), val2); ES3.Save<List<string>>("cosmeticEquipped", (from x in __instance.cosmeticEquipped.Where(IsValidCosmetic) select __instance.cosmeticAssets[x].assetId).Concat(missingCosmeticEquipped).ToList(), val2); ES3.Save<List<List<string>>>("cosmeticPresets", __instance.cosmeticPresets.Select((List<int> preset, int i) => (from x in preset.Where(IsValidCosmetic) select __instance.cosmeticAssets[x].assetId).Concat((i < missingCosmeticPresets.Count) ? ((IEnumerable<string>)missingCosmeticPresets[i]) : ((IEnumerable<string>)new List<string>())).ToList()).ToList(), val2); ES3.Save<List<List<int>>>("colorPresets", __instance.colorPresets, val2); ES3.Save<int[]>("colorsEquipped", __instance.colorsEquipped, val2); ES3.StoreCachedFile(val2); } catch (Exception arg2) { Logger.LogError($"[MetaSaveModded] Save failed: {arg2}"); } return false; bool IsValidCosmetic(int x) { if (x >= 0 && x < __instance.cosmeticAssets.Count) { return (Object)(object)__instance.cosmeticAssets[x] != (Object)null; } return false; } bool IsValidModdedCosmetic(int x) { if (IsValidCosmetic(x)) { return Cosmetics.RegisteredCosmetics.Contains(__instance.cosmeticAssets[x]); } return false; } bool IsValidVanillaCosmetic(int x) { if (IsValidCosmetic(x)) { return !Cosmetics.RegisteredCosmetics.Contains(__instance.cosmeticAssets[x]); } return false; } } private static List<string> GetModdedBackups() { return ((IEnumerable<string>)Directory.GetFiles(Application.persistentDataPath, ModdedSavePath + "_BACKUP*.es3")).OrderByDescending((Func<string, int>)SemiFunc.GetBackupNumber).ToList(); } private static bool CreateModdedBackup(string _path) { if (!SemiFunc.IsMainEditor() || !File.Exists(_path)) { return false; } try { List<string> moddedBackups = GetModdedBackups(); int num = ((moddedBackups.Count <= 0) ? 1 : (SemiFunc.GetBackupNumber(moddedBackups[0]) + 1)); File.Copy(_path, Path.Combine(Application.persistentDataPath, $"{ModdedSavePath}_BACKUP{num}.es3"), overwrite: true); foreach (string item in GetModdedBackups().Skip(3)) { SemiFunc.DeleteFileSafe(item); } return true; } catch (Exception ex) { Logger.LogWarning("[MetaSaveModded] Could not back up " + Path.GetFileName(_path) + ": " + ex.Message); return false; } } [HarmonyPatch("Load")] [HarmonyPrefix] private static void LoadPrefix() { moddedSaveAllowed = false; } [HarmonyPatch("Load")] [HarmonyPostfix] private static void LoadPatch(MetaManager __instance) { LoadModded(); } private static bool TryLoadModded(string _path) { if (!File.Exists(_path)) { return false; } try { ES3Settings val = MetaManager.instance.MakeSettings(_path); if (!ES3.FileExists(val)) { return false; } if (ES3.KeyExists("cosmeticUnlocks", val)) { List<string> source = ES3.Load<List<string>>("cosmeticUnlocks", val); MetaManager.instance.cosmeticUnlocks = MetaManager.instance.cosmeticUnlocks.Concat(source.Where(IsValidCosmetic).Select(CosmeticIndex)).Distinct().ToList(); missingCosmeticUnlocks = source.Where((string x) => !IsValidCosmetic(x)).ToList(); } if (ES3.KeyExists("cosmeticHistory", val)) { List<string> source2 = ES3.Load<List<string>>("cosmeticHistory", val); MetaManager.instance.cosmeticHistory = MetaManager.instance.cosmeticHistory.Concat(source2.Where(IsValidCosmetic).Select(CosmeticIndex)).Distinct().ToList(); missingCosmeticHistory = source2.Where((string x) => !IsValidCosmetic(x)).ToList(); } if (ES3.KeyExists("cosmeticEquipped", val)) { List<string> source3 = ES3.Load<List<string>>("cosmeticEquipped", val); MetaManager.instance.cosmeticEquipped = source3.Where(IsValidCosmetic).Select(CosmeticIndex).ToList(); missingCosmeticEquipped = source3.Where((string x) => !IsValidCosmetic(x)).ToList(); } if (ES3.KeyExists("cosmeticPresets", val)) { List<List<string>> list = ES3.Load<List<List<string>>>("cosmeticPresets", val); if (list != null) { int num = Mathf.Min(new int[3] { MetaManager.instance.cosmeticPresets.Count, list.Count, missingCosmeticPresets.Count }); for (int num2 = 0; num2 < num; num2++) { MetaManager.instance.cosmeticPresets[num2] = list[num2].Where(IsValidCosmetic).Select(CosmeticIndex).ToList(); missingCosmeticPresets[num2] = list[num2].Where((string x) => !IsValidCosmetic(x)).ToList(); } } } if (ES3.KeyExists("colorPresets", val)) { List<List<int>> list2 = ES3.Load<List<List<int>>>("colorPresets", val); if (list2 != null) { int num3 = Mathf.Min(MetaManager.instance.colorPresets.Count, list2.Count); for (int num4 = 0; num4 < num3; num4++) { MetaManager.instance.colorPresets[num4] = list2[num4]; } } } if (ES3.KeyExists("colorsEquipped", val)) { int[] array = ES3.Load<int[]>("colorsEquipped", val); if (array != null) { int num5 = Mathf.Min(MetaManager.instance.colorsEquipped.Length, array.Length); for (int num6 = 0; num6 < num5; num6++) { MetaManager.instance.colorsEquipped[num6] = array[num6]; } } } return true; } catch (Exception arg) { Logger.LogError($"[MetaSaveModded] Failed to load {Path.GetFileName(_path)}: {arg}"); return false; } static int CosmeticIndex(string x) { return MetaManager.instance.cosmeticAssets.FindIndex((CosmeticAsset a) => Object.op_Implicit((Object)(object)a) && a.assetId == x); } static bool IsValidCosmetic(string x) { return Object.op_Implicit((Object)(object)((IEnumerable<CosmeticAsset>)MetaManager.instance.cosmeticAssets).FirstOrDefault((Func<CosmeticAsset, bool>)((CosmeticAsset a) => Object.op_Implicit((Object)(object)a) && a.assetId == x))); } } private static bool TryLoadModdedRetry(string _path) { if (!File.Exists(_path)) { return false; } for (int i = 1; i < 5; i++) { if (TryLoadModded(_path)) { return true; } Thread.Sleep(200); } return TryLoadModded(_path); } public static void LoadModded() { if (!Object.op_Implicit((Object)(object)MetaManager.instance)) { return; } SemiFunc.DeleteFileSafe(SavePathLegacyTemp); if (File.Exists(SavePathLegacyBackup)) { CreateModdedBackup(SavePathLegacyBackup); SemiFunc.DeleteFileSafe(SavePathLegacyBackup); } if (TryLoadModdedRetry(SavePathFull)) { Logger.LogInfo("[MetaSaveModded] " + ModdedSavePath + ".es3 found"); CreateModdedBackup(SavePathFull); moddedSaveAllowed = true; return; } List<string> moddedBackups = GetModdedBackups(); foreach (string item in moddedBackups) { if (TryLoadModdedRetry(item)) { Logger.LogWarning("[MetaSaveModded] " + ModdedSavePath + ".es3 restored from " + Path.GetFileName(item)); SemiFunc.DeleteFileSafe(SavePathFull); moddedSaveAllowed = true; MetaManager.instance.Save(); return; } } if (File.Exists(SavePathFull) || moddedBackups.Count > 0) { Logger.LogError("[MetaSaveModded] " + ModdedSavePath + " exists but could not be loaded - modded saving disabled this session"); moddedSaveAllowed = false; } else { Logger.LogWarning("[MetaSaveModded] " + ModdedSavePath + ".es3 not found - creating new"); moddedSaveAllowed = true; MetaManager.instance.Save(); } } } [HarmonyPatch(typeof(PlatformManager))] internal static class PlatformManagerPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] public static void AwakePatch(PlatformManager __instance) { if (!((Object)(object)__instance != (Object)(object)PlatformManager.instance) && ConfigManager.VanillaDeveloperMode != null && ConfigManager.VanillaDeveloperMode.Value) { UpdateDeveloperMode(); } } public static void UpdateDeveloperMode() { if (ConfigManager.VanillaDeveloperMode == null || (Object)(object)PlatformManager.instance == (Object)null) { return; } bool value = ConfigManager.VanillaDeveloperMode.Value; if (PlatformManager.instance.developerFlags.debug_console != value) { if (value) { Logger.LogInfo("Enabling vanilla developer mode."); } else { Logger.LogInfo("Disabling vanilla developer mode."); } } PlatformManager.instance.developerFlags.debug_console = value; } } [HarmonyPatch(typeof(PlayerController))] internal static class PlayerControllerPatch { [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> LateStartTranspiler(IEnumerable<CodeInstruction> instructions) { FieldInfo fieldInfo = AccessTools.Field(typeof(PlayerController), "playerAvatarScript"); MethodInfo methodInfo = AccessTools.Method(typeof(SemiFunc), "PlayerGetSteamID", new Type[1] { typeof(PlayerAvatar) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(Upgrades), "InvokeStartActions", new Type[1] { typeof(string) }, (Type[])null); bool found = false; int num = 0; List<CodeInstruction> list = new List<CodeInstruction>(); foreach (CodeInstruction instruction in instructions) { list.Add(instruction); if (num switch { 0 => instruction.opcode == OpCodes.Ldloc_1, 1 => instruction.opcode == OpCodes.Ldfld && CodeInstructionExtensions.LoadsField(instruction, fieldInfo, false), 2 => instruction.opcode == OpCodes.Call && CodeInstructionExtensions.Calls(instruction, methodInfo), 3 => instruction.opcode == OpCodes.Stloc_2, _ => false, }) { num++; if (num > 3) { found = true; num = 0; list.Add(new CodeInstruction(OpCodes.Ldloc_2, (object)null)); list.Add(new CodeInstruction(OpCodes.Call, (object)methodInfo2)); } } else { num = 0; } } foreach (CodeInstruction item in list) { yield return item; } if (!found) { Logger.LogWarning("Failed to patch PlayerController.LateStart!"); } } } [HarmonyPatch(typeof(PlayerCosmetics))] internal static class PlayerCosmeticsPatch { [HarmonyPatch("Awake")] [HarmonyPrefix] private static void AwakePatch(PlayerCosmetics __instance) { if (!Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent<PlayerCosmeticsModded>())) { ((Component)__instance).gameObject.AddComponent<PlayerCosmeticsModded>(); } } [HarmonyPatch("SetupCosmetics")] [HarmonyPrefix] private static bool SetupCosmeticsPatch(PlayerCosmetics __instance, bool _synced, bool _forced, List<int> _cosmetics) { PhotonView val = ((Object.op_Implicit((Object)(object)__instance.deathHead) && __instance.deathHead.setup && Object.op_Implicit((Object)(object)__instance.deathHead.playerAvatar)) ? __instance.deathHead.playerAvatar.photonView : __instance.photonView); if (_synced && SemiFunc.IsMultiplayer() && !val.IsMine) { return true; } PlayerCosmeticsModded component = ((Component)__instance).gameObject.GetComponent<PlayerCosmeticsModded>(); if (!Object.op_Implicit((Object)(object)component)) { return true; } component.cosmeticEquipped.Clear(); if (!SemiFunc.IsMultiplayer() || !_synced) { return true; } List<int> list = _cosmetics ?? MetaManager.instance.cosmeticEquipped; __instance.SetupCosmeticsLogic(list.ToArray(), _forced); List<string> list2 = new List<string>(); foreach (int item in list) { if (item >= 0 && item < MetaManager.instance.cosmeticAssets.Count) { CosmeticAsset val2 = MetaManager.instance.cosmeticAssets[item]; if (Object.op_Implicit((Object)(object)val2)) { list2.Add(val2.assetId); } } } PhotonNetwork.RemoveBufferedRPCs(((MonoBehaviourPun)component).photonView.ViewID, "SetupCosmeticsModdedRPC", (int[])null); ((MonoBehaviourPun)component).photonView.RPC("SetupCosmeticsModdedRPC", (RpcTarget)4, new object[1] { string.Join("\u001f", list2) }); PhotonNetwork.RemoveBufferedRPCs(__instance.photonView.ViewID, "SetupCosmeticsRPC", (int[])null); __instance.photonView.RPC("SetupCosmeticsRPC", (RpcTarget)4, new object[2] { list.Where(IsValidVanillaCosmetic).ToArray(), _forced }); return false; static bool IsValidVanillaCosmetic(int x) { if (x >= 0 && x < MetaManager.instance.cosmeticAssets.Count && (Object)(object)MetaManager.instance.cosmeticAssets[x] != (Object)null) { return !Cosmetics.RegisteredCosmetics.Contains(MetaManager.instance.cosmeticAssets[x]); } return false; } } [HarmonyPatch("SetupCosmeticsLogic")] [HarmonyPrefix] private static void SetupCosmeticsLogicPatch(PlayerCosmetics __instance, ref int[] _cosmeticEquipped, bool _forced) { PlayerCosmeticsModded component = ((Component)__instance).gameObject.GetComponent<PlayerCosmeticsModded>(); if (!Object.op_Implicit((Object)(object)component) || component.cosmeticEquipped.Count == 0) { return; } List<int> list = new List<int>(); foreach (string _cosmetic in component.cosmeticEquipped.ToList()) { int num = MetaManager.instance.cosmeticAssets.FindIndex((CosmeticAsset x) => x.assetId == _cosmetic); if (num >= 0) { list.Add(num); } } _cosmeticEquipped = list.ToArray(); } } [HarmonyPatch(typeof(Resources))] internal static class ResourcesPatch { [HarmonyPatch("Load", new Type[] { typeof(string), typeof(Type) })] [HarmonyPrefix] private static bool PrefabPatch(string path, Type systemTypeInstance, ref Object __result) { if (systemTypeInstance == typeof(GameObject) && NetworkPrefabs.TryGetNetworkPrefab(path, out GameObject prefab)) { __result = (Object)(object)prefab; return false; } return true; } } [HarmonyPatch(typeof(RunManager))] internal static class RunManagerPatch { private static bool _patchedAwake; [HarmonyPatch("Awake")] [HarmonyPostfix] [HarmonyPriority(0)] private static void AwakePatch(RunManager __instance) { if (!_patchedAwake) { _patchedAwake = true; NetworkingEvents.Initialize(); ValuablePresets.Initialize(); Levels.RegisterInitialLevels(); Valuables.RegisterInitialValuables(); BundleLoader.FinishLoadOperations((MonoBehaviour)(object)__instance); } } } [HarmonyPatch(typeof(SemiFunc))] internal static class SemiFuncPatch { [HarmonyPatch("DebugTester")] [HarmonyPrefix] private static bool DebugTesterPatch(ref bool __result) { if (ConfigManager.DeveloperMode.Value) { __result = true; return false; } return true; } [HarmonyPatch("EnemySpawn")] [HarmonyPrefix] private static bool EnemySpawnPatch(ref bool __result) { if (Enemies.SpawnNextEnemiesNotDespawned > 0) { Enemies.SpawnNextEnemiesNotDespawned--; __result = true; return false; } return true; } } [HarmonyPatch(typeof(SplashScreen))] internal static class SplashScreenPatch { private static bool _showedBundleLoaderLoadingText; [HarmonyPatch("StateWarning")] [HarmonyPostfix] private static void StateWarningPatch(SplashScreen __instance) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)__instance.state == 3) { ((Component)SplashScreenUI.instance.warningTransform).gameObject.SetActive(false); } } [HarmonyPatch("StateDone")] [HarmonyPrefix] private static bool StateDonePatch() { if (BundleLoader.AllBundlesLoaded) { return true; } if (_showedBundleLoaderLoadingText) { return false; } _showedBundleLoaderLoadingText = true; int childCount = ((Component)SplashScreenUI.instance).transform.childCount; for (int i = 1; i < childCount; i++) { Transform child = ((Component)SplashScreenUI.instance).transform.GetChild(i); ((Component)child).gameObject.SetActive(false); } BundleLoaderLoadingText.Show(); return false; } } [HarmonyPatch(typeof(StatsManager))] internal static class StatsManagerPatch { [HarmonyPatch("RunStartStats")] [HarmonyPostfix] private static void RunStartStatsPatch() { Items.RegisterItems(); Upgrades.RegisterUpgrades(); } } } namespace REPOLib.Objects { public enum LevelType { Normal, Shop, Arena } internal class PlayerCosmeticsModded : MonoBehaviourPun { public List<string> cosmeticEquipped = new List<string>(); [PunRPC] internal void SetupCosmeticsModdedRPC(string _cosmeticEquippedNames) { cosmeticEquipped = (string.IsNullOrEmpty(_cosmeticEquippedNames) ? new List<string>() : _cosmeticEquippedNames.Split("\u001f").ToList()); } } internal class PrefabRefComparer : IEqualityComparer<PrefabRef> { public StringComparison ComparisonType { get; } public PrefabRefComparer(StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) { ComparisonType = comparisonType; } public bool Equals(PrefabRef x, PrefabRef y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (string.Equals(((PrefabRef<GameObject>)(object)x).PrefabName, ((PrefabRef<GameObject>)(object)y).PrefabName, ComparisonType)) { return string.Equals(((PrefabRef<GameObject>)(object)x).ResourcePath, ((PrefabRef<GameObject>)(object)y).ResourcePath, ComparisonType); } return false; } public int GetHashCode(PrefabRef obj) { if (obj == null) { return 0; } int num = 17; num = num * 23 + (((PrefabRef<GameObject>)(object)obj).PrefabName?.GetHashCode(StringComparison.OrdinalIgnoreCase) ?? 0); return num * 23 + (((PrefabRef<GameObject>)(object)obj).ResourcePath?.GetHashCode(StringComparison.OrdinalIgnoreCase) ?? 0); } } internal static class PrefabRefResolver { private const string GameResourcesFolder = "Assets/REPO/Game/Resources/"; private const int MaxDepth = 8; private const BindingFlags InstanceFields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private static readonly Dictionary<Type, FieldInfo[]> _serializedFields = new Dictionary<Type, FieldInfo[]>(); private static readonly Dictionary<Type, (FieldInfo ResourcePath, FieldInfo Bundle)?> _prefabRefFields = new Dictionary<Type, (FieldInfo, FieldInfo)?>(); internal static IEnumerator ResolveBundle(AssetBundle bundle) { if (bundle.isStreamedSceneAssetBundle) { yield break; } AssetBundleRequest request = bundle.LoadAllAssetsAsync(); yield return request; int num = 0; Object[] allAssets = request.allAssets; foreach (Object val in allAssets) { GameObject val2 = (GameObject)(object)((val is GameObject) ? val : null); if (val2 == null) { ScriptableObject val3 = (ScriptableObject)(object)((val is ScriptableObject) ? val : null); if (val3 != null) { num += Walk(val3, bundle, 0); } continue; } MonoBehaviour[] componentsInChildren = val2.GetComponentsInChildren<MonoBehaviour>(true); foreach (MonoBehaviour val4 in componentsInChildren) { if ((Object)(object)val4 != (Object)null) { num += Walk(val4, bundle, 0); } } } if (num > 0) { Logger.LogDebug($"Resolved {num} PrefabRef(s) in bundle \"{((Object)bundle).name}\"", extended: true); } } internal static bool Resolve(object prefabRef, AssetBundle? bundle) { (FieldInfo, FieldInfo)? prefabRefFields = GetPrefabRefFields(prefabRef.GetType()); if (!prefabRefFields.HasValue) { return false; } (FieldInfo, FieldInfo) value = prefabRefFields.Value; FieldInfo item = value.Item1; FieldInfo item2 = value.Item2; string text = item.GetValue(prefabRef) as string; if (string.IsNullOrEmpty(text)) { return false; } if (text.StartsWith("Assets/REPO/Game/Resources/", StringComparison.OrdinalIgnoreCase)) { string text2 = text.Substring("Assets/REPO/Game/Resources/".Length); int num = text2.LastIndexOf('.'); text2 = ((num < 0) ? text2 : text2.Substring(0, num)); item.SetValue(prefabRef, text2); item2.SetValue(prefabRef, null); Logger.LogDebug("PrefabRef uses base-game asset \"" + text2 + "\" (converted from old path \"" + text + "\")" + FromBundle(bundle), extended: true); return true; } if (!text.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase)) { if ((Object)(object)bundle != (Object)null && !NetworkPrefabs.HasNetworkPrefab(text)) { Logger.LogDebug("PrefabRef uses base-game asset \"" + text + "\"" + FromBundle(bundle), extended: true); } return false; } if ((Object)(object)bundle == (Object)null) { return false; } object? value2 = item2.GetValue(prefabRef); if ((Object)((value2 is AssetBundle) ? value2 : null) == (Object)(object)bundle) { return false; } if (!bundle.Contains(text.ToLowerInvariant())) { Logger.LogWarning("PrefabRef to \"" + text + "\" can't be loaded because it isn't in bundle \"" + ((Object)bundle).name + "\". Make sure it's included in the bundle."); return false; } item2.SetValue(prefabRef, bundle); return true; } private static string FromBundle(AssetBundle? bundle) { if (!((Object)(object)bundle != (Object)null)) { return string.Empty; } return " in bundle \"" + ((Object)bundle).name + "\""; } private static int Walk(object obj, AssetBundle bundle, int depth) { if (depth > 8) { return 0; } Type type = obj.GetType(); if (GetPrefabRefFields(type).HasValue) { return Resolve(obj, bundle) ? 1 : 0; } int num = 0; FieldInfo[] serializedFields = GetSerializedFields(type); foreach (FieldInfo fieldInfo in serializedFields) { object value; try { value = fieldInfo.GetValue(obj); } catch { continue; } if (value == null || value is Object) { continue; } if (value is IList list) { foreach (object item in list) { if (item != null && !(item is Object)) { num += Walk(item, bundle, depth + 1); } } } else { num += Walk(value, bundle, depth + 1); } } return num; } private static FieldInfo[] GetSerializedFields(Type type) { if (_serializedFields.TryGetValue(type, out FieldInfo[] value)) { return value; } List<FieldInfo> list = new List<FieldInfo>(); Type type2 = type; while (type2 != null && type2 != typeof(object) && type2 != typeof(MonoBehaviour) && type2 != typeof(ScriptableObject)) { FieldInfo[] fields = type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (!fieldInfo.IsNotSerialized && (fieldInfo.IsPublic || ((MemberInfo)fieldInfo).GetCustomAttribute<SerializeField>() != null) && CanContainPrefabRef(fieldInfo.FieldType)) { list.Add(fieldInfo); } } type2 = type2.BaseType; } value = list.ToArray(); _serializedFields[type] = value; return value; } private static bool CanContainPrefabRef(Type type) { if (type.IsArray) { return CanContainPrefabRef(type.GetElementType()); } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { return CanContainPrefabRef(type.GetGenericArguments()[0]); } if (type.IsClass && type != typeof(string) && !typeof(Object).IsAssignableFrom(type)) { return type.IsSerializable; } return false; } private static (FieldInfo ResourcePath, FieldInfo Bundle)? GetPrefabRefFields(Type type) { if (_prefabRefFields.TryGetValue(type, out (FieldInfo, FieldInfo)? value)) { return value; } Type type2 = type; while (type2 != null && (!type2.IsGenericType || !(type2.GetGenericTypeDefinition() == typeof(PrefabRef<>)))) { type2 = type2.BaseType; } FieldInfo fieldInfo = type2?.GetField("resourcePath", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); FieldInfo fieldInfo2 = type2?.GetField("bundle", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); value = ((fieldInfo != null && fieldInfo2 != null) ? new(FieldInfo, FieldInfo)?((fieldInfo, fieldInfo2)) : (((FieldInfo, FieldInfo)?)null)); _prefabRefFields[type] = value; return value; } } internal enum PrefabRefResult { Success, PrefabIdNullOrEmpty, PrefabNull, PrefabAlreadyRegistered, DifferentPrefabAlreadyRegistered } internal struct PrefabRefResponse { public PrefabRefResult Result { get; set; } public PrefabRef? PrefabRef { get; set; } public PrefabRefResponse(PrefabRefResult result, PrefabRef? prefabRef) { Result = result; PrefabRef = prefabRef; } } internal class UnityObjectNameComparer<T> : IEqualityComparer<T> where T : Object { public StringComparison ComparisonType { get; private set; } public UnityObjectNameComparer(StringComparison comparisonType = StringComparison.OrdinalIgnoreCase) { ComparisonType = comparisonType; } public bool Equals(T x, T y) { if ((Object)(object)x == (Object)(object)y) { return true; } if ((Object)(object)x == (Object)null || (Object)(object)y == (Object)null) { return false; } return ((Object)x).name.Equals(((Object)y).name, ComparisonType); } public int GetHashCode(T obj) { if (!((Object)(object)obj != (Object)null)) { return 0; } return ((Object)obj).name.GetHashCode(); } } } namespace REPOLib.Objects.Sdk { public abstract class Content : ScriptableObject { public abstract string Name { get; } public abstract AssetBundle? Bundle { get; set; } public abstract void Initialize(Mod mod); } [CreateAssetMenu(menuName = "REPOLib/Cosmetic", order = 5, fileName = "New Cosmetic")] public class CosmeticContent : Content { [SerializeField] private string? _assetId; [SerializeField] private CosmeticAsset? _asset; [SerializeField] private GameObject? _prefab; [SerializeField] private PrefabRef? _prefabRef; public string? AssetId => _assetId; public CosmeticAsset? Asset => _asset; public GameObject? Prefab => _prefab; public PrefabRef? PrefabRef => _prefabRef; public override string Name { get { object obj = ((PrefabRef<GameObject>)(object)PrefabRef)?.PrefabName; if (obj == null) { GameObject? prefab = Prefab; obj = ((prefab != null) ? ((Object)prefab).name : null) ?? string.Empty; } return (string)obj; } } public override AssetBundle? Bundle { get; set; } public override void Initialize(Mod mod) { Cosmetics.RegisterCosmetic(this); } } [CreateAssetMenu(menuName = "REPOLib/Enemy", order = 3, fileName = "New Enemy")] public class EnemyContent : Content { [SerializeField] private EnemySetup? _setup; [SerializeField] private List<GameObject> _spawnObjects = new List<GameObject>(); public EnemySetup? Setup => _setup; public List<GameObject> SpawnObjects => _spawnObjects; public override string Name { get { EnemySetup? setup = Setup; return ((setup != null) ? ((Object)setup).name : null) ?? string.Empty; } } public override AssetBundle? Bundle { get; set; } public override void Initialize(Mod mod) { Enemies.RegisterEnemy(this); } } [CreateAssetMenu(menuName = "REPOLib/Item", order = 2, fileName = "New Item")] public class ItemContent : Content { [SerializeField] private ItemAttributes? _prefab; public ItemAttributes? Prefab => _prefab; public override string Name { get { ItemAttributes? prefab = Prefab; return ((prefab != null) ? ((Object)prefab).name : null) ?? string.Empty; } } public override AssetBundle? Bundle { get; set; } public override void Initialize(Mod mod) { Items.RegisterItem(this); } } [CreateAssetMenu(menuName = "REPOLib/Level", order = 4, fileName = "New Level")] public class LevelContent : Content { [SerializeField] private Level? _level; [SerializeField] private LevelType _levelType; [SerializeField] private GameObject? _connectObject; [SerializeField] private GameObject? _blockObject; [SerializeField] private List<GameObject> _startRooms = new List<GameObject>(); [Space] [Header("Difficulty 1")] [SerializeField] private List<GameObject> _modulesNormal1 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesPassage1 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesDeadEnd1 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesExtraction1 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesMega1 = new List<GameObject>(); [Space] [Header("Difficulty 2")] [SerializeField] private List<GameObject> _modulesNormal2 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesPassage2 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesDeadEnd2 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesExtraction2 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesMega2 = new List<GameObject>(); [Space] [Header("Difficulty 3")] [SerializeField] private List<GameObject> _modulesNormal3 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesPassage3 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesDeadEnd3 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesExtraction3 = new List<GameObject>(); [SerializeField] private List<GameObject> _modulesMega3 = new List<GameObject>(); [Space] [Header("Special")] [SerializeField] private int _modulesSpecialAmount; [SerializeField] private List<GameObject> _modulesSpecial = new List<GameObject>(); public Level? Level => _level; public override string Name { get { Level? level = Level; return ((level != null) ? ((Object)level).name : null) ?? string.Empty; } } public LevelType LevelType => _levelType; public GameObject? ConnectObject => _connectObject; public GameObject? BlockObject => _blockObject; public List<GameObject> StartRooms => _startRooms; public List<GameObject> ModulesNormal1 => _modulesNormal1; public List<GameObject> ModulesPassage1 => _modulesPassage1; public List<GameObject> ModulesDeadEnd1 => _modulesDeadEnd1; public List<GameObject> ModulesExtraction1 => _modulesExtraction1; public List<GameObject> ModulesMega1 => _modulesMega1; public List<GameObject> ModulesNormal2 => _modulesNormal2; public List<GameObject> ModulesPassage2 => _modulesPassage2; public List<GameObject> ModulesDeadEnd2 => _modulesDeadEnd2; public List<GameObject> ModulesExtraction2 => _modulesExtraction2; public List<GameObject> ModulesMega2 => _modulesMega2; public List<GameObject> ModulesNormal3 => _modulesNormal3; public List<GameObject> ModulesPassage3 => _modulesPassage3; public List<GameObject> ModulesDeadEnd3 => _modulesDeadEnd3; public List<GameObject> ModulesExtraction3 => _modulesExtraction3; public List<GameObject> ModulesMega3 => _modulesMega3; public int ModulesSpecialAmount => _modulesSpecialAmount; public List<GameObject> ModulesSpecial => _modulesSpecial; public override AssetBundle? Bundle { get; set; } public override void Initialize(Mod mod) { Levels.RegisterLevel(this); } } [CreateAssetMenu(menuName = "REPOLib/Mod", order = 0, fileName = "New Mod")] public class Mod : ScriptableObject { [SerializeField] private string _name; [SerializeField] private string _author; [SerializeField] private string _version = "1.0.0"; [SerializeField] private string _description; [SerializeField] private string _websiteUrl; [SerializeField] private string[] _dependencies = new string[1] { "Zehs-REPOLib-4.5.1" }; [SerializeField] private Sprite? _icon; [SerializeField] private TextAsset? _readme; public string Name => _name; public string Author => _author; public string Version => _version; public string Description => _description; public string WebsiteUrl => _websiteUrl; public IReadOnlyList<string> Dependencies => _dependencies; public Sprite? Icon => _icon; public TextAsset? Readme => _readme; public string FullName => Author + "-" + Name; public string Identifier => Author + "-" + Name + "-" + Version; } [CreateAssetMenu(menuName = "REPOLib/Valuable", order = 1, fileName = "New Valuable")] public class ValuableContent : Content { [SerializeField] private ValuableObject? _prefab; [SerializeField] private string[] _valuablePresets = new string[1] { "Valuables - Generic" }; public ValuableObject? Prefab => _prefab; public IReadOnlyList<string> ValuablePresets => _valuablePresets; public override string Name { get { ValuableObject? prefab = Prefab; return ((prefab != null) ? ((Object)prefab).name : null) ?? string.Empty; } } public override AssetBundle? Bundle { get; set; } public override void Initialize(Mod mod) { Valuables.RegisterValuable(this); } } } namespace REPOLib.Modules { public static class Commands { private static readonly List<ChatCommand> _commandsToRegister = new List<ChatCommand>(); private static readonly List<ChatCommand> _commandsRegistered = new List<ChatCommand>(); public static IReadOnlyList<ChatCommand> AllCommands => GetCommands(); public static IReadOnlyList<ChatCommand> RegisteredCommands => _commandsRegistered; internal static void RegisterCommands() { if ((Object)(object)DebugCommandHandler.instance == (Object)null) { Logger.LogError("Failed to register commands. DebugCommandHandler instance is null."); return; } Logger.LogInfo("Adding commands."); _commandsRegistered.Clear(); foreach (ChatCommand item in _commandsToRegister) { DebugCommandHandler.instance.Register(item); _commandsRegistered.Add(item); } } public static void RegisterCommand(ChatCommand chatCommand) { if (chatCommand == null) { throw new ArgumentException("Failed to register command. ChatCommand is null."); } if (chatCommand.Execute == null) { Logger.LogError("Failed to register command \"" + chatCommand.Name + "\". Execute method is null."); } else if (_commandsToRegister.Contains(chatCommand)) { Logger.LogError("Failed to register command \"" + chatCommand.Name + "\". Command is already registered!"); } else if (_commandsToRegister.Any((ChatCommand x) => x.Name == chatCommand.Name)) { Logger.LogError("Failed to register command \"" + chatCommand.Name + "\". Command already exists with the same name."); } else { _commandsToRegister.Add(chatCommand); } } private static IReadOnlyList<ChatCommand> GetCommands() { if ((Object)(object)DebugCommandHandler.instance == (Object)null) { return Array.Empty<ChatCommand>(); } return DebugCommandHandler.instance._commands.Values.ToList(); } } public static class Cosmetics { private static readonly List<CosmeticAsset> _cosmeticsToRegister = new List<CosmeticAsset>(); private static readonly List<CosmeticAsset> _cosmeticsRegistered = new List<CosmeticAsset>(); private static bool _initialCosmeticsRegistered; public static IReadOnlyList<CosmeticAsset> AllCosmetics => MetaManager.instance?.GetCosmetics() ?? new List<CosmeticAsset>(); public static IReadOnlyList<CosmeticAsset> RegisteredCosmetics => _cosmeticsRegistered; internal static void RegisterCosmetics() { BundleLoader.OnAllBundlesLoaded -= RegisterCosmetics; Logger.LogInfo("Adding cosmetics."); foreach (CosmeticAsset item in _cosmeticsToRegister) { RegisterCosmeticWithGame(item); } MetaManagerPatch.LoadModded(); _initialCosmeticsRegistered = true; } private static void RegisterCosmeticWithGame(CosmeticAsset item) { if (Object.op_Implicit((Object)(object)item.defaultColor)) { item.defaultColor = ((IEnumerable<SemiColor>)MetaManager.instance.colors).FirstOrDefault((Func<SemiColor, bool>)((SemiColor c) => c.color == item.defaultColor.color)); } if (string.IsNullOrWhiteSpace(item.assetId) || item.assetId.StartsWith("vanilla:")) { item.assetId = "modded:" + ((Object)item).name; } CosmeticAsset val = ((IEnumerable<CosmeticAsset>)AllCosmetics).FirstOrDefault((Func<CosmeticAsset, bool>)((CosmeticAsset x) => (Object)(object)x != (Object)(object)item && x.assetId == item.assetId)); if ((Object)(object)val != (Object)null) { Logger.LogWarning("Failed to add cosmetic \"" + ((Object)item).name + "\" to MetaManager. Same assetId as \"" + ((Object)val).name + "\". Asset ID: " + item.assetId, extended: true); } else if (MetaManager.instance.AddCosmetic(item)) { if (!_cosmeticsRegistered.Contains(item)) { _cosmeticsRegistered.Add(item); } Logger.LogInfo("Added cosmetic \"" + ((Object)item).name + "\" to MetaManager.", extended: true); } } public static PrefabRef? RegisterCosmetic(CosmeticAsset? cosmeticAsset) { if ((Object)(object)cosmeticAsset == (Object)null) { Logger.LogError("Failed to register cosmetic. CosmeticAsset is null."); return null; } if (cosmeticAsset.prefab == null) { Logger.LogError("Failed to register cosmetic \"" + ((Object)cosmeticAsset).name + "\". PrefabRef is null."); return null; } _cosmeticsToRegister.Add(cosmeticAsset); if (_initialCosmeticsRegistered) { RegisterCosmeticWithGame(cosmeticAsset); MetaManagerPatch.LoadModded(); } return cosmeticAsset.prefab; } public static PrefabRef? RegisterCosmetic(CosmeticContent? cosmeticContent) { if ((Object)(object)cosmeticContent == (Object)null) { Logger.LogError("Failed to register cosmetic. CosmeticContent is null."); return null; } if ((Object)(object)cosmeticContent.Asset == (Object)null) { Logger.LogError("Failed to register cosmetic. CosmeticAsset is null."); return null; } PrefabRef val = null; if (cosmeticContent.PrefabRef != null) { val = cosmeticContent.PrefabRef; if (val != null) { PrefabRefResolver.Resolve(val, cosmeticContent.Bundle); } } else { if (!((Object)(object)cosmeticContent.Prefab != (Object)null)) { Logger.LogError("Failed to register cosmetic. Prefab is null."); return null; } GameObject prefab = cosmeticContent.Prefab; string prefabId = "Cosmetics/" + ((Object)prefab).name; PrefabRefResponse prefabRefResponse = NetworkPrefabs.RegisterNetworkPrefabInternal(prefabId, prefab); val = prefabRefResponse.PrefabRef; if (prefabRefResponse.Result == PrefabRefResult.PrefabAlreadyRegistered) { Logger.LogWarning("Failed to register cosmetic \"" + ((Object)cosmeticContent).name + "\". Cosmetic is already registered!"); return null; } if (prefabRefResponse.Result == PrefabRefResult.DifferentPrefabAlreadyRegistered) { Logger.LogError("Failed to register cosmetic \"" + ((Object)cosmeticContent).name + "\". A cosmetic prefab is already registered with the same name."); return null; } if (prefabRefResponse.Result != PrefabRefResult.Success) { Logger.LogError($"Failed to register cosmetic \"{((Object)cosmeticContent).name}\". (Reason: {prefabRefResponse.Result})"); return null; } } if (val == null) { Logger.LogError("Failed to register cosmetic \"" + ((Object)cosmeticContent).name + "\". PrefabRef is null."); return null; } cosmeticContent.Asset.prefab = val; if (!string.IsNullOrWhiteSpace(cosmeticContent.AssetId)) { cosmeticContent.Asset.assetId = cosmeticContent.AssetId; } return RegisterCosmetic(cosmeticContent.Asset); } } public static class Enemies { internal static int SpawnNextEnemiesNotDespawned = 0; private static readonly List<EnemySetup> _enemiesToRegister = new List<EnemySetup>(); public static IReadOnlyList<EnemySetup> AllEnemies => EnemyDirector.instance?.GetEnemies() ?? new List<EnemySetup>(); public static IReadOnlyList<EnemySetup> RegisteredEnemies => _enemiesToRegister; internal static void RegisterEnemies() { Logger.LogInfo("Adding enemies."); foreach (EnemySetup item in _enemiesToRegister) { RegisterEnemyWithGame(item); } } private static void RegisterEnemyWithGame(EnemySetup enemySetup) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) if (!enemySetup.TryGetEnemyParent(out EnemyParent enemyParent)) { Logger.LogError("Failed to register enemy \"" + ((Object)enemySetup).name + "\" to game. Could not find EnemyParent component."); } else if (EnemyDirector.instance.AddEnemy(enemySetup)) { Logger.LogInfo($"Added enemy \"{enemyParent.enemyName}\" to difficulty {enemyParent.difficulty}", extended: true); } } public static void RegisterEnemy(EnemyContent? enemyContent) { if ((Object)(object)enemyContent == (Object)null) { Logger.LogError("Failed to register enemy. EnemyContent is null."); return; } EnemySetup enemySetup = enemyContent.Setup; List<GameObject> spawnObjects = enemyContent.SpawnObjects; if ((Object)(object)enemySetup == (Object)null) { Logger.LogError("Failed to register enemy. EnemySetup is null."); return; } if (spawnObjects == null || spawnObjects.Count == 0) { Logger.LogError("Failed to register enemy \"" + enemyContent.Name + "\". No spawn objects found."); return; } if (_enemiesToRegister.Contains(enemySetup)) { Logger.LogError("Failed to register enemy \"" + enemyContent.Name + "\". Enemy is already registered!"); return; } if (_enemiesToRegister.Any((EnemySetup x) => ((Object)x).name == ((Object)enemySetup).name)) { Logger.LogError("Failed to register enemy \"" + enemyContent.Name + "\". Enemy already exists with the same name."); return; } List<PrefabRef> list = new List<PrefabRef>(); foreach (GameObject item in spawnObjects) { if ((Object)(object)item == (Object)null) { Logger.LogWarning("Enemy \"" + enemyContent.Name + "\" has a null spawn object."); continue; } string prefabId = "Enemies/" + ((Object)item).name; PrefabRefResponse prefabRefResponse = NetworkPrefabs.RegisterNetworkPrefabInternal(prefabId, item); PrefabRef prefabRef = prefabRefResponse.PrefabRef; if (prefabRefResponse.Result == PrefabRefResult.DifferentPrefabAlreadyRegistered) { Logger.LogError("Failed to register enemy \"" + enemyContent.Name + "\" spawn object. A prefab is already registered with the same name."); continue; } if (prefabRefResponse.Result != PrefabRefResult.Success && prefabRefResponse.Result != PrefabRefResult.PrefabAlreadyRegistered) { Logger.LogError($"Failed to register enemy \"{enemyContent.Name}\" spawn object. (Reason: {prefabRefResponse.Result})"); continue; } if (prefabRef == null) { Logger.LogError("Failed to register enemy \"" + enemyContent.Name + "\" spawn object. PrefabRef is null."); continue; } if (prefabRefResponse.Result == PrefabRefResult.Success) { Utilities.FixAudioMixerGroups(item); } list.Add(prefabRef); } if (list.Count == 0) { Logger.LogError("Failed to register enemy \"" + enemyContent.Name + "\". No valid spawn objects found."); return; } enemySetup.spawnObjects = list; _enemiesToRegister.Add(enemySetup); } public static List<EnemyParent>? SpawnEnemy(EnemySetup? enemySetup, Vector3 position, Quaternion rotation, bool spawnDespawned = false) { //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_024d: 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) if ((Object)(object)enemySetup == (Object)null) { Logger.LogError("Failed to spawn enemy. EnemySetup is null."); return null; } if (!enemySetup.TryGetEnemyParent(out EnemyParent enemyParent)) { Logger.LogError("Failed to spawn enemy. EnemyParent is null."); return null; } if ((Object)(object)LevelGenerator.Instance == (Object)null) { Logger.LogError("Failed to spawn enemy \"" + enemyParent.enemyName + "\". EnemySetup instance is null."); return null; } if ((Object)(object)RunManager.instance == (Object)null) { Logger.LogError("Failed to spawn enemy \"" + enemyParent.enemyName + "\". RunManager instance is null."); return null; } if ((Object)(object)EnemyDirector.instance == (Object)null) { Logger.LogError("Failed to spawn enemy \"" + enemyParent.enemyName + "\". EnemyDirector instance is null."); return null; } RunManager.instance.EnemiesSpawnedRemoveStart(); List<EnemyParent> list = new List<EnemyParent>(); EnemyParent val2 = default(EnemyParent); foreach (PrefabRef spawnObject in enemySetup.spawnObjects) { GameObject prefab = ((PrefabRef<GameObject>)(object)spawnObject).Prefab; if ((Object)(object)prefab == (Object)null) { Logger.LogError("Failed to spawn enemy \"" + enemyParent.enemyName + "\" spawn object. GameObject is null."); continue; } GameObject val = NetworkPrefabs.SpawnNetworkPrefab(spawnObject, position, rotation, 0); if ((Object)(object)val == (Object)null) { Logger.LogError("Failed to spawn enemy \"" + enemyParent.enemyName + "\" spawn object \"" + ((Object)prefab).name + "\""); } else if (val.TryGetComponent<EnemyParent>(ref val2)) { list.Add(val2); if (!spawnDespawned) { SpawnNextEnemiesNotDespawned++; } val2.SetupDone = true; Enemy componentInChildren = val.GetComponentInChildren<Enemy>(); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.EnemyTeleported(position); } else { Logger.LogError("Enemy \"" + enemyParent.enemyName + "\" spawn object \"" + ((Object)prefab).name + "\" does not have an enemy component."); } val2.firstSpawnPointUsed = true; EnemyDirector.instance.FirstSpawnPointAdd(val2); } } RunManager.instance.EnemiesSpawnedRemoveEnd(); if (list.Count == 0) { Logger.LogInfo("Failed to spawn enemy \"" + enemyParent.enemyName + "\". No spawn objects where spawned."); return list; } Logger.LogInfo($"Spawned enemy \"{enemyParent.enemyName}\" at position {position}", extended: true); return list; } [Obsolete("This is no longer supported. Use AllEnemies or RegisteredEnemies instead.", true)] public static IReadOnlyList<EnemySetup> GetEnemies() { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return AllEnemies; } [Obsolete("This is no longer supported. Use AllEnemies or RegisteredEnemies instead.", true)] public static bool TryGetEnemyByName(string name, [NotNullWhen(true)] out EnemySetup? enemySetup) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); enemySetup = null; return false; } [Obsolete("This is no longer supported. Use AllEnemies or RegisteredEnemies instead.", true)] public static EnemySetup? GetEnemyByName(string name) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return null; } [Obsolete("This is no longer supported. Use AllEnemies or RegisteredEnemies instead.", true)] public static bool TryGetEnemyThatContainsName(string name, [NotNullWhen(true)] out EnemySetup? enemySetup) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); enemySetup = null; return false; } [Obsolete("This is no longer supported. Use AllEnemies or RegisteredEnemies instead.", true)] public static EnemySetup? GetEnemyThatContainsName(string name) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return null; } } public static class Items { private static readonly List<Item> _itemsToRegister = new List<Item>(); private static readonly List<Item> _itemsRegistered = new List<Item>(); private static bool _initialItemsRegistered; public static IReadOnlyList<Item> AllItems => StatsManager.instance?.GetItems() ?? new List<Item>(); public static IReadOnlyList<Item> RegisteredItems => _itemsRegistered; internal static void RegisterItems() { Logger.LogInfo("Adding items."); foreach (Item item in _itemsToRegister) { RegisterItemWithGame(item); } _initialItemsRegistered = true; } private static void RegisterItemWithGame(Item item) { if (StatsManager.instance.AddItem(item)) { if (!_itemsRegistered.Contains(item)) { _itemsRegistered.Add(item); } Logger.LogInfo("Added item \"" + item.itemName + "\" to StatsManager.", extended: true); } else { Logger.LogWarning("Failed to add item \"" + item.itemName + "\" to StatsManager.", extended: true); } } public static PrefabRef? RegisterItem(ItemAttributes? itemAttributes) { if ((Object)(object)itemAttributes == (Object)null) { Logger.LogError("Failed to register item. ItemAttributes is null."); return null; } Item item = itemAttributes.item; if ((Object)(object)item == (Object)null) { Logger.LogError("Failed to register item. Item is null."); return null; } GameObject gameObject = ((Component)itemAttributes).gameObject; string prefabId = "Items/" + ((Object)gameObject).name; PrefabRefResponse prefabRefResponse = NetworkPrefabs.RegisterNetworkPrefabInternal(prefabId, gameObject); PrefabRef prefabRef = prefabRefResponse.PrefabRef; if (prefabRefResponse.Result == PrefabRefResult.PrefabAlreadyRegistered) { Logger.LogWarning("Failed to register item \"" + item.itemName + "\". Item is already registered!"); return null; } if (prefabRefResponse.Result == PrefabRefResult.DifferentPrefabAlreadyRegistered) { Logger.LogError("Failed to register item \"" + item.itemName + "\". A item prefab is already registered with the same name."); return null; } if (prefabRefResponse.Result != PrefabRefResult.Success) { Logger.LogError($"Failed to register item \"{((Object)gameObject).name}\". (Reason: {prefabRefResponse.Result})"); return null; } if (prefabRef == null) { Logger.LogError("Failed to register item \"" + ((Object)gameObject).name + "\". PrefabRef is null."); return null; } item.prefab = prefabRef; Utilities.FixAudioMixerGroups(gameObject); _itemsToRegister.Add(item); if (_initialItemsRegistered) { RegisterItemWithGame(item); } return prefabRef; } public static PrefabRef? RegisterItem(ItemContent? itemContent) { if ((Object)(object)itemContent == (Object)null) { Logger.LogError("Failed to register item. ItemContent is null."); return null; } return RegisterItem(itemContent.Prefab); } public static GameObject? SpawnItem(Item? item, Vector3 position, Quaternion rotation) { //IL_006a: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)item == (Object)null) { Logger.LogError("Failed to spawn item. Item is null."); return null; } if (!((PrefabRef<GameObject>)(object)item.prefab).IsValid()) { Logger.LogError("Failed to spawn item \"" + item.itemName + "\". PrefabRef is not valid."); return null; } if (!SemiFunc.IsMasterClientOrSingleplayer()) { Logger.LogError("Failed to spawn item \"" + item.itemName + "\". You are not the host."); return null; } GameObject val = NetworkPrefabs.SpawnNetworkPrefab(item.prefab, position, rotation, 0); if ((Object)(object)val == (Object)null) { Logger.LogError("Failed to spawn item \"" + item.itemName + "\". Spawned GameObject is null."); return null; } Logger.LogInfo($"Spawned item \"{item.itemName}\" at position {position}, rotation: {((Quaternion)(ref rotation)).eulerAngles}", extended: true); return val; } [Obsolete("This is no longer supported. Use AllItems or RegisteredItems instead.", true)] public static IReadOnlyList<Item> GetItems() { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return AllItems; } [Obsolete("This is no longer supported. Use AllItems or RegisteredItems instead.", true)] public static bool TryGetItemByName(string name, [NotNullWhen(true)] out Item? item) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); item = null; return false; } [Obsolete("This is no longer supported. Use AllItems or RegisteredItems instead.", true)] public static Item? GetItemByName(string name) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return null; } [Obsolete("This is no longer supported. Use AllItems or RegisteredItems instead.", true)] public static bool TryGetItemThatContainsName(string name, [NotNullWhen(true)] out Item? item) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); item = null; return false; } [Obsolete("This is no longer supported. Use AllItems or RegisteredItems instead.", true)] public static Item? GetItemThatContainsName(string name) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return null; } } internal static class LevelAmbiences { private static readonly List<LevelAmbience> _levelAmbiencesRegistered = new List<LevelAmbience>(); private static readonly List<Level> _levelToProcess = new List<Level>(); private static readonly List<Level> _levelsProcessed = new List<Level>(); private static bool _initialLevelAmbiencesRegistered; public static IReadOnlyList<LevelAmbience> AllLevelAmbiences => AudioManager.instance?.levelAmbiences ?? new List<LevelAmbience>(); public static IReadOnlyList<LevelAmbience> RegisteredLevelAmbiences => _levelAmbiencesRegistered; internal static void RegisterLevelAmbiences() { if (_initialLevelAmbiencesRegistered) { foreach (LevelAmbience item in _levelAmbiencesRegistered) { AddLevelAmbienceToAudioManager(item); } return; } Logger.LogInfo("Adding level ambiences."); foreach (Level item2 in _levelToProcess) { RegisterLevelAmbiencesWithGame(item2); } _initialLevelAmbiencesRegistered = true; } private static void AddLevelAmbienceToAudioManager(LevelAmbience levelAmbience) { if (!AllLevelAmbiences.Contains(levelAmbience)) { AudioManager.instance.levelAmbiences.Add(levelAmbience); Logger.LogInfo("Added level ambience \"" + ((Object)levelAmbience).name + "\" to AudioManager.", extended: true); } } private static void RegisterLevelAmbiencesWithGame(Level level) { if (_levelsProcessed.Contains(level)) { return; } for (int i = 0; i < level.AmbiencePresets.Count; i++) { LevelAmbience val = level.AmbiencePresets[i]; if (!AudioManager.instance.levelAmbiences.Contains(val)) { if (TryGetLevelAmbience(((Object)val).name, out LevelAmbience levelAmbience)) { level.AmbiencePresets[i] = levelAmbience; Logger.LogInfo("Replaced existing level ambience \"" + ((Object)val).name + "\" in level \"" + ((Object)level).name + "\"", extended: true); } else { AddLevelAmbienceToAudioManager(val); _levelAmbiencesRegistered.Add(val); Logger.LogInfo("Registered level ambience \"" + ((Object)val).name + "\" from level \"" + ((Object)level).name + "\"", extended: true); } } } _levelsProcessed.Add(level); } public static void RegisterLevelAmbience(Level? level) { if ((Object)(object)level == (Object)null) { Logger.LogError("Failed to register level ambience for level. Level is null."); return; } if (_levelToProcess.Contains(level)) { Logger.LogWarning("Failed to register level ambience for level \"" + ((Object)level).name + "\". Level has already been processed!"); return; } _levelToProcess.Add(level); if (_initialLevelAmbiencesRegistered) { RegisterLevelAmbiencesWithGame(level); } } private static bool TryGetLevelAmbience(string name, [NotNullWhen(true)] out LevelAmbience? levelAmbience) { levelAmbience = ((IEnumerable<LevelAmbience>)AllLevelAmbiences).FirstOrDefault((Func<LevelAmbience, bool>)((LevelAmbience x) => ((Object)x).name == name)); return (Object)(object)levelAmbience != (Object)null; } } public static class Levels { private enum ModuleType { StartRoom, Normal, Passage, DeadEnd, Extraction, Special, Mega } private static readonly List<Level> _levelsToRegister = new List<Level>(); private static readonly List<Level> _levelsRegistered = new List<Level>(); private static readonly Dictionary<Level, LevelType> _levelTypes = new Dictionary<Level, LevelType>(); private static bool _initialLevelsRegistered; public static IReadOnlyList<Level> AllLevels => RunManager.instance?.levels ?? new List<Level>(); public static IReadOnlyList<Level> AllShopLevels => RunManager.instance?.levelShop ?? new List<Level>(); public static IReadOnlyList<Level> AllArenaLevels => RunManager.instance?.levelArena ?? new List<Level>(); public static IReadOnlyList<Level> RegisteredLevels => _levelsRegistered; internal static void RegisterInitialLevels() { if (_initialLevelsRegistered) { return; } Logger.LogInfo("Adding levels."); foreach (Level item in _levelsToRegister) { RegisterLevelWithGame(item); } _initialLevelsRegistered = true; } private static void RegisterLevelWithGame(Level level) { if (!_levelsRegistered.Contains(level)) { LevelType levelType = GetLevelType(level); List<Level> gameLevelList = GetGameLevelList(levelType); if (gameLevelList.Any((Level x) => (Object)(object)x != (Object)null && ((Object)x).name.Equals(((Object)level).name, StringComparison.OrdinalIgnoreCase))) { Logger.LogError($"Failed to add {levelType} level \"{((Object)level).name}\". A level already exists with the same name."); return; } RegisterLevelValuablePresets(level, levelType); LevelAmbiences.RegisterLevelAmbience(level); gameLevelList.Add(level); Logger.LogInfo($"Added {levelType} level \"{((Object)level).name}\"", extended: true); _levelsRegistered.Add(level); } } private static LevelType GetLevelType(Level level) { if (!_levelTypes.TryGetValue(level, out var value)) { return LevelType.Normal; } return value; } private static List<Level> GetGameLevelList(LevelType levelType) { RunManager instance = RunManager.instance; return levelType switch { LevelType.Shop => instance.levelShop, LevelType.Arena => instance.levelArena, _ => instance.levels, }; } private static void RegisterLevelValuablePresets(Level level, LevelType levelType) { if (level.ValuablePresets.Count == 0) { if (levelType != LevelType.Shop) { Logger.LogWarning("Level \"" + ((Object)level).name + "\" does not have any valuable presets! Adding generic preset."); level.ValuablePresets.Add(ValuablePresets.GenericValuablePreset); } return; } for (int i = 0; i < level.ValuablePresets.Count; i++) { LevelValuables val = level.ValuablePresets[i]; if (!ValuablePresets.AllValuablePresets.Values.Contains(val)) { if (ValuablePresets.AllValuablePresets.TryGetValue(((Object)val).name, out LevelValuables value)) { level.ValuablePresets[i] = value; Logger.LogInfo("Replaced proxy valuable preset \"" + ((Object)val).name + "\" in level \"" + ((Object)level).name + "\"", extended: true); } else { ValuablePresets.RegisterValuablePreset(val); Logger.LogInfo("Registered valuable preset \"" + ((Object)val).name + "\" from level \"" + ((Object)level).name + "\"", extended: true); } } } } public static void RegisterLevel(LevelContent? levelContent) { if ((Object)(object)levelContent == (Object)null) { Logger.LogError("Failed to register level. LevelContent is null."); return; } Level level = levelContent.Level; if ((Object)(object)level == (Object)null) { Logger.LogError("Failed to register level. Level is null."); return; } if (_levelsToRegister.Contains(level)) { Logger.LogWarning("Failed to register level \"" + ((Object)level).name + "\". Level is already registered!"); return; } if (_levelsToRegister.Any((Level x) => ((Object)x).name.Equals(((Object)level).name, StringComparison.OrdinalIgnoreCase))) { Logger.LogError("Failed to register level \"" + ((Object)level).name + "\". Level already exists with the same name."); return; } GameObject connectObject = levelContent.ConnectObject; if ((Object)(object)connectObject != (Object)null) { PrefabRef connectObject2 = RegisterLevelPrefab("Level/" + ((Object)level).name + "/Other/" + ((Object)connectObject).name, connectObject); level.ConnectObject = connectObject2; } GameObject blockObject = levelContent.BlockObject; if ((Object)(object)blockObject != (Object)null) { PrefabRef blockObject2 = RegisterLevelPrefab("Level/" + ((Object)level).name + "/Other/" + ((Object)blockObject).name, blockObject); level.BlockObject = blockObject2; } level.StartRooms = RegisterLevelModules(level, ModuleType.StartRoom, levelContent.StartRooms); level.ModulesNormal1 = RegisterLevelModules(level, ModuleType.Normal, levelContent.ModulesNormal1); level.ModulesPassage1 = RegisterLevelModules(level, ModuleType.Passage, levelContent.ModulesPassage1); level.ModulesDeadEnd1 = RegisterLevelModules(level, ModuleType.DeadEnd, levelContent.ModulesDeadEnd1); level.ModulesExtraction1 = RegisterLevelModules(level, ModuleType.Extraction, levelContent.ModulesExtraction1); level.ModulesMega1 = RegisterLevelModules(level, ModuleType.Mega, levelContent.ModulesMega1); level.ModulesNormal2 = RegisterLevelModules(level, ModuleType.Normal, levelContent.ModulesNormal2); level.ModulesPassage2 = RegisterLevelModules(level, ModuleType.Passage, levelContent.ModulesPassage2); level.ModulesDeadEnd2 = RegisterLevelModules(level, ModuleType.DeadEnd, levelContent.ModulesDeadEnd2); level.ModulesExtraction2 = RegisterLevelModules(level, ModuleType.Extraction, levelContent.ModulesExtraction2); level.ModulesMega2 = RegisterLevelModules(level, ModuleType.Mega, levelContent.ModulesMega2); level.ModulesNormal3 = RegisterLevelModules(level, ModuleType.Normal, levelContent.ModulesNormal3); level.ModulesPassage3 = RegisterLevelModules(level, ModuleType.Passage, levelContent.ModulesPassage3); level.ModulesDeadEnd3 = RegisterLevelModules(level, ModuleType.DeadEnd, levelContent.ModulesDeadEnd3); level.ModulesExtraction3 = RegisterLevelModules(level, ModuleType.Extraction, levelContent.ModulesExtraction3); level.ModulesMega3 = RegisterLevelModules(level, ModuleType.Mega, levelContent.ModulesMega3); level.ModulesSpecialAmount = levelContent.ModulesSpecialAmount; level.ModulesSpecial = RegisterLevelModules(level, ModuleType.Special, levelContent.ModulesSpecial); if (level.LoadingGraphic01.IsValid()) { PrefabRefResolver.Resolve(level.LoadingGraphic01, levelContent.Bundle); } if (level.LoadingGraphic02.IsValid()) { PrefabRefResolver.Resolve(level.LoadingGraphic02, levelContent.Bundle); } if (level.LoadingGraphic03.IsValid()) { PrefabRefResolver.Resolve(level.LoadingGraphic03, levelContent.Bundle); } _levelTypes[level] = levelContent.LevelType; _levelsToRegister.Add(level); if (_initialLevelsRegistered) { RegisterLevelWithGame(level); } } private static List<PrefabRef> RegisterLevelModules(Level level, ModuleType moduleType, List<GameObject> modules) { List<PrefabRef> list = new List<PrefabRef>(); foreach (GameObject module in modules) { string prefabId = $"Level/{((Object)level).name}/{moduleType}/{((Object)module).name}"; PrefabRef val = RegisterLevelPrefab(prefabId, module); if (val != null) { list.Add(val); } } return list; } private static PrefabRef? RegisterLevelPrefab(string prefabId, GameObject prefab) { PrefabRefResponse prefabRefResponse = NetworkPrefabs.RegisterNetworkPrefabInternal(prefabId, prefab); if (prefabRefResponse.Result == PrefabRefResult.Success) { Utilities.FixAudioMixerGroups(prefab); return prefabRefResponse.PrefabRef; } if (prefabRefResponse.Result == PrefabRefResult.PrefabAlreadyRegistered) { return prefabRefResponse.PrefabRef; } if (prefabRefResponse.Result == PrefabRefResult.DifferentPrefabAlreadyRegistered) { Logger.LogError("Failed to register level network prefab \"" + prefabId + "\". A prefab is already registered with the same prefab ID."); return null; } Logger.LogError($"Failed to register level network prefab \"{prefabId}\". (Reason: {prefabRefResponse.Result})"); return null; } [Obsolete("This is no longer supported. Use AllLevels or RegisteredLevels instead.", true)] public static IReadOnlyList<Level> GetLevels() { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return AllLevels; } [Obsolete("This is no longer supported. Use AllLevels or RegisteredLevels instead.", true)] public static bool TryGetLevelByName(string name, [NotNullWhen(true)] out Level? level) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); level = null; return false; } [Obsolete("This is no longer supported. Use AllLevels or RegisteredLevels instead.", true)] public static Level? GetLevelByName(string name) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return null; } [Obsolete("This is no longer supported. Use AllLevels or RegisteredLevels instead.", true)] public static bool TryGetLevelThatContainsName(string name, [NotNullWhen(true)] out Level? level) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); level = null; return false; } [Obsolete("This is no longer supported. Use AllLevels or RegisteredLevels instead.", true)] public static Level? GetLevelThatContainsName(string name) { Logger.LogError("This method is deprecated! " + Utilities.GetStackTrace()); return null; } } public static class Localization { private class LocalizationProvider : ResourceProviderBase { private readonly Dictionary<string, Object> _objects = new Dictionary<string, Object>(); public IResourceLocation CreateLocation(Object obj, Type type) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown string text = string.Format("{0}/{1}", "REPOLib.Localization", obj.GetInstanceID()); _objects[text] = obj; return (IResourceLocation)new ResourceLocationBase(obj.name, text, ((ResourceProviderBase)this).ProviderId, type, Array.Empty<IResourceLocation>()); } public void Clear() { _objects.Clear(); } public override void Provide(ProvideHandle provideHandle) { if (_objects.TryGetValue(((ProvideHandle)(ref provideHandle)).Location.InternalId, out Object value) && value != (Object)null) { ((ProvideHandle)(ref provideHandle)).Complete<Object>(value, true, (Exception)null); } else { ((ProvideHandle)(ref provideHandle)).Complete<Object>((Object)null, false, new Exception("REPOLib has no localization asset for " + ((ProvideHandle)(ref provideHandle)).Location.InternalId)); } } } private const string LocatorId = "REPOLib.Localization"; private static readonly List<StringTable> _stringTables = new List<StringTable>(); private static readonly HashSet<LocalizedAsset> _checkedLocalizedAssets = new HashSet<LocalizedAsset>(); private static readonly LocalizationProvider _provider = new LocalizationProvider(); private static ResourceLocationMap? _locator; private static bool _rebuildQueued; private static Dictionary<string, (Guid TableGuid, string TableName, long KeyId)>? _gameKeys; public static IReadOnlyList<StringTable> RegisteredStringTables => _stringTables; public static void RegisterStringTable(StringTable stringTable) { //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) if ((Object)(object)stringTable == (Object)null) { Logger.LogError("Failed to register string table. StringTable is null."); } else if ((Object)(object)((LocalizationTable)stringTable).SharedData == (Object)null) { Logger.LogError("Failed to register string table \"" + ((Object)stringTable).name + "\". It has no SharedTableData."); } else if (!_stringTables.Contains(stringTable)) { string collectionName = ((LocalizationTable)stringTable).TableCollectionName; string collectionName2 = collectionName; LocaleIdentifier localeIdentifier = ((LocalizationTable)stringTable).LocaleIdentifier; string tableAddress = GetTableAddress(collectionName2, ((LocaleIdentifier)(ref localeIdentifier)).Code); if (IsProvidedByGame(tableAddress) || IsProvidedByGame(GuidKey(((LocalizationTable)stringTable).SharedData))) { Logger.LogError("Failed to register string table \"" + ((Object)stringTable).name + "\". A table collection named \"" + collectionName + "\" already exists in the game. Use a unique name for your table collection."); } else if (_stringTables.Any((StringTable x) => (Object)(object)((LocalizationTable)x).SharedData != (Object)(object)((LocalizationTable)stringTable).SharedData && ((LocalizationTable)x).TableCollectionName == collectionName)) { Logger.LogError("Failed to register string table \"" + ((Object)stringTable).name + "\". A table collection named \"" + collectionName + "\" was already registered by another mod."); } else { _stringTables.Add(stringTable); QueueRebuild(); Logger.LogDebug("Registered string table \"" + ((Object)stringTable).name + "\"", extended: true); } } } internal static IEnumerator RegisterBundleStringTables(AssetBundle bundle) { if (bundle.isStreamedSceneAssetBundle) { yield break; } AssetBundleRequest request = bundle.LoadAllAssetsAsync<StringTable>(); yield return request; foreach (StringTable item in request.allAssets.OfType<StringTable>()) { RegisterStringTable(item); } } internal static IEnumerator FixLocalizedAssets() { List<LocalizedAsset> list = (from x in Resources.FindObjectsOfTypeAll<LocalizedAsset>() where (Object)(object)x != (Object)null && !_checkedLocalizedAssets.Contains(x) select x).ToList(); _checkedLocalizedAssets.UnionWith(list); List<LocalizedAsset> invalid = list.Where((LocalizedAsset x) => !x.IsValid()).ToList(); if (invalid.Count == 0) { yield break; } if (_gameKeys == null) { yield return LoadGameKeys(); } foreach (LocalizedAsset item in invalid) { string entryKey = GetEntryKey(((Object)item).name); if (_gameKeys != null && _gameKeys.Tr