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 Hard Item Randomizer v1.11.25
BepInEx/plugins/AssetChainFixer.dll
Decompiled a week agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Logging; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.ResourceManagement.ResourceProviders; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("0.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 AssetChainFixer { [BepInPlugin("com.assetchain.fixer", "AssetChainFixer", "1.0.0")] public class Plugin : BaseUnityPlugin { internal static ModLog Log = ModLog.For("AssetChainFixer"); internal static Plugin Instance; internal static bool ManualPlayEnabled = true; private void Awake() { Instance = this; ModLog.SetFallback(((BaseUnityPlugin)this).Logger); Log.LogInfo("[AssetChainFixer] 已加载。"); } private void OnDestroy() { ModLog.Shutdown(); } private void Update() { if (Input_GetKeyDown_F5()) { ChainFixer.RunDemoSpawn(); } if (Input_GetKeyDown_F6()) { ManualPlayEnabled = !ManualPlayEnabled; } } private static bool Input_GetKeyDown_F5() { return Input.GetKeyDown((KeyCode)286); } private static bool Input_GetKeyDown_F6() { return Input.GetKeyDown((KeyCode)287); } } public static class ChainFixer { public enum BundleType { Unknown, Normal, StreamedScene } private static readonly Regex BundleSuffixRegex = new Regex("_[0-9a-fA-F]{32}\\.bundle+$", RegexOptions.Compiled); private static Dictionary<string, string> _bundleKeys; private static Dictionary<string, GameObject> _prefabCache = new Dictionary<string, GameObject>(StringComparer.Ordinal); private static tk2dSpriteCollectionData _cachedCoinRocksCollection; private static bool _coinRocksLoadAttempted; private static Dictionary<string, Sprite> _spriteCache; public static void EnsureBundleKeyMap() { if (_bundleKeys != null) { return; } Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); try { foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key2 in resourceLocator.Keys) { if (key2 is string text && BundleSuffixRegex.Match(text).Success) { string key = BundleSuffixRegex.Replace(text, ""); dictionary[key] = text; } } } } catch (Exception ex) { Plugin.Log?.LogWarning("[ChainFixer] 构建 bundle key 映射异常: " + ex.Message); } _bundleKeys = ((dictionary.Count > 0) ? dictionary : null); Plugin.Log?.LogInfo($"[ChainFixer] bundle key 映射: {dictionary.Count} 个"); } public static string ToBundleKey(string name) { EnsureBundleKeyMap(); if (_bundleKeys == null) { Plugin.Log?.LogWarning("[ChainFixer] bundle key 映射未就绪(Addressables 未加载 catalog)"); return name; } if (BundleSuffixRegex.IsMatch(name)) { name = BundleSuffixRegex.Replace(name, ""); } else if (name.EndsWith(".bundle", StringComparison.OrdinalIgnoreCase)) { name = name.Substring(0, name.Length - 7); } if (_bundleKeys.TryGetValue(name, out var value)) { return value; } throw new Exception("Bundle " + name + " not found in lookup."); } public static List<string> FindKeysContaining(string fragment, string logTag = "ChainFixer") { List<string> list = new List<string>(); try { foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text && text.IndexOf(fragment, StringComparison.OrdinalIgnoreCase) >= 0) { list.Add(text); Plugin.Log?.LogInfo("[" + logTag + "] key 匹配 '" + fragment + "': " + text); } } } Plugin.Log?.LogInfo($"[{logTag}] 匹配 '{fragment}' 共 {list.Count} 个"); } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] 遍历 key 异常: " + ex.Message); } return list; } public static T LoadNativeDataSet<T>(string keyFragment, string assetPath, string logTag = "ChainFixer") where T : Object { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Invalid comparison between Unknown and I4 List<string> list = FindKeysContaining(keyFragment, logTag); if (list.Count == 0) { Plugin.Log?.LogWarning("[" + logTag + "] 未找到含 '" + keyFragment + "' 的数据集 key"); return default(T); } string text = list[0]; AssetBundle val = null; try { AsyncOperationHandle<IAssetBundleResource> val2 = default(AsyncOperationHandle<IAssetBundleResource>); val2 = Addressables.LoadAssetAsync<IAssetBundleResource>((object)text); val2.WaitForCompletion(); if ((int)val2.Status != 1 || val2.Result == null) { Plugin.Log?.LogWarning($"[{logTag}] 数据集加载失败: {text} → {val2.OperationException}"); return default(T); } val = val2.Result.GetAssetBundle(); } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] 数据集加载异常 " + text + ": " + ex.Message); return default(T); } if ((Object)(object)val == (Object)null) { return default(T); } T val3 = val.LoadAsset<T>(assetPath); if ((Object)(object)val3 == (Object)null) { val3 = val.LoadAllAssets<T>().FirstOrDefault(); } if ((Object)(object)val3 != (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] 数据集命中: key=" + text + " asset=" + assetPath + " → " + ((Object)val3).name); } else { Plugin.Log?.LogWarning("[" + logTag + "] 数据集未命中: key=" + text + " asset=" + assetPath); } return val3; } public static SavedItem LoadDataSavedItem(string keyFragment, string assetName, string logTag = "ChainFixer") { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 List<string> list = FindKeysContaining(keyFragment, logTag); if (list.Count == 0) { return null; } string text = list[0]; try { AsyncOperationHandle<IAssetBundleResource> val = default(AsyncOperationHandle<IAssetBundleResource>); val = Addressables.LoadAssetAsync<IAssetBundleResource>((object)text); val.WaitForCompletion(); if ((int)val.Status != 1 || val.Result == null) { return null; } AssetBundle assetBundle = val.Result.GetAssetBundle(); if ((Object)(object)assetBundle == (Object)null) { return null; } SavedItem val2 = assetBundle.LoadAsset<SavedItem>(assetName); if ((Object)(object)val2 != (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] 数据集命中 SavedItem '" + assetName + "' @ " + text); return val2; } GameObject val3 = assetBundle.LoadAsset<GameObject>(assetName); if ((Object)(object)val3 != (Object)null) { SavedItem component = val3.GetComponent<SavedItem>(); if ((Object)(object)component != (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] 数据集命中 GameObject→SavedItem '" + assetName + "' @ " + text); return component; } PrefabCollectable component2 = val3.GetComponent<PrefabCollectable>(); if ((Object)(object)component2 != (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] 数据集命中 GameObject→PrefabCollectable '" + assetName + "' @ " + text); return (SavedItem)(object)component2; } } Plugin.Log?.LogWarning("[" + logTag + "] 数据集未找到 '" + assetName + "' @ " + text); } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] 数据集加载异常 " + text + ": " + ex.Message); } return null; } public static AssetBundle LoadBundleWithDeps(string bundleName, string logTag = "ChainFixer") { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 string text; try { text = ToBundleKey(bundleName); } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] bundle key 映射未命中 " + bundleName + ",尝试直接 key 加载: " + ex.Message); text = bundleName; } Plugin.Log?.LogInfo("[" + logTag + "] Addressables 加载 " + bundleName + " → key=" + text); AsyncOperationHandle<IAssetBundleResource> val = default(AsyncOperationHandle<IAssetBundleResource>); try { val = Addressables.LoadAssetAsync<IAssetBundleResource>((object)text); val.WaitForCompletion(); if ((int)val.Status != 1 || val.Result == null) { Plugin.Log?.LogWarning($"[{logTag}] Addressables 加载失败: {val.OperationException}"); return null; } AssetBundle assetBundle = val.Result.GetAssetBundle(); Plugin.Log?.LogInfo("[" + logTag + "] bundle 依赖链加载成功: " + ((Object)assetBundle).name); return assetBundle; } catch (Exception ex2) { Plugin.Log?.LogWarning("[" + logTag + "] Addressables 加载异常 " + bundleName + ": " + ex2.Message); return null; } } public static List<RuntimeAnimatorController> WarmupBundle(AssetBundle bundle, string logTag = "ChainFixer") { List<RuntimeAnimatorController> list = new List<RuntimeAnimatorController>(); int num = 0; int num2 = 0; int num3 = 0; try { Object[] array = bundle.LoadAllAssets(); foreach (Object val in array) { if (val == (Object)null) { continue; } num3++; if (val is Sprite) { num++; continue; } RuntimeAnimatorController val2 = (RuntimeAnimatorController)(object)((val is RuntimeAnimatorController) ? val : null); if (val2 != null) { list.Add(val2); } else if (val is AnimationClip) { num2++; } } } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] 预热异常: " + ex.Message); } Plugin.Log?.LogInfo($"[{logTag}] 预热(全量): total={num3} sprites={num} controllers={list.Count} clips={num2}"); return list; } public static int FixAnimatorControllers(GameObject root, List<RuntimeAnimatorController> loadedCtrls, string logTag = "ChainFixer") { if (loadedCtrls == null || loadedCtrls.Count == 0) { return 0; } Dictionary<string, RuntimeAnimatorController> dictionary = new Dictionary<string, RuntimeAnimatorController>(StringComparer.OrdinalIgnoreCase); foreach (RuntimeAnimatorController loadedCtrl in loadedCtrls) { if (!dictionary.ContainsKey(((Object)loadedCtrl).name)) { dictionary[((Object)loadedCtrl).name] = loadedCtrl; } } int num = 0; Animator[] componentsInChildren = root.GetComponentsInChildren<Animator>(true); foreach (Animator val in componentsInChildren) { if (!((Object)(object)val == (Object)null) && val.layerCount <= 0) { string text = (((Object)(object)val.runtimeAnimatorController != (Object)null) ? ((Object)val.runtimeAnimatorController).name : ((Object)((Component)val).gameObject).name); if (!string.IsNullOrEmpty(text) && dictionary.TryGetValue(text, out var value)) { val.runtimeAnimatorController = value; num++; Plugin.Log?.LogInfo($"[{logTag}] 回填 Controller: {text} → {((Object)((Component)val).gameObject).name}, Layers={val.layerCount}"); } } } return num; } public static GameObject SpawnWithFullChain(string bundleName, string prefabPath, Transform parent, string logTag = "ChainFixer") { AssetBundle val = LoadBundleWithDeps(bundleName, logTag); if ((Object)(object)val == (Object)null) { return null; } List<RuntimeAnimatorController> loadedCtrls = WarmupBundle(val, logTag); GameObject val2 = val.LoadAsset<GameObject>(prefabPath); if ((Object)(object)val2 == (Object)null) { Plugin.Log?.LogWarning("[" + logTag + "] prefab 加载失败: " + prefabPath); return null; } Plugin.Log?.LogInfo("[" + logTag + "] prefab 加载成功: " + ((Object)val2).name); GameObject val3 = Object.Instantiate<GameObject>(val2); if ((Object)(object)parent != (Object)null) { val3.transform.SetParent(parent, false); } val3.SetActive(false); FixAnimatorControllers(val3, loadedCtrls, logTag); return val3; } public static void DumpSceneExtractDiagnostics(string sceneAddress, string sceneBundleKey, Func<GameObject, bool> matcher, string logTag = "ChainFixer") { //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_0330: Unknown result type (might be due to invalid IL or missing references) //IL_035c: Unknown result type (might be due to invalid IL or missing references) //IL_039e: Unknown result type (might be due to invalid IL or missing references) //IL_03a4: Invalid comparison between Unknown and I4 //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) try { Plugin.Log?.LogInfo("[" + logTag + "] ===== F4 场景提取诊断开始 ====="); Plugin.Log?.LogInfo("[" + logTag + "] 目标场景 address: '" + sceneAddress + "',目标 bundle key: '" + sceneBundleKey + "'"); Plugin.Log?.LogInfo("[" + logTag + "] --- 1. 遍历全部 locator keys ---"); int num = 0; List<string> list = new List<string>(); List<string> list2 = new List<string>(); foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text) { num++; if (text.IndexOf("aspid", StringComparison.OrdinalIgnoreCase) >= 0) { list.Add(text); } if (text.StartsWith("Scenes/", StringComparison.OrdinalIgnoreCase)) { list2.Add(text); } } } } Plugin.Log?.LogInfo($"[{logTag}] locator 总 key 数: {num}"); Plugin.Log?.LogInfo(string.Format("[{0}] 含 'aspid' 的 key ({1}): {2}", logTag, list.Count, string.Join(" | ", list))); Plugin.Log?.LogInfo(string.Format("[{0}] 以 'Scenes/' 开头的 key ({1}): {2}", logTag, list2.Count, string.Join(" | ", list2.Take(50)))); Plugin.Log?.LogInfo("[" + logTag + "] --- 2. LoadResourceLocations 定位场景 " + sceneAddress + " ---"); try { AsyncOperationHandle<IList<IResourceLocation>> val = Addressables.LoadResourceLocationsAsync((object)sceneAddress, typeof(Scene)); val.WaitForCompletion(); Plugin.Log?.LogInfo(string.Format("[{0}] LoadResourceLocations(Scene) Status={1} Result={2} loc", logTag, val.Status, (val.Result == null) ? "null" : val.Result.Count.ToString())); if (val.Result != null) { foreach (IResourceLocation item in val.Result) { Plugin.Log?.LogInfo($"[{logTag}] Scene location: InternalId='{item.InternalId}' PrimaryKey='{item.PrimaryKey}' ResourceType={item.ResourceType} Data={item.Data}"); } } } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] LoadResourceLocations(Scene) 异常: " + ex.Message); } Plugin.Log?.LogInfo("[" + logTag + "] --- 3. 尝试用场景 address 加载 bundle (IAssetBundleResource) ---"); try { AsyncOperationHandle<IAssetBundleResource> val2 = Addressables.LoadAssetAsync<IAssetBundleResource>((object)sceneAddress); val2.WaitForCompletion(); ModLog log = Plugin.Log; if (log != null) { object[] obj = new object[4] { logTag, sceneAddress, val2.Status, null }; object obj2; if (val2.Result != null) { AssetBundle assetBundle = val2.Result.GetAssetBundle(); obj2 = ((assetBundle != null) ? ((Object)assetBundle).name : null); } else { obj2 = "Result=null"; } obj[3] = obj2; log.LogInfo(string.Format("[{0}] LoadAssetAsync<IAssetBundleResource>('{1}') Status={2} {3}", obj)); } if ((int)val2.Status == 1 && val2.Result != null) { AssetBundle assetBundle2 = val2.Result.GetAssetBundle(); if ((Object)(object)assetBundle2 != (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] bundle 名: '" + ((Object)assetBundle2).name + "'"); DumpBundleAssets(assetBundle2, matcher, logTag); } } } catch (Exception ex2) { Plugin.Log?.LogWarning("[" + logTag + "] 场景 address 加载 bundle 异常: " + ex2.Message); } Plugin.Log?.LogInfo("[" + logTag + "] --- 4. 尝试直接 LoadBundleWithDeps ---"); AssetBundle val3 = LoadBundleWithDeps(sceneBundleKey, logTag); if ((Object)(object)val3 != (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] LoadBundleWithDeps 成功: '" + ((Object)val3).name + "'"); DumpBundleAssets(val3, matcher, logTag); } else { Plugin.Log?.LogWarning("[" + logTag + "] LoadBundleWithDeps 失败 (返回 null)"); } Plugin.Log?.LogInfo("[" + logTag + "] --- 5. 尝试 AssetBundle.LoadFromFile 直接读磁盘 ---"); try { string text2 = Application.streamingAssetsPath + "/aa/StandaloneWindows64"; string[] array = new string[3] { text2 + "/scenes_scenes_scenes/aspid_01.bundle", text2 + "/" + sceneBundleKey, text2 + "/aspid_01.bundle" }; foreach (string text3 in array) { Plugin.Log?.LogInfo($"[{logTag}] 检查磁盘路径: {text3} exists={File.Exists(text3)}"); if (File.Exists(text3)) { AssetBundle val4 = AssetBundle.LoadFromFile(text3); Plugin.Log?.LogInfo("[" + logTag + "] LoadFromFile 结果: " + (((Object)(object)val4 == (Object)null) ? "null" : ((Object)val4).name)); if ((Object)(object)val4 != (Object)null) { DumpBundleAssets(val4, matcher, logTag); val4.Unload(false); } } } } catch (Exception ex3) { Plugin.Log?.LogWarning("[" + logTag + "] LoadFromFile 异常: " + ex3.Message); } Plugin.Log?.LogInfo("[" + logTag + "] ===== F4 场景提取诊断结束 ====="); } catch (Exception arg) { Plugin.Log?.LogError($"[{logTag}] DumpSceneExtractDiagnostics 异常: {arg}"); } } private static void DumpBundleAssets(AssetBundle bundle, Func<GameObject, bool> matcher, string logTag) { try { Object[] array = bundle.LoadAllAssets(); Plugin.Log?.LogInfo($"[{logTag}] bundle '{((Object)bundle).name}' LoadAllAssets 总数: {array.Length}"); int num = 0; int num2 = 0; List<GameObject> list = new List<GameObject>(); Object[] array2 = array; foreach (Object val in array2) { if (!(val == (Object)null)) { GameObject val2 = (GameObject)(object)((val is GameObject) ? val : null); if (val2 != null) { num++; list.Add(val2); } else { num2++; } } } Plugin.Log?.LogInfo($"[{logTag}] GameObject 资产: {num} 个,其他资产: {num2} 个"); foreach (GameObject item in list.Take(80)) { bool flag = false; try { flag = matcher(item); } catch { } if (flag) { Plugin.Log?.LogInfo("[" + logTag + "] ★命中★ GameObject: '" + ((Object)item).name + "' components=" + string.Join(",", Array.ConvertAll(item.GetComponents<Component>(), (Component c) => ((object)c).GetType().Name))); } else { Plugin.Log?.LogInfo($"[{logTag}] GameObject: '{((Object)item).name}' hit={flag}"); } } } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] DumpBundleAssets 异常: " + ex.Message); } } public static GameObject ExtractSceneObjectAsTemplate(string bundleName, Func<GameObject, bool> matcher, string logTag = "ChainFixer") { //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Invalid comparison between Unknown and I4 try { Plugin.Log?.LogInfo("[" + logTag + "] 从 bundle " + bundleName + " 提取模板"); AssetBundle val = null; string text = bundleName; int num = text.LastIndexOf('/'); if (num >= 0) { text = text.Substring(num + 1); } string text2 = Regex.Replace(text, "_[0-9a-fA-F]{32}\\.bundle$", ".bundle"); Plugin.Log?.LogInfo("[" + logTag + "] 遍历已加载 bundle,匹配名: '" + text2 + "' (来源 '" + bundleName + "')"); foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if (!((Object)(object)allLoadedAssetBundle == (Object)null)) { bool flag = ((Object)allLoadedAssetBundle).name == text2 || ((Object)allLoadedAssetBundle).name.EndsWith("/" + text2, StringComparison.OrdinalIgnoreCase) || ((Object)allLoadedAssetBundle).name.IndexOf(text2, StringComparison.OrdinalIgnoreCase) >= 0; Plugin.Log?.LogInfo($"[{logTag}] 已加载 bundle: '{((Object)allLoadedAssetBundle).name}' nameMatch={flag}"); if (flag) { val = allLoadedAssetBundle; break; } } } if ((Object)(object)val == (Object)null && (bundleName.IndexOf("/", StringComparison.Ordinal) >= 0 || bundleName.StartsWith("Scenes", StringComparison.OrdinalIgnoreCase))) { Plugin.Log?.LogInfo("[" + logTag + "] 参数为场景 address,尝试 LoadAssetAsync<IAssetBundleResource> 直接取场景 bundle"); try { AsyncOperationHandle<IAssetBundleResource> val2 = Addressables.LoadAssetAsync<IAssetBundleResource>((object)bundleName); val2.WaitForCompletion(); Plugin.Log?.LogInfo($"[{logTag}] LoadAssetAsync<IAssetBundleResource> Status={val2.Status}"); if ((int)val2.Status == 1 && val2.Result != null) { val = val2.Result.GetAssetBundle(); } } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] 场景 address 加载 bundle 异常: " + ex.Message); } } if ((Object)(object)val == (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] 尝试 LoadBundleWithDeps 加载"); val = LoadBundleWithDeps(bundleName, logTag); } if ((Object)(object)val == (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] 尝试 AssetBundle.LoadFromFile 磁盘直读"); try { string text3 = Application.streamingAssetsPath + "/aa/StandaloneWindows64"; string text4 = text2.Replace(".bundle", "_3f5daa59bb73e1ff0f6bb2d9a0e72e54.bundle"); string[] array = new string[3] { text3 + "/scenes_scenes_scenes/" + text2, text3 + "/scenes_scenes_scenes/" + text4, text3 + "/" + text2 }; foreach (string text5 in array) { if (File.Exists(text5)) { Plugin.Log?.LogInfo("[" + logTag + "] LoadFromFile: " + text5); AssetBundle val3 = AssetBundle.LoadFromFile(text5); if ((Object)(object)val3 != (Object)null) { val = val3; break; } } } } catch (Exception ex2) { Plugin.Log?.LogWarning("[" + logTag + "] LoadFromFile 异常: " + ex2.Message); } } if ((Object)(object)val == (Object)null) { Plugin.Log?.LogWarning("[" + logTag + "] bundle 加载失败: " + bundleName); return null; } GameObject val4 = null; GameObject[] array2 = val.LoadAllAssets<GameObject>(); Plugin.Log?.LogInfo($"[{logTag}] bundle 内 GameObject 资产数: {array2.Length}"); GameObject[] array3 = array2; foreach (GameObject val5 in array3) { if (!((Object)(object)val5 == (Object)null) && matcher(val5)) { val4 = val5; break; } } if ((Object)(object)val4 == (Object)null) { Plugin.Log?.LogWarning($"[{logTag}] bundle {bundleName} 中未找到匹配对象 (GameObject资产={array2.Length})"); return null; } GameObject val6 = Object.Instantiate<GameObject>(val4); ((Object)val6).name = ((Object)val4).name + " [Template]"; Object.DontDestroyOnLoad((Object)(object)val6); Plugin.Log?.LogInfo("[" + logTag + "] 模板提取成功: " + ((Object)val6).name + "(源自 bundle " + bundleName + ",未加载场景)"); return val6; } catch (Exception arg) { Plugin.Log?.LogError($"[{logTag}] ExtractSceneObjectAsTemplate 异常: {arg}"); return null; } } public static GameObject LoadPrefabFixed(string bundleName, string prefabPath, string logTag = "ChainFixer") { string key = bundleName + "|" + prefabPath; if (_prefabCache.TryGetValue(key, out var value) && (Object)(object)value != (Object)null) { Plugin.Log?.LogInfo("[" + logTag + "] prefab 缓存命中: " + prefabPath); return value; } AssetBundle val = LoadBundleWithDeps(bundleName, logTag); if ((Object)(object)val == (Object)null) { return null; } List<RuntimeAnimatorController> loadedCtrls = WarmupBundle(val, logTag); GameObject val2 = val.LoadAsset<GameObject>(prefabPath); if ((Object)(object)val2 == (Object)null) { Plugin.Log?.LogWarning("[" + logTag + "] prefab 加载失败: " + prefabPath); return null; } Plugin.Log?.LogInfo("[" + logTag + "] prefab 加载成功: " + ((Object)val2).name); FixAnimatorControllers(val2, loadedCtrls, logTag); _prefabCache[key] = val2; return val2; } public static string ReportSpriteState(GameObject root) { StringBuilder stringBuilder = new StringBuilder(); SpriteRenderer[] componentsInChildren = root.GetComponentsInChildren<SpriteRenderer>(true); foreach (SpriteRenderer val in componentsInChildren) { string text = (((Object)(object)val.sprite != (Object)null) ? ((Object)val.sprite).name : "null"); string text2 = ""; if ((Object)(object)val.sprite != (Object)null) { text2 = (((Object)(object)val.sprite.texture != (Object)null) ? ((Object)val.sprite.texture).name : "noTex"); text2 += (((Object)(object)val.sprite.texture != (Object)null) ? $"({((Texture)val.sprite.texture).width}x{((Texture)val.sprite.texture).height})" : ""); } stringBuilder.AppendLine(" SpriteRenderer '" + ((Object)((Component)val).gameObject).name + "': sprite=" + text + " texture=" + text2); } return stringBuilder.ToString(); } public static tk2dSpriteCollectionData FindSpriteCollection(string collectionName, string logTag = "ChainFixer") { tk2dSpriteCollectionData[] array = Resources.FindObjectsOfTypeAll<tk2dSpriteCollectionData>(); foreach (tk2dSpriteCollectionData val in array) { if ((Object)(object)val != (Object)null && ((Object)val).name == collectionName) { Plugin.Log?.LogInfo($"[{logTag}] 找到 sprite collection: '{collectionName}' sprites={val.Count}"); return val; } } Plugin.Log?.LogWarning("[" + logTag + "] 未找到 sprite collection: '" + collectionName + "'"); return null; } public static BundleType DetectBundleType(AssetBundle bundle, string logTag = "ChainFixer") { if ((Object)(object)bundle == (Object)null) { return BundleType.Unknown; } try { int num = bundle.LoadAllAssets().Length; Plugin.Log?.LogInfo($"[{logTag}] bundle '{((Object)bundle).name}' 是普通 bundle,LoadAllAssets={num} 个资产"); return BundleType.Normal; } catch (InvalidOperationException) { Plugin.Log?.LogInfo("[" + logTag + "] bundle '" + ((Object)bundle).name + "' 是 streamed scene bundle(LoadAllAssets 抛异常)"); return BundleType.StreamedScene; } catch (Exception ex2) { Plugin.Log?.LogWarning("[" + logTag + "] bundle '" + ((Object)bundle).name + "' 类型检测异常: " + ex2.Message); return BundleType.Unknown; } } public static GameObject ExtractFromSceneBundle(string bundleName, Func<GameObject, bool> matcher, string logTag = "ChainFixer") { //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Invalid comparison between Unknown and I4 //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_054d: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_056b: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_040a: Unknown result type (might be due to invalid IL or missing references) //IL_052c: Unknown result type (might be due to invalid IL or missing references) //IL_052f: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) Plugin.Log?.LogInfo("[" + logTag + "] 从 streamed scene bundle 提取对象: " + bundleName); string text = ExtractSceneNameFromBundle(bundleName); Plugin.Log?.LogInfo("[" + logTag + "] 推断场景名: '" + text + "'"); List<string> list = new List<string>(); foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text2 && text2.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0) { list.Add(text2); } } } Plugin.Log?.LogInfo(string.Format("[{0}] locator 中匹配的 key ({1}): {2}", logTag, list.Count, string.Join(" | ", list.Take(20)))); foreach (string item in list) { Plugin.Log?.LogInfo("[" + logTag + "] 尝试 LoadResourceLocations: '" + item + "'"); try { AsyncOperationHandle<IList<IResourceLocation>> val = Addressables.LoadResourceLocationsAsync((object)item, typeof(SceneInstance)); val.WaitForCompletion(); if (val.Result != null && val.Result.Count > 0) { Plugin.Log?.LogInfo($"[{logTag}] LoadResourceLocations 命中 {val.Result.Count} 个"); foreach (IResourceLocation item2 in val.Result) { Plugin.Log?.LogInfo("[" + logTag + "] location: InternalId='" + item2.InternalId + "' PrimaryKey='" + item2.PrimaryKey + "'"); } AsyncOperationHandle<SceneInstance> val2 = Addressables.LoadSceneAsync((object)item, (LoadSceneMode)1, true, 100, (SceneReleaseMode)0); try { val2.WaitForCompletion(); } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] WaitForCompletion 异常: " + ex.Message); } if ((int)val2.Status == 1) { SceneInstance result = val2.Result; Scene scene = ((SceneInstance)(ref result)).Scene; Plugin.Log?.LogInfo($"[{logTag}] 场景加载成功: '{((Scene)(ref scene)).name}' rootObjects={((Scene)(ref scene)).rootCount}"); GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects(); int num = 0; GameObject val3 = null; GameObject[] array = rootGameObjects; for (int i = 0; i < array.Length; i++) { Transform[] componentsInChildren = array[i].GetComponentsInChildren<Transform>(true); foreach (Transform val4 in componentsInChildren) { num++; if (((Component)val4).gameObject.activeSelf || ((Component)val4).gameObject.activeInHierarchy) { bool flag = false; try { flag = matcher(((Component)val4).gameObject); } catch { } if (flag) { val3 = ((Component)val4).gameObject; break; } } } if ((Object)(object)val3 != (Object)null) { break; } } Plugin.Log?.LogInfo($"[{logTag}] 场景内扫描: {num} 个活跃对象, 命中={(Object)(object)val3 != (Object)null}"); if ((Object)(object)val3 != (Object)null) { GameObject val5 = Object.Instantiate<GameObject>(val3); ((Object)val5).name = ((Object)val3).name + " [Extracted]"; Object.DontDestroyOnLoad((Object)(object)val5); Plugin.Log?.LogInfo("[" + logTag + "] ★ 模板提取成功: " + ((Object)val5).name); try { Addressables.UnloadSceneAsync(val2, true); Plugin.Log?.LogInfo("[" + logTag + "] 场景已卸载"); } catch (Exception ex2) { Plugin.Log.LogWarning("[" + logTag + "] 场景卸载异常: " + ex2.Message); } return val5; } Plugin.Log?.LogInfo("[" + logTag + "] 未命中,打印场景对象:"); array = rootGameObjects; for (int i = 0; i < array.Length; i++) { Component[] componentsInChildren2 = array[i].GetComponentsInChildren<Component>(true); foreach (Component val6 in componentsInChildren2) { if (!(val6 is Transform) && !(val6 is MeshFilter)) { Plugin.Log?.LogInfo("[" + logTag + "] '" + ((Object)val6.gameObject).name + "' → " + ((object)val6).GetType().Name); } } } try { Addressables.UnloadSceneAsync(val2, true); } catch { } continue; } Plugin.Log?.LogWarning($"[{logTag}] 场景加载失败: Status={val2.Status}"); try { if (val2.IsValid()) { Addressables.Release<SceneInstance>(val2); } } catch { } } else { Plugin.Log?.LogInfo("[" + logTag + "] LoadResourceLocations 无结果"); } } catch (Exception ex3) { Plugin.Log.LogWarning("[" + logTag + "] key '" + item + "' 加载异常: " + ex3.Message); } } Plugin.Log?.LogWarning("[" + logTag + "] 所有 key 尝试完毕,未成功提取"); return null; } private static string ExtractSceneNameFromBundle(string bundleName) { string text = bundleName; int num = text.LastIndexOf('/'); if (num >= 0) { text = text.Substring(num + 1); } text = BundleSuffixRegex.Replace(text, ""); if (text.EndsWith(".bundle", StringComparison.OrdinalIgnoreCase)) { text = text.Substring(0, text.Length - 7); } int num2 = text.IndexOf('_'); if (num2 > 0) { text = text.Substring(num2 + 1); } int num3 = text.LastIndexOf('_'); if (num3 > 0 && text.Length - num3 == 33) { text = text.Substring(0, num3); } return text; } public static List<Object> ProbeBundleAssets(AssetBundle bundle, Func<Object, bool> matcher = null, string logTag = "ChainFixer") { List<Object> list = new List<Object>(); if ((Object)(object)bundle == (Object)null) { return list; } switch (DetectBundleType(bundle, logTag)) { case BundleType.Normal: { Object[] array = bundle.LoadAllAssets(); Plugin.Log?.LogInfo($"[{logTag}] 普通 bundle '{((Object)bundle).name}' 全量资产: {array.Length}"); Object[] array2 = array; foreach (Object val in array2) { if (val == (Object)null) { continue; } bool flag = matcher?.Invoke(val) ?? false; if (flag) { list.Add(val); } GameObject val2 = (GameObject)(object)((val is GameObject) ? val : null); if (val2 != null) { Plugin.Log?.LogInfo(string.Format("[{0}] GO: '{1}' components=[{2}] hit={3}", logTag, ((Object)val2).name, string.Join(",", Array.ConvertAll(val2.GetComponents<Component>(), (Component c) => ((object)c)?.GetType().Name ?? "?")), flag)); } else { Plugin.Log?.LogInfo($"[{logTag}] Asset: '{val.name}' type={((object)val).GetType().Name} hit={flag}"); } } break; } case BundleType.StreamedScene: Plugin.Log?.LogInfo("[" + logTag + "] streamed scene bundle '" + ((Object)bundle).name + "' → 需要通过加载场景访问内容"); break; } return list; } public static bool SetSpriteFromCollection(tk2dSprite sprite, tk2dSpriteCollectionData collection, string spriteName, string logTag = "ChainFixer") { if ((Object)(object)sprite == (Object)null || (Object)(object)collection == (Object)null) { return false; } int spriteIdByName = collection.GetSpriteIdByName(spriteName); if (spriteIdByName < 0) { Plugin.Log?.LogWarning("[" + logTag + "] collection '" + ((Object)collection).name + "' 中未找到 sprite: '" + spriteName + "'"); return false; } ((tk2dBaseSprite)sprite).SetSprite(collection, spriteIdByName); Plugin.Log?.LogInfo("[" + logTag + "] sprite 设置成功: '" + spriteName + "' (collection='" + ((Object)collection).name + "')"); return true; } public static GameObject CreateTemplate(string name, Action<GameObject> builder, string logTag = "ChainFixer") { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown GameObject val = new GameObject(name); val.SetActive(false); try { builder(val); } catch (Exception ex) { Plugin.Log?.LogWarning("[" + logTag + "] CreateTemplate builder 异常: " + ex.Message); } Object.DontDestroyOnLoad((Object)(object)val); Plugin.Log?.LogInfo("[" + logTag + "] 模板创建完成: '" + name + "'"); return val; } public static tk2dSpriteCollectionData LoadTk2dCollectionBundle(string logTag = "ChainFixer") { if ((Object)(object)_cachedCoinRocksCollection != (Object)null) { return _cachedCoinRocksCollection; } if (_coinRocksLoadAttempted) { return null; } _coinRocksLoadAttempted = true; Plugin.Log?.LogInfo("[" + logTag + "] 搜索全内存 tk2dSpriteCollectionData..."); tk2dSpriteCollectionData[] array = Resources.FindObjectsOfTypeAll<tk2dSpriteCollectionData>(); foreach (tk2dSpriteCollectionData val in array) { if ((Object)(object)val == (Object)null || val.spriteDefinitions == null) { continue; } for (int j = 0; j < val.spriteDefinitions.Length; j++) { if (val.spriteDefinitions[j] != null && val.spriteDefinitions[j].name == "rosary_rock_type_020000") { _cachedCoinRocksCollection = val; Plugin.Log?.LogInfo($"[{logTag}] ★ 找到 Coin Rocks collection: sprites={val.spriteDefinitions.Length} target_index={j}"); return _cachedCoinRocksCollection; } } } Plugin.Log?.LogInfo("[" + logTag + "] 全内存未命中,遍历已加载 bundle..."); foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if ((Object)(object)allLoadedAssetBundle == (Object)null) { continue; } try { array = allLoadedAssetBundle.LoadAllAssets<tk2dSpriteCollectionData>(); foreach (tk2dSpriteCollectionData val2 in array) { if ((Object)(object)val2 == (Object)null || val2.spriteDefinitions == null) { continue; } for (int k = 0; k < val2.spriteDefinitions.Length; k++) { if (val2.spriteDefinitions[k] != null && val2.spriteDefinitions[k].name == "rosary_rock_type_020000") { _cachedCoinRocksCollection = val2; Plugin.Log?.LogInfo($"[{logTag}] ★ 从 bundle '{((Object)allLoadedAssetBundle).name}' 找到 Coin Rocks collection: sprites={val2.spriteDefinitions.Length}"); return _cachedCoinRocksCollection; } } } } catch { } } Plugin.Log?.LogWarning("[" + logTag + "] 全内存+全 bundle 搜索均未找到 Coin Rocks collection"); return null; } public static void RunDemoSpawn() { try { Transform val = UIManagerFindCanvas(); GameObject val2 = SpawnWithFullChain("prompts_assets_all.bundle", "Assets/Prefabs/UI/Messages/UI Msg Crest Evolve.prefab", ((Object)(object)val != (Object)null) ? ((Component)val).transform : null, "F5Demo"); if ((Object)(object)val2 == (Object)null) { Plugin.Log?.LogWarning("[F5Demo] 修复流程失败"); return; } val2.SetActive(true); Plugin.Log?.LogInfo("[F5Demo] 实例化成功: " + ((Object)val2).name); Plugin.Log?.LogInfo("[F5Demo] " + ReportSpriteState(val2)); } catch (Exception arg) { Plugin.Log?.LogError($"[F5Demo] 异常: {arg}"); } } private static Transform UIManagerFindCanvas() { try { Type type = Type.GetType("UIManager, Assembly-CSharp"); if (type != null) { Object val = Object.FindObjectOfType(type); if (val != (Object)null) { PropertyInfo property = type.GetProperty("UICanvas"); if (property != null) { object? value = property.GetValue(val); Canvas val2 = (Canvas)((value is Canvas) ? value : null); if (val2 != null) { return ((Component)val2).transform; } } } } } catch { } Canvas[] array = Resources.FindObjectsOfTypeAll<Canvas>(); foreach (Canvas val3 in array) { if ((Object)(object)val3 != (Object)null && !val3.overrideSorting) { return ((Component)val3).transform; } } return null; } public static void StartNativeClipPlay(GameObject go, string logTag = "原生采样") { if (!((Object)(object)go == (Object)null)) { ((MonoBehaviour)Plugin.Instance).StartCoroutine(NativeClipCoroutine(go, logTag)); } } private static IEnumerator NativeClipCoroutine(GameObject go, string logTag) { int num = 0; PlayMakerFSM[] componentsInChildren = go.GetComponentsInChildren<PlayMakerFSM>(true); for (int i = 0; i < componentsInChildren.Length; i++) { ((Behaviour)componentsInChildren[i]).enabled = false; num++; } int num2 = 0; Animator[] componentsInChildren2 = go.GetComponentsInChildren<Animator>(true); for (int i = 0; i < componentsInChildren2.Length; i++) { ((Behaviour)componentsInChildren2[i]).enabled = false; num2++; } Plugin.Log?.LogInfo($"[{logTag}] 已禁用 FSM x{num} Animator x{num2}"); Animator anim = null; componentsInChildren2 = go.GetComponentsInChildren<Animator>(true); foreach (Animator val in componentsInChildren2) { if ((Object)(object)val.runtimeAnimatorController != (Object)null) { anim = val; break; } } if ((Object)(object)anim == (Object)null) { Plugin.Log?.LogWarning("[" + logTag + "] 无 Animator"); yield break; } RuntimeAnimatorController runtimeAnimatorController = anim.runtimeAnimatorController; AnimationClip clip = null; string text = ""; try { AnimationClip[] animationClips = runtimeAnimatorController.animationClips; Plugin.Log?.LogInfo("[" + logTag + "] controller=" + ((Object)runtimeAnimatorController).name + " clips=" + ((animationClips == null) ? "null" : animationClips.Length.ToString())); if (animationClips != null && animationClips.Length != 0) { clip = animationClips[0]; text = (((Object)(object)clip != (Object)null) ? $"{((Object)clip).name} len={clip.length}" : "null"); } } catch (Exception ex) { Plugin.Log?.LogError("[" + logTag + "] 取 clip 异常: " + ex.Message); } Plugin.Log?.LogInfo("[" + logTag + "] clip0 = " + text); Transform val2 = go.transform.Find("Tool_Socket_Evolve_lvl1"); if ((Object)(object)val2 == (Object)null) { Plugin.Log?.LogWarning("[" + logTag + "] 找不到 lvl1"); yield break; } Transform val3 = val2.Find("Pivot/Icon"); SpriteRenderer srIcon = (((Object)(object)val3 != (Object)null) ? ((Component)val3).GetComponent<SpriteRenderer>() : null); if ((Object)(object)clip == (Object)null) { Plugin.Log?.LogWarning("[" + logTag + "] clip 为空,回退手动演出"); yield return ManualPlayCoroutine(go, logTag); yield break; } AnimationEvent[] evts = clip.events; if (evts != null && evts.Length != 0) { Array.Sort(evts, (AnimationEvent a, AnimationEvent b) => a.time.CompareTo(b.time)); Plugin.Log?.LogInfo("[" + logTag + "] 事件表: " + string.Join(", ", Array.ConvertAll(evts, (AnimationEvent e) => $"{e.functionName}@{e.time:F2}s"))); } float t = 0f; float dur = Mathf.Max(0.1f, clip.length); int evtIdx = 0; while (t < dur) { clip.SampleAnimation(((Component)anim).gameObject, t); if (evts != null) { for (; evtIdx < evts.Length && t >= evts[evtIdx].time; evtIdx++) { string functionName = evts[evtIdx].functionName; Plugin.Log?.LogInfo($"[{logTag}] 事件@{t:F2}s: {functionName}"); ((Component)anim).gameObject.SendMessage(functionName, (SendMessageOptions)1); if ((Object)(object)go != (Object)null && (Object)(object)go != (Object)(object)((Component)anim).gameObject) { go.SendMessage(functionName, (SendMessageOptions)1); } } } t += Time.deltaTime; yield return null; } clip.SampleAnimation(((Component)anim).gameObject, dur - 0.001f); string arg = (((Object)(object)srIcon != (Object)null && (Object)(object)srIcon.sprite != (Object)null) ? ((Object)srIcon.sprite).name : "nullSprite"); Plugin.Log?.LogInfo($"[{logTag}] 采样完成 dur={dur:F2} 终帧Icon={arg}"); yield return (object)new WaitForSeconds(1f); Object.Destroy((Object)(object)go); } public static Sprite FindLoadedSprite(string name) { if (_spriteCache != null && _spriteCache.TryGetValue(name, out var value)) { return value; } if (_spriteCache == null) { _spriteCache = new Dictionary<string, Sprite>(); } Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>(); foreach (Sprite val in array) { if (!((Object)(object)val == (Object)null) && !(((Object)val).name != name)) { _spriteCache[name] = val; return val; } } _spriteCache[name] = null; return null; } public static void StartManualPlay(GameObject go, string logTag = "手动演出") { if (!((Object)(object)go == (Object)null)) { ((MonoBehaviour)Plugin.Instance).StartCoroutine(ManualPlayCoroutine(go, logTag)); } } private static IEnumerator ManualPlayCoroutine(GameObject go, string logTag) { int num = 0; Animator[] componentsInChildren = go.GetComponentsInChildren<Animator>(true); for (int i = 0; i < componentsInChildren.Length; i++) { ((Behaviour)componentsInChildren[i]).enabled = false; num++; } Plugin.Log?.LogInfo($"[{logTag}] 已禁用 Animator x{num}"); int num2 = 0; PlayMakerFSM[] componentsInChildren2 = go.GetComponentsInChildren<PlayMakerFSM>(true); for (int i = 0; i < componentsInChildren2.Length; i++) { ((Behaviour)componentsInChildren2[i]).enabled = false; num2++; } Plugin.Log?.LogInfo($"[{logTag}] 已禁用 PlayMakerFSM x{num2}"); Transform val = go.transform.Find("Tool_Socket_Evolve_lvl1"); if ((Object)(object)val == (Object)null) { Plugin.Log?.LogWarning("[" + logTag + "] 找不到 Tool_Socket_Evolve_lvl1"); yield break; } Transform t = val.Find("Pivot/Icon"); Transform t2 = val.Find("Pivot/Icon_Glow"); Transform crest = val.Find("Pivot/Crest"); Transform t3 = val.Find("Pivot/Crest_Glow"); Transform t4 = val.Find("white_flash"); Transform val2 = val.Find("evolve_burst"); Transform val3 = val.Find("evolve_loop"); Transform val4 = go.transform.Find("BG"); SpriteRenderer srIcon = GetSR(t); SpriteRenderer srIconGlow = GetSR(t2); SpriteRenderer srCrest = GetSR(crest); SpriteRenderer srCrestGlow = GetSR(t3); SpriteRenderer srFlash = GetSR(t4); SpriteRenderer srBG = GetSR(val4); Sprite fallback = FindLoadedSprite("UI_tool_slot_extra_sockets_single"); Sprite sprTiny = FindLoadedSprite("UI_tool_slot_extra_sockets_0000_filled_tiny"); Sprite sprGlow = FindLoadedSprite("UI_tool_slot_extra_sockets_0000_filled_glow"); Sprite fallback2 = FindLoadedSprite("hornet_prompts_tool_sockets_0001_explorer_socket"); fallback = snap(srCrest, fallback); sprTiny = snap(srCrest, sprTiny); sprGlow = snap(srCrestGlow, sprGlow); fallback2 = snap(srIcon, fallback2); ModLog log = Plugin.Log; if (log != null) { string[] obj = new string[12] { "[", logTag, "] sprite: single=", ((fallback != null) ? ((Object)fallback).name : null) ?? "null", " tiny=", null, null, null, null, null, null, null }; Sprite obj2 = sprTiny; obj[5] = ((obj2 != null) ? ((Object)obj2).name : null) ?? "null"; obj[6] = " glow="; Sprite obj3 = sprGlow; obj[7] = ((obj3 != null) ? ((Object)obj3).name : null) ?? "null"; obj[8] = " icon="; obj[9] = ((fallback2 != null) ? ((Object)fallback2).name : null) ?? "null"; obj[10] = " bg="; object obj4; if (srBG == null) { obj4 = null; } else { Sprite sprite = srBG.sprite; obj4 = ((sprite != null) ? ((Object)sprite).name : null); } if (obj4 == null) { obj4 = "null"; } obj[11] = (string)obj4; log.LogInfo(string.Concat(obj)); } ParticleSystem psBurst = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<ParticleSystem>() : null); ParticleSystem val5 = (((Object)(object)val3 != (Object)null) ? ((Component)val3).GetComponent<ParticleSystem>() : null); if ((Object)(object)psBurst != (Object)null) { EmissionModule emission = psBurst.emission; ((EmissionModule)(ref emission)).enabled = false; } if ((Object)(object)val5 != (Object)null) { EmissionModule emission2 = val5.emission; ((EmissionModule)(ref emission2)).enabled = false; val5.Stop(true, (ParticleSystemStopBehavior)0); } if ((Object)(object)srBG != (Object)null) { srBG.color = new Color(0f, 0f, 0f, 0f); val4.SetAsFirstSibling(); } if ((Object)(object)srIcon != (Object)null) { srIcon.sprite = fallback2; srIcon.color = new Color(1f, 1f, 1f, 0f); } if ((Object)(object)srIconGlow != (Object)null) { srIconGlow.color = new Color(1f, 1f, 1f, 0f); } if ((Object)(object)srCrest != (Object)null) { srCrest.sprite = fallback; srCrest.color = new Color(1f, 1f, 1f, 0f); } if ((Object)(object)srCrestGlow != (Object)null) { srCrestGlow.sprite = sprGlow; srCrestGlow.color = new Color(1f, 1f, 1f, 0f); } if ((Object)(object)srFlash != (Object)null) { srFlash.color = new Color(1f, 1f, 1f, 0f); } crest.localScale = Vector3.one * 0.4f; float t5 = 0f; float bgIn = 0.28f; while (t5 < 0.58000004f) { t5 += Time.deltaTime; float num3 = Mathf.Clamp01(t5 / bgIn) * 0.85f; if ((Object)(object)srBG != (Object)null) { srBG.color = new Color(0f, 0f, 0f, num3); } float num4 = Mathf.Clamp01((t5 - 0.05f) / 0.22f); if ((Object)(object)srIcon != (Object)null) { srIcon.color = new Color(1f, 1f, 1f, num4); } if ((Object)(object)srIconGlow != (Object)null) { srIconGlow.color = new Color(1f, 1f, 1f, num4 * 0.5f); } yield return null; } while (t5 < 1f) { t5 += Time.deltaTime; float num5 = Mathf.Clamp01((t5 - 0.58f) / 0.42f); float num6 = 1f - Mathf.Pow(1f - num5, 3f); crest.localScale = Vector3.one * Mathf.Lerp(0.4f, 1.12f, num6); if ((Object)(object)srCrest != (Object)null) { srCrest.color = new Color(1f, 1f, 1f, num6); } if ((Object)(object)srCrestGlow != (Object)null) { srCrestGlow.color = new Color(1f, 1f, 1f, num6); ((Component)srCrestGlow).transform.localScale = Vector3.one * Mathf.Lerp(2.2f, 2.8f, num6); } yield return null; } if ((Object)(object)srCrest != (Object)null && (Object)(object)sprTiny != (Object)null) { srCrest.sprite = sprTiny; } yield return (object)new WaitForSeconds(0.12f); if ((Object)(object)srCrest != (Object)null && (Object)(object)sprGlow != (Object)null) { srCrest.sprite = sprGlow; } if ((Object)(object)psBurst != (Object)null) { psBurst.Play(); } if ((Object)(object)srFlash != (Object)null) { float ft = 0f; while (ft < 0.22f) { ft += Time.deltaTime; float num7 = ((ft < 0.07f) ? (ft / 0.07f) : (1f - (ft - 0.07f) / 0.15f)); srFlash.color = new Color(1f, 1f, 1f, Mathf.Clamp01(num7) * 0.95f); yield return null; } srFlash.color = new Color(1f, 1f, 1f, 0f); } if ((Object)(object)psBurst != (Object)null) { psBurst.Stop(true, (ParticleSystemStopBehavior)0); } yield return (object)new WaitForSeconds(1.2f); float ot = 0f; while (ot < 0.5f) { ot += Time.deltaTime; float num8 = 1f - Mathf.Clamp01(ot / 0.5f); if ((Object)(object)srBG != (Object)null && (Object)(object)srBG != (Object)null) { srBG.color = new Color(0f, 0f, 0f, 0.85f * num8); } if ((Object)(object)srIcon != (Object)null) { srIcon.color = new Color(1f, 1f, 1f, num8); } if ((Object)(object)srIconGlow != (Object)null) { srIconGlow.color = new Color(1f, 1f, 1f, num8 * 0.5f); } if ((Object)(object)srCrest != (Object)null) { srCrest.color = new Color(1f, 1f, 1f, num8); } if ((Object)(object)srCrestGlow != (Object)null) { srCrestGlow.color = new Color(1f, 1f, 1f, num8); } yield return null; } Object.Destroy((Object)(object)go); Plugin.Log?.LogInfo("[" + logTag + "] 演出完成,已销毁"); static SpriteRenderer GetSR(Transform val6) { if (!((Object)(object)val6 != (Object)null)) { return null; } return ((Component)val6).GetComponent<SpriteRenderer>(); } static Sprite snap(SpriteRenderer sr, Sprite result) { if ((Object)(object)sr != (Object)null && (Object)(object)sr.sprite != (Object)null) { return sr.sprite; } return result; } } } public sealed class ModLog { private const int FlushThreshold = 4096; private static readonly Dictionary<string, ModLog> _byTag; private static readonly object _registryGate; private static ManualLogSource _fallback; private static bool _closed; private readonly string _tag; private readonly object _gate = new object(); private readonly StringBuilder _buffer = new StringBuilder(5120); private StreamWriter _writer; private bool _broken; private static ModLog _default; private static ModLog DefaultInstance { get { ModLog modLog = _default; if (modLog != null) { return modLog; } return _default = For(typeof(ModLog).Assembly.GetName().Name); } } private ModLog(string tag) { _tag = tag; } public static ModLog For(string tag) { lock (_registryGate) { if (_byTag.TryGetValue(tag, out var value)) { return value; } value = new ModLog(tag); _byTag[tag] = value; return value; } } public static void SetFallback(ManualLogSource source) { _fallback = source; } public static void Shutdown() { lock (_registryGate) { _closed = true; foreach (KeyValuePair<string, ModLog> item in _byTag) { item.Value.Close(); } _byTag.Clear(); } } static ModLog() { _byTag = new Dictionary<string, ModLog>(4); _registryGate = new object(); try { AppDomain.CurrentDomain.ProcessExit += delegate { Shutdown(); }; AppDomain.CurrentDomain.DomainUnload += delegate { Shutdown(); }; } catch { } } public void LogInfo(object message) { Write("INFO ", message); } public void LogWarning(object message) { Write("WARN ", message); } public void LogError(object message) { Write("ERROR", message); } public void LogDebug(object message) { Write("DEBUG", message); } public void LogMessage(object message) { Write("INFO ", message); } public static void Info(object message) { DefaultInstance.LogInfo(message); } public static void Warning(object message) { DefaultInstance.LogWarning(message); } public static void Error(object message) { DefaultInstance.LogError(message); } public static void Debug(object message) { DefaultInstance.LogDebug(message); } private void Write(string level, object message) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (message == null) { return; } string text = message as string; if (text == null) { text = message.ToString(); } if (string.IsNullOrEmpty(text)) { return; } lock (_gate) { if (_closed) { return; } if (_broken) { if (_fallback != null) { _fallback.Log(LevelOf(level), (object)text); } return; } _buffer.Append(DateTime.Now.ToString("HH:mm:ss.fff")); _buffer.Append(" [").Append(level).Append("] "); _buffer.Append(text); _buffer.Append('\n'); if (_buffer.Length >= 4096 || level == "ERROR") { FlushLocked(); } } } private void FlushLocked() { if (_buffer.Length == 0) { return; } try { if (_writer == null) { OpenLocked(); } _writer.Write(_buffer.ToString()); _writer.Flush(); _buffer.Length = 0; } catch (Exception ex) { _broken = true; _buffer.Length = 0; if (_fallback != null) { _fallback.LogWarning((object)("[ModLog] 写入日志文件失败,后续日志回退到 BepInEx 日志: " + ex.Message)); } } } private void OpenLocked() { string text = Path.Combine(Paths.ConfigPath, "SilksongItemRandomizer", "logs"); Directory.CreateDirectory(text); string path = _tag + ".log"; FileStream stream = new FileStream(Path.Combine(text, path), FileMode.Create, FileAccess.Write, FileShare.ReadWrite); _writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); _writer.AutoFlush = false; } private void Close() { lock (_gate) { if (_buffer.Length > 0 && !_broken) { FlushLocked(); } if (_writer != null) { try { _writer.Flush(); _writer.Dispose(); } catch { } _writer = null; } _buffer.Length = 0; } } private static LogLevel LevelOf(string level) { return (LogLevel)(level switch { "ERROR" => 2, "WARN " => 4, "DEBUG" => 32, _ => 16, }); } } }
BepInEx/plugins/HKSilksong_SceneRandomizer.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using PharloomCore.Logic; using SilksongItemRandomizer; using StartingAbilityPicker; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("0.0.0.0")] namespace HKSilksong_Randomizer; public static class RoomMapGenerator { private static readonly bool[,] letters; static RoomMapGenerator() { letters = new bool[128, 25]; string[] array = new string[26] { "01110100011000111111000110001", "11110100011111010001100011111", "01110100011000010000100000111", "11110100011000110001100011110", "11111100001111010000100011111", "11111100001111010000100010000", "01110100011000010111100001111", "10001100011111110001100011000", "01110001000010000100001000111", "00111000100001000100011001100", "10001100101110010010100011000", "10000100001000010000100001111", "10001110111010110001100011000", "10001110011010110011100011000", "01110100011000110001100010111", "11110100011111010000100010000", "01110100011000110001101010101", "11110100011111010010100011001", "01111100000111000001100011110", "11111001000010000100001000010", "10001100011000110001100001110", "10001100011000101010001000100", "10001100011000110101101011010", "10001010100010001010100010001", "10001010100010000100001000010", "11111000100010001000100011111" }; for (int i = 0; i < 26; i++) { string text = array[i]; for (int j = 0; j < 25; j++) { letters[65 + i, j] = text[j] == '1'; } } string[] array2 = new string[10] { "01110100011000110001100010111", "00100011000010000100001000111", "01110100010001000100010001111", "11110000111100000011100011110", "10001100111110000010000100010", "11111100001111000001100011111", "01110100001111010001100010111", "11111000010001000100001000010", "01110100011000101110100010111", "01110100011000101111000011110" }; for (int k = 0; k < 10; k++) { string text2 = array2[k]; for (int l = 0; l < 25; l++) { letters[48 + k, l] = text2[l] == '1'; } } string text3 = "00000000000000000000011111"; for (int m = 0; m < 25; m++) { letters[95, m] = text3[m] == '1'; } } public static bool GenerateFromFile(string connectionsFilePath, string outputImagePath) { if (!File.Exists(connectionsFilePath)) { ModLog.Warning("File not found: " + connectionsFilePath); return false; } return GenerateFromLines(File.ReadAllLines(connectionsFilePath), outputImagePath); } public static bool GenerateFromLines(IEnumerable<string> connectionLines, string outputImagePath) { Dictionary<string, HashSet<string>> dictionary = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase); foreach (string connectionLine in connectionLines) { string text = connectionLine?.Trim(); if (string.IsNullOrEmpty(text) || text.StartsWith("#")) { continue; } string[] array = text.Split(new char[1] { '|' }); if (array.Length != 4) { continue; } string text2 = array[0]; string text3 = array[2]; if (!string.IsNullOrEmpty(text2) && !string.IsNullOrEmpty(text3)) { if (!dictionary.ContainsKey(text2)) { dictionary[text2] = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } if (!dictionary.ContainsKey(text3)) { dictionary[text3] = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } dictionary[text2].Add(text3); dictionary[text3].Add(text2); } } if (dictionary.Count == 0) { ModLog.Warning("No connections found."); return false; } GenerateMapTexture(dictionary, outputImagePath); ModLog.Info("Map saved to " + outputImagePath); return true; } private static void GenerateMapTexture(Dictionary<string, HashSet<string>> graph, string outputPath) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) int num = 250; int num2 = 120; int num3 = 100; int num4 = 80; List<string> list = graph.Keys.ToList(); int num5 = (int)Math.Ceiling(Math.Sqrt(list.Count)); int num6 = (int)Math.Ceiling((double)list.Count / (double)num5); int num7 = num5 * (num + num3) + num3; int num8 = num6 * (num2 + num4) + num4; Texture2D val = new Texture2D(num7, num8, (TextureFormat)4, false); Color[] array = (Color[])(object)new Color[num7 * num8]; for (int i = 0; i < array.Length; i++) { array[i] = Color.black; } val.SetPixels(array); Dictionary<string, Vector2> dictionary = new Dictionary<string, Vector2>(); int num9 = 0; int num10 = 0; foreach (string item in list) { dictionary[item] = new Vector2((float)(num3 + num9 * (num + num3)), (float)(num4 + num10 * (num2 + num4))); num9++; if (num9 >= num5) { num9 = 0; num10++; } } foreach (KeyValuePair<string, HashSet<string>> item2 in graph) { if (!dictionary.TryGetValue(item2.Key, out var value)) { continue; } foreach (string item3 in item2.Value) { if (dictionary.TryGetValue(item3, out var value2)) { DrawLine(val, (int)(value.x + (float)(num / 2)) + 2, (int)(value.y + (float)(num2 / 2)) + 2, (int)(value2.x + (float)(num / 2)) + 2, (int)(value2.y + (float)(num2 / 2)) + 2, Color.gray, 3); } } } foreach (KeyValuePair<string, Vector2> item4 in dictionary) { DrawEmptyRectangle(val, (int)item4.Value.x, (int)item4.Value.y, num, num2, Color.gray); DrawTextBitmap(val, (int)item4.Value.x + 10, (int)item4.Value.y + 35, item4.Key, Color.white); } val.Apply(); string directoryName = Path.GetDirectoryName(outputPath); if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } File.WriteAllBytes(outputPath, ImageConversion.EncodeToPNG(val)); Object.DestroyImmediate((Object)(object)val); } private static void DrawEmptyRectangle(Texture2D tex, int x, int y, int w, int h, Color color) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) for (int i = x; i < x + w; i++) { if (i >= 0 && i < ((Texture)tex).width) { if (y >= 0 && y < ((Texture)tex).height) { tex.SetPixel(i, y, color); } if (y + h - 1 >= 0 && y + h - 1 < ((Texture)tex).height) { tex.SetPixel(i, y + h - 1, color); } } } for (int j = y; j < y + h; j++) { if (j >= 0 && j < ((Texture)tex).height) { if (x >= 0 && x < ((Texture)tex).width) { tex.SetPixel(x, j, color); } if (x + w - 1 >= 0 && x + w - 1 < ((Texture)tex).width) { tex.SetPixel(x + w - 1, j, color); } } } } private static void DrawTextBitmap(Texture2D tex, int x, int y, string text, Color color) { //IL_00c6: Unknown result type (might be due to invalid IL or missing references) int num = x; int num2 = 4; int num3 = 1; string text2 = text.ToUpper(); foreach (char c in text2) { if ((c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_') { num += 5 * num2 + num2; continue; } for (int j = 0; j < 5; j++) { for (int k = 0; k < 5; k++) { if (!letters[(uint)c, j * 5 + k]) { continue; } int num4 = ((c != '_') ? (4 - j) : (4 - j - num3)); for (int l = 0; l < num2; l++) { for (int m = 0; m < num2; m++) { int num5 = num + k * num2 + l; int num6 = y + num4 * num2 + m; if (num5 >= 0 && num5 < ((Texture)tex).width && num6 >= 0 && num6 < ((Texture)tex).height) { tex.SetPixel(num5, num6, color); } } } } } num += 5 * num2 + num2; } } private static void DrawLine(Texture2D tex, int x0, int y0, int x1, int y1, Color color, int thickness = 2) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) int num = Math.Abs(x1 - x0); int num2 = ((x0 < x1) ? 1 : (-1)); int num3 = -Math.Abs(y1 - y0); int num4 = ((y0 < y1) ? 1 : (-1)); int num5 = num + num3; while (true) { for (int i = -thickness / 2; i <= thickness / 2; i++) { for (int j = -thickness / 2; j <= thickness / 2; j++) { int num6 = x0 + i; int num7 = y0 + j; if (num6 >= 0 && num6 < ((Texture)tex).width && num7 >= 0 && num7 < ((Texture)tex).height) { tex.SetPixel(num6, num7, color); } } } if (x0 != x1 || y0 != y1) { int num8 = 2 * num5; if (num8 >= num3) { num5 += num3; x0 += num2; } if (num8 <= num) { num5 += num; y0 += num4; } continue; } break; } } } [BepInPlugin("HardItemRandomizer.HKSilksong_SceneRandomizer", "Random Scene Loader", "0.1.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class RandomSceneLoader : BaseUnityPlugin { internal class SceneConfig { public List<string> Exits; public SceneConfig(List<string> exits) { Exits = exits ?? new List<string>(); } } internal ModLog log = ModLog.For("SceneRandomizer"); private Random rng; private static readonly Dictionary<string, SceneConfig> FallbackSceneConfigs = new Dictionary<string, SceneConfig>(StringComparer.OrdinalIgnoreCase) { { "Tut_01", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "top1" }) }, { "Tut_01b", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Tut_02", new SceneConfig(new List<string> { "right1", "right2" }) }, { "Tut_03", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Bonetown", new SceneConfig(new List<string> { "bot1", "bot2", "left1", "left2", "right1", "right2", "top1", "top2", "top3", "top4", "top5", "top6" }) }, { "Weave_02", new SceneConfig(new List<string> { "left2", "left3", "left4", "right1", "right2", "right3" }) }, { "Weave_03", new SceneConfig(new List<string> { "right1" }) }, { "Weave_04", new SceneConfig(new List<string> { "left1", "right2" }) }, { "Weave_05b", new SceneConfig(new List<string> { "left1" }) }, { "Weave_07", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Weave_08", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Weave_10", new SceneConfig(new List<string> { "left1" }) }, { "Weave_11", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Weave_12", new SceneConfig(new List<string> { "left1" }) }, { "Weave_13", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Weave_14", new SceneConfig(new List<string> { "bot1" }) }, { "Bone_01", new SceneConfig(new List<string> { "left2", "right1", "right2", "top2" }) }, { "Bone_04", new SceneConfig(new List<string> { "bot2", "left1", "left2", "right1", "top1" }) }, { "Bone_05", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Bone_03", new SceneConfig(new List<string> { "bot1", "left1", "left2", "left4", "right1", "right3", "top1" }) }, { "Bone_05b", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Bone_06", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Bone_07", new SceneConfig(new List<string> { "left1", "right1", "right2", "top1" }) }, { "Bone_08", new SceneConfig(new List<string> { "bot1", "left2", "left3", "right2", "right3" }) }, { "Bone_09", new SceneConfig(new List<string> { "left1", "right1", "right2", "top1" }) }, { "Bone_10", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Bone_11", new SceneConfig(new List<string> { "bot1", "left1", "right1", "right2", "top1" }) }, { "Bone_14", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Bone_15", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Bone_16", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Bone_17", new SceneConfig(new List<string> { "right1" }) }, { "Bone_18", new SceneConfig(new List<string> { "left1" }) }, { "Bone_19", new SceneConfig(new List<string> { "bot1" }) }, { "Bone_East_01", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "right3" }) }, { "Bone_East_02", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Bone_East_04", new SceneConfig(new List<string> { "bot1", "left1", "right1", "right2", "top2" }) }, { "Bone_East_05", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Bone_East_07", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "right1", "right2", "right3", "right4", "right5", "top1" }) }, { "Bone_East_09", new SceneConfig(new List<string> { "left2", "left3", "right1", "right2", "top1" }) }, { "Bone_East_10", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2" }) }, { "Bone_East_11", new SceneConfig(new List<string> { "bot1", "left1", "right1", "right2" }) }, { "Bone_East_12", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Bone_East_13", new SceneConfig(new List<string> { "left1" }) }, { "Bone_East_14", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2" }) }, { "Bone_East_15", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Bone_East_16", new SceneConfig(new List<string> { "bot1", "right1" }) }, { "Bone_East_17", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Bone_East_18", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Bone_East_18b", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Bone_East_18c", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Bone_East_20", new SceneConfig(new List<string> { "right1" }) }, { "Bone_East_22", new SceneConfig(new List<string> { "left1" }) }, { "Bone_East_24", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Bone_East_25", new SceneConfig(new List<string> { "left1" }) }, { "Bone_East_26", new SceneConfig(new List<string> { "bot1", "top1" }) }, { "Bone_East_27", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Bone_East_04c", new SceneConfig(new List<string> { "left1" }) }, { "Bone_East_04b", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Bone_East_09b", new SceneConfig(new List<string> { "bot1", "left1", "top1" }) }, { "Bone_East_14b", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Ant_02", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Ant_03", new SceneConfig(new List<string> { "left2", "right3" }) }, { "Ant_04", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Ant_04_left", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Ant_04_mid", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Ant_05b", new SceneConfig(new List<string> { "bot1", "bot2", "right1" }) }, { "Ant_05c", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Ant_09", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Ant_14", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "left5", "right2", "right3" }) }, { "Ant_17", new SceneConfig(new List<string> { "right1" }) }, { "Ant_19", new SceneConfig(new List<string> { "left1" }) }, { "Ant_20", new SceneConfig(new List<string> { "left1" }) }, { "Ant_21", new SceneConfig(new List<string> { "right1" }) }, { "Ant_Merchant", new SceneConfig(new List<string> { "right1" }) }, { "Ant_Queen", new SceneConfig(new List<string> { "left1" }) }, { "Aspid_01", new SceneConfig(new List<string> { "bot1", "bot2", "bot3", "bot4", "bot5", "bot6", "bot7", "bot8", "left1", "left2", "right2", "right3", "right4", "top1", "top2", "top3", "top4", "top5", "top6", "top7" }) }, { "Belltown_04", new SceneConfig(new List<string> { "bot1", "left1", "left2" }) }, { "Belltown_06", new SceneConfig(new List<string> { "left1", "left3", "right1" }) }, { "Belltown_Room_shellwood", new SceneConfig(new List<string> { "left1" }) }, { "Belltown_Shrine", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Belltown_basement_03", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Bellshrine", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Bellshrine_03", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Bonegrave", new SceneConfig(new List<string> { "right1", "right2", "top1" }) }, { "Bone_01c", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Bone_02", new SceneConfig(new List<string> { "left1", "right1", "top1", "top2" }) }, { "Bellshrine_05", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Bellway_03", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Greymoor_01", new SceneConfig(new List<string> { "bot1", "left1", "left2", "right1", "right2", "right3" }) }, { "Bellshrine_02", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Greymoor_02", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3" }) }, { "Greymoor_15", new SceneConfig(new List<string> { "left1", "left3", "right2", "right3" }) }, { "Greymoor_15b", new SceneConfig(new List<string> { "left2", "left3", "right1", "top1" }) }, { "Room_CrowCourt", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Room_CrowCourt_02", new SceneConfig(new List<string> { "top1" }) }, { "Clover_01", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Greymoor_22", new SceneConfig(new List<string> { "bot1" }) }, { "Greymoor_12", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Greymoor_03", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3", "right4", "right5" }) }, { "Dust_01", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Dust_02", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "right3", "top1" }) }, { "Dust_03", new SceneConfig(new List<string> { "bot1", "left1", "top1" }) }, { "Dust_Chef", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Dust_04", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Dust_Shack", new SceneConfig(new List<string> { "left1" }) }, { "Dust_10", new SceneConfig(new List<string> { "right1" }) }, { "Dust_05", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Dust_06", new SceneConfig(new List<string> { "left1", "right1", "right2", "right3" }) }, { "Dust_12", new SceneConfig(new List<string> { "left1" }) }, { "Dust_11", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Greymoor_17", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Halfway_01", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Greymoor_04", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2" }) }, { "Greymoor_11", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Greymoor_06", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3", "right4", "top1" }) }, { "Greymoor_10", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Wisp_03", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Wisp_06", new SceneConfig(new List<string> { "bot1" }) }, { "Greymoor_07", new SceneConfig(new List<string> { "bot1", "left1", "right1", "right2" }) }, { "Greymoor_20b", new SceneConfig(new List<string> { "right1" }) }, { "Greymoor_20c", new SceneConfig(new List<string> { "left1" }) }, { "Greymoor_08", new SceneConfig(new List<string> { "left2", "right1", "top1" }) }, { "Greymoor_16", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Bellway_04", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Greymoor_05", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2" }) }, { "Belltown", new SceneConfig(new List<string> { "left3", "right2" }) }, { "Memory_Needolin", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Belltown_07", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shellwood_01", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2" }) }, { "Shellwood_02", new SceneConfig(new List<string> { "left2", "left3", "right1", "right2" }) }, { "Shellwood_16", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shellwood_03", new SceneConfig(new List<string> { "bot1", "left1", "left3", "right1", "right2", "right3" }) }, { "Shellwood_04b", new SceneConfig(new List<string> { "left1", "right1", "top1", "top2" }) }, { "Shellwood_08c", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shellwood_04c", new SceneConfig(new List<string> { "bot1", "top1" }) }, { "Shellwood_08", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Coral_19", new SceneConfig(new List<string> { "bot1", "bot2", "bot3", "bot4", "bot5", "bot6", "bot7", "right1", "top1", "top2", "top3", "top4", "top5", "top6", "top7", "top8" }) }, { "Shellwood_19", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shellwood_14", new SceneConfig(new List<string> { "left1" }) }, { "Shellwood_10", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3" }) }, { "Shellwood_11", new SceneConfig(new List<string> { "right1", "right2" }) }, { "Shellwood_26", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Shellwood_18", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Shellwood_13", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Shellwood_01b", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "right3" }) }, { "Shellwood_20", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shellwood_Witch", new SceneConfig(new List<string> { "right1" }) }, { "Dock_08", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Dock_01", new SceneConfig(new List<string> { "left1", "right1", "right2" }) }, { "Bellway_02", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Dock_16", new SceneConfig(new List<string> { "right1" }) }, { "Bone_East_03", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Room_Forge", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Dock_04", new SceneConfig(new List<string> { "left1", "right1", "right2", "right3" }) }, { "Dock_06_Church", new SceneConfig(new List<string> { "bot1", "right1" }) }, { "Dock_10", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Dock_15", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "right3" }) }, { "Dock_13", new SceneConfig(new List<string> { "right1" }) }, { "Dock_11", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Dock_12", new SceneConfig(new List<string> { "left1" }) }, { "Dock_14", new SceneConfig(new List<string> { "left1" }) }, { "Dock_09", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Dock_02", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "right3" }) }, { "Dock_02b", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2" }) }, { "Dock_03c", new SceneConfig(new List<string> { "left2", "top1", "top2" }) }, { "Dock_03", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Dock_03b", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shellwood_15", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Coral_19b", new SceneConfig(new List<string> { "bot1" }) }, { "Coral_02", new SceneConfig(new List<string> { "bot2", "right1" }) }, { "Coral_03", new SceneConfig(new List<string> { "bot1", "bot2", "bot3", "bot4", "bot5", "bot6", "left1", "left2", "left3", "right1", "right2", "right3" }) }, { "Coral_12", new SceneConfig(new List<string> { "left2", "left3", "right1" }) }, { "Coral_11", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Coral_11b", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Coral_34", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Coral_25", new SceneConfig(new List<string> { "bot1", "right1" }) }, { "Coral_23", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Coral_39", new SceneConfig(new List<string> { "right1" }) }, { "Coral_35b", new SceneConfig(new List<string> { "bot1", "left2", "left3", "left4", "left5", "right1", "right2" }) }, { "Coral_40", new SceneConfig(new List<string> { "right1" }) }, { "Coral_41", new SceneConfig(new List<string> { "right1" }) }, { "Coral_35", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "top1" }) }, { "Coral_24", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Coral_26", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Coral_38", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Coral_44", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Coral_29", new SceneConfig(new List<string> { "left1" }) }, { "Coral_27", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Coral_28", new SceneConfig(new List<string> { "right1" }) }, { "Coral_Tower_01", new SceneConfig(new List<string> { "left1" }) }, { "Coral_42", new SceneConfig(new List<string> { "right1" }) }, { "Coral_43", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Bellway_08", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Coral_32", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Coral_Judge_Arena", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Coral_10", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Song_19_entrance", new SceneConfig(new List<string> { "left1", "right1", "right2" }) }, { "Song_01c", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Song_01", new SceneConfig(new List<string> { "bot1", "right2", "top1" }) }, { "Under_07b", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Song_01b", new SceneConfig(new List<string> { "bot1", "right1", "top1" }) }, { "Song_05", new SceneConfig(new List<string> { "left3", "left4", "left5", "right2", "right3", "right4" }) }, { "Song_02", new SceneConfig(new List<string> { "left2", "right1" }) }, { "Ward_01", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3" }) }, { "Ward_02", new SceneConfig(new List<string> { "bot1", "right1", "top1" }) }, { "Ward_02b", new SceneConfig(new List<string> { "bot1", "right1" }) }, { "Ward_03", new SceneConfig(new List<string> { "bot1", "left1", "top1" }) }, { "Ward_07", new SceneConfig(new List<string> { "bot1" }) }, { "Ward_06", new SceneConfig(new List<string> { "bot1", "top1" }) }, { "Song_07", new SceneConfig(new List<string> { "right1" }) }, { "Song_27", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Song_20", new SceneConfig(new List<string> { "left1", "left2", "right4", "right5", "right6", "top1" }) }, { "Bellway_City", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Library_13", new SceneConfig(new List<string> { "left1", "right1", "right2" }) }, { "Song_11", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "right1", "right2", "right3" }) }, { "Song_15", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Song_17", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Hang_01", new SceneConfig(new List<string> { "right1", "right2" }) }, { "Hang_02", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Hang_03", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "top1" }) }, { "Hang_10", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Hang_03_top", new SceneConfig(new List<string> { "bot1" }) }, { "Hang_13", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Hang_08", new SceneConfig(new List<string> { "bot1", "left1", "left2", "left3", "left4", "right1" }) }, { "Hang_09", new SceneConfig(new List<string> { "right1" }) }, { "Hang_16", new SceneConfig(new List<string> { "right1" }) }, { "Hang_06", new SceneConfig(new List<string> { "bot1", "left1", "right1", "top1" }) }, { "Hang_06b", new SceneConfig(new List<string> { "left1" }) }, { "Hang_17b", new SceneConfig(new List<string> { "left1" }) }, { "Hang_04", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Hang_12", new SceneConfig(new List<string> { "right1" }) }, { "Hang_07", new SceneConfig(new List<string> { "bot1", "left1", "right1", "top1" }) }, { "Song_09", new SceneConfig(new List<string> { "bot1", "right1", "top1" }) }, { "Song_09b", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Cog_05", new SceneConfig(new List<string> { "left1", "right2", "top1" }) }, { "Cog_Dancers", new SceneConfig(new List<string> { "bot1", "bot2", "left1", "right1", "top1" }) }, { "Cog_04", new SceneConfig(new List<string> { "left2", "right2", "right3", "top1", "top2" }) }, { "Cog_Bench", new SceneConfig(new List<string> { "left1" }) }, { "Song_25", new SceneConfig(new List<string> { "bot1", "left1", "right1", "top1", "top2" }) }, { "Song_Enclave", new SceneConfig(new List<string> { "bot1", "left1", "left2", "top1" }) }, { "Song_Enclave_Tube", new SceneConfig(new List<string> { "bot1" }) }, { "Under_01", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1" }) }, { "Under_27", new SceneConfig(new List<string> { "left1", "right1", "right2" }) }, { "Shellwood_22", new SceneConfig(new List<string> { "right1" }) }, { "Shellwood_11b", new SceneConfig(new List<string> { "right1" }) }, { "Under_01b", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Under_02", new SceneConfig(new List<string> { "left1", "left3", "right1", "right2", "right3", "right4" }) }, { "Under_14", new SceneConfig(new List<string> { "left1" }) }, { "Under_16", new SceneConfig(new List<string> { "right1" }) }, { "Under_03b", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Under_07", new SceneConfig(new List<string> { "left3", "right2" }) }, { "Under_07c", new SceneConfig(new List<string> { "left2", "top1" }) }, { "Under_06", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Under_08", new SceneConfig(new List<string> { "bot1", "top1" }) }, { "Under_05", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3" }) }, { "Under_11", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Under_23", new SceneConfig(new List<string> { "bot1", "right1" }) }, { "Wisp_09", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Wisp_05", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Wisp_02", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Belltown_08", new SceneConfig(new List<string> { "right1" }) }, { "Wisp_04", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Wisp_08", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Wisp_07", new SceneConfig(new List<string> { "left1" }) }, { "Under_04", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Under_03c", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Under_03", new SceneConfig(new List<string> { "right1" }) }, { "Under_10", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Under_12", new SceneConfig(new List<string> { "left1" }) }, { "Under_13", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "right1", "right2", "right3" }) }, { "Under_22", new SceneConfig(new List<string> { "right1" }) }, { "Under_21", new SceneConfig(new List<string> { "right1" }) }, { "Under_19", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Under_19c", new SceneConfig(new List<string> { "bot1", "left1", "left2" }) }, { "Under_19b", new SceneConfig(new List<string> { "right1" }) }, { "Under_18", new SceneConfig(new List<string> { "left1", "right1", "top1", "top2" }) }, { "Under_17", new SceneConfig(new List<string> { "bot1", "bot2", "left1", "right1", "top1" }) }, { "Library_11b", new SceneConfig(new List<string> { "left3", "right1" }) }, { "Library_11", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2" }) }, { "Library_13b", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Library_04", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "right1", "right2", "right3", "right4", "right5", "right6", "top1" }) }, { "Library_16", new SceneConfig(new List<string> { "right1" }) }, { "Library_10", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Library_12b", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Library_12", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Library_05", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2" }) }, { "Library_06", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Library_07", new SceneConfig(new List<string> { "bot1", "bot2", "bot3", "left1", "left2", "top1" }) }, { "Library_08", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Library_09", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Library_14", new SceneConfig(new List<string> { "left1" }) }, { "Library_01", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2" }) }, { "Library_15", new SceneConfig(new List<string> { "right1" }) }, { "Library_03", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Song_24", new SceneConfig(new List<string> { "right1" }) }, { "Song_20b", new SceneConfig(new List<string> { "bot1", "left2", "left4", "right2", "right3", "top1" }) }, { "Library_02", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2" }) }, { "Song_29", new SceneConfig(new List<string> { "right1" }) }, { "Arborium_01", new SceneConfig(new List<string> { "bot1", "left1", "left2", "left3", "right1", "right2", "right3", "right4", "right5" }) }, { "Cog_10", new SceneConfig(new List<string> { "bot1" }) }, { "Cog_07", new SceneConfig(new List<string> { "left1" }) }, { "Cog_06", new SceneConfig(new List<string> { "left2", "right1" }) }, { "Arborium_04", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Arborium_03", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "right1", "right2" }) }, { "Arborium_02", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Arborium_05", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Arborium_06", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Arborium_09", new SceneConfig(new List<string> { "right1", "right2" }) }, { "Arborium_Tube", new SceneConfig(new List<string> { "right1" }) }, { "Arborium_07", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Arborium_08", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Song_13", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Song_18", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Song_03", new SceneConfig(new List<string> { "bot1", "top1" }) }, { "Song_04", new SceneConfig(new List<string> { "bot1", "left1", "right1", "right2" }) }, { "Song_10", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Song_12", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "right1", "right2", "right3" }) }, { "Song_14", new SceneConfig(new List<string> { "left1" }) }, { "Song_26", new SceneConfig(new List<string> { "right1" }) }, { "Song_28", new SceneConfig(new List<string> { "right1" }) }, { "Song_08", new SceneConfig(new List<string> { "right1" }) }, { "Slab_01", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Slab_02", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Slab_03", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "left5", "left6", "left7", "left8", "right1", "right2", "right3", "right4", "right5", "right7", "right8", "right9" }) }, { "Slab_04", new SceneConfig(new List<string> { "bot1", "right1", "top1" }) }, { "Slab_23", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Slab_21", new SceneConfig(new List<string> { "left1", "left3", "top1" }) }, { "Slab_22", new SceneConfig(new List<string> { "bot1", "bot2" }) }, { "Slab_Cell_Creature", new SceneConfig(new List<string> { "left1" }) }, { "Slab_20", new SceneConfig(new List<string> { "left1" }) }, { "Slab_17", new SceneConfig(new List<string> { "left1" }) }, { "Slab_18", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Slab_16", new SceneConfig(new List<string> { "bot1", "left1", "right1", "top1" }) }, { "Slab_15", new SceneConfig(new List<string> { "bot1", "left1", "right1", "top1" }) }, { "Peak_01", new SceneConfig(new List<string> { "left1", "left2", "left3", "left4", "right1", "right2", "right3", "right4", "top1", "top2", "top3", "top4" }) }, { "Slab_14", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Slab_13", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Slab_05", new SceneConfig(new List<string> { "bot1", "right1", "top1" }) }, { "Slab_06", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Peak_07", new SceneConfig(new List<string> { "bot1", "bot2", "bot3", "bot4", "bot5", "top1", "top2" }) }, { "Peak_08b", new SceneConfig(new List<string> { "bot4", "bot5", "bot6", "left1", "left2" }) }, { "Peak_08", new SceneConfig(new List<string> { "bot1", "right1", "top1" }) }, { "Peak_05d", new SceneConfig(new List<string> { "bot1" }) }, { "Peak_05", new SceneConfig(new List<string> { "bot1", "right3", "top2" }) }, { "Peak_05c", new SceneConfig(new List<string> { "left2", "right1" }) }, { "Peak_05e", new SceneConfig(new List<string> { "left1", "right1", "right2" }) }, { "Peak_06b", new SceneConfig(new List<string> { "left1" }) }, { "Peak_02", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3", "right4" }) }, { "Peak_04d", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Peak_04", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Bellway_Peak", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "top1" }) }, { "Bellway_Peak_02", new SceneConfig(new List<string> { "left1" }) }, { "Peak_04c", new SceneConfig(new List<string> { "right1", "right2" }) }, { "Peak_10", new SceneConfig(new List<string> { "right1" }) }, { "Slab_08", new SceneConfig(new List<string> { "left1" }) }, { "Slab_Cell_Quiet", new SceneConfig(new List<string> { "left1", "left2" }) }, { "Slab_19b", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Slab_07", new SceneConfig(new List<string> { "right1", "right2" }) }, { "Slab_12", new SceneConfig(new List<string> { "left1" }) }, { "Slab_10c", new SceneConfig(new List<string> { "left1" }) }, { "Slab_10b", new SceneConfig(new List<string> { "left1" }) }, { "Cog_10_Destroyed", new SceneConfig(new List<string> { "bot1", "left1" }) }, { "Cog_09_Destroyed", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Song_Tower_Destroyed", new SceneConfig(new List<string> { "bot1", "top1" }) }, { "Arborium_10", new SceneConfig(new List<string> { "left1" }) }, { "Arborium_11", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Aqueduct_01", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Aqueduct_02", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3" }) }, { "Bellway_Aqueduct", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Aqueduct_07", new SceneConfig(new List<string> { "right1" }) }, { "Aqueduct_04", new SceneConfig(new List<string> { "bot1", "right1" }) }, { "Aqueduct_03", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Aqueduct_06", new SceneConfig(new List<string> { "bot1", "left1", "left2" }) }, { "Aqueduct_08", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Aqueduct_05", new SceneConfig(new List<string> { "left1" }) }, { "Shadow_01", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1", "right2", "right3", "top1" }) }, { "Shadow_18", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shadow_12", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shadow_19", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2" }) }, { "Shadow_24", new SceneConfig(new List<string> { "left1" }) }, { "Shadow_10", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Shadow_25", new SceneConfig(new List<string> { "left1" }) }, { "Shadow_08", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Shadow_27", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shadow_26", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2" }) }, { "Shadow_16", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shadow_15", new SceneConfig(new List<string> { "right1", "right2" }) }, { "Shadow_14", new SceneConfig(new List<string> { "right1", "right2" }) }, { "Shadow_02", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "right3" }) }, { "Shadow_11", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shadow_13", new SceneConfig(new List<string> { "left1" }) }, { "Shadow_23", new SceneConfig(new List<string> { "left1" }) }, { "Shadow_03", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Shadow_21", new SceneConfig(new List<string> { "bot1" }) }, { "Shadow_09", new SceneConfig(new List<string> { "left1", "left2", "left3", "right1" }) }, { "Shadow_Weavehome", new SceneConfig(new List<string> { "left1" }) }, { "Shadow_05", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shadow_04b", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Shadow_04", new SceneConfig(new List<string> { "left1", "right1", "right2", "top1" }) }, { "Shadow_20", new SceneConfig(new List<string> { "bot1", "top1" }) }, { "Bellway_Shadow", new SceneConfig(new List<string> { "left1" }) }, { "Tube_Hub", new SceneConfig(new List<string> { "left1", "left3", "left4" }) }, { "Cradle_01", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Cradle_02", new SceneConfig(new List<string> { "left2", "right1", "right2" }) }, { "Cradle_02b", new SceneConfig(new List<string> { "right1" }) }, { "Cradle_03", new SceneConfig(new List<string> { "left2", "right2" }) }, { "Crawl_04", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Crawl_02", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "right3" }) }, { "Crawl_06", new SceneConfig(new List<string> { "left1" }) }, { "Crawl_01", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Crawl_03", new SceneConfig(new List<string> { "bot1", "left1", "right1", "top1" }) }, { "Crawl_08", new SceneConfig(new List<string> { "bot1" }) }, { "Crawl_05", new SceneConfig(new List<string> { "right1" }) }, { "Crawl_03b", new SceneConfig(new List<string> { "bot1", "right1", "top1" }) }, { "Crawl_07", new SceneConfig(new List<string> { "bot1", "left1", "top1" }) }, { "Crawl_09", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Crawl_10", new SceneConfig(new List<string> { "right1" }) }, { "Abyss_12", new SceneConfig(new List<string> { "left1", "right2" }) }, { "Abyss_05", new SceneConfig(new List<string> { "left2", "right1" }) }, { "Abyss_08", new SceneConfig(new List<string> { "left1" }) }, { "Abyss_07", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Abyss_01", new SceneConfig(new List<string> { "left1", "right2", "right3", "right4" }) }, { "Abyss_06", new SceneConfig(new List<string> { "right1" }) }, { "Abyss_04", new SceneConfig(new List<string> { "left1" }) }, { "Abyss_02b", new SceneConfig(new List<string> { "left2", "right1", "top1" }) }, { "Abyss_02", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Abyss_03", new SceneConfig(new List<string> { "left1", "left2" }) }, { "Abyss_13", new SceneConfig(new List<string> { "left1", "right1", "top1" }) }, { "Abyss_11", new SceneConfig(new List<string> { "bot1", "right1" }) }, { "Abyss_09", new SceneConfig(new List<string> { "bot1", "top1" }) }, { "Greymoor_13", new SceneConfig(new List<string> { "bot1", "left1", "right1" }) }, { "Clover_01b", new SceneConfig(new List<string> { "right1" }) }, { "Clover_02c", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Clover_05c", new SceneConfig(new List<string> { "left1", "left2", "right1", "right2", "right3" }) }, { "Clover_21", new SceneConfig(new List<string> { "right1" }) }, { "Clover_16", new SceneConfig(new List<string> { "right1", "top1" }) }, { "Clover_06", new SceneConfig(new List<string> { "bot1", "bot2" }) }, { "Clover_19", new SceneConfig(new List<string> { "left1", "top1" }) }, { "Clover_04b", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Clover_11", new SceneConfig(new List<string> { "right1" }) }, { "Clover_03", new SceneConfig(new List<string> { "left1", "left2", "right1" }) }, { "Clover_18", new SceneConfig(new List<string> { "left1" }) }, { "Tut_04", new SceneConfig(new List<string> { "left1", "right1" }) }, { "Cog_09", new SceneConfig(new List<string> { "bot1" }) }, { "Cog_08", new SceneConfig(new List<string> { "bot1", "top1" }) } }; internal readonly Dictionary<string, SceneConfig> sceneConfigs = new Dictionary<string, SceneConfig>(StringComparer.OrdinalIgnoreCase); private string lastEntryGateUsed; private string previousSceneName; private string currentSceneName = "(unknown)"; private bool isTransitioning; private bool loadRequested; public static bool SuppressTransitionPatch; private bool autoDiscoveryMode; private HashSet<string> discoveredScenes = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private string discoveryFilePath; private readonly List<string> preferredSceneSubstrings = new List<string>(); private List<string> _cachedPreferredLowered; private WaitForSeconds waitHalfSecond; private WaitForSeconds waitThirdSecond; private WaitForSeconds waitTenthSecond; private WaitForSeconds waitFifthSecond; private GUIStyle sceneLabelStyle; private string cachedSceneLabel = ""; private string lastRenderedScene = ""; private ConfigEntry<bool> cfgShowSceneLabel; private ConfigEntry<string> cfgTeleportScene; private ConfigEntry<bool> cfgTeleportConfirm; private HashSet<string> visitedScenesF6 = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public static bool EnableRandomization = false; private ConfigEntry<bool> cfgEnableRandomization; private ConfigEntry<bool> cfgInstantMusicTransition; private bool _apiInitialized; public static int CurrentSeed { get; internal set; } = 0; private void BuildSceneConfigs() { sceneConfigs.Clear(); try { Dictionary<string, List<string>> randomizableSceneExits = VanillaExitMap.GetRandomizableSceneExits(); if (randomizableSceneExits != null && randomizableSceneExits.Count > 0) { int num = 0; int num2 = 0; foreach (KeyValuePair<string, List<string>> item in randomizableSceneExits) { sceneConfigs[item.Key] = new SceneConfig(new List<string>(item.Value)); num += item.Value.Count; foreach (string item2 in item.Value) { if (item2.StartsWith("door", StringComparison.OrdinalIgnoreCase)) { num2++; } } } log.LogInfo($"[SceneConfigs] 由 Core 出口表构建:{sceneConfigs.Count} 场景 / {num} 出口(含 {num2} 个 door* 动态门)"); return; } } catch (Exception ex) { log.LogWarning("[SceneConfigs] 读取 Core 出口表失败,回退内置表:" + ex.Message); } foreach (KeyValuePair<string, SceneConfig> fallbackSceneConfig in FallbackSceneConfigs) { sceneConfigs[fallbackSceneConfig.Key] = fallbackSceneConfig.Value; } log.LogWarning($"[SceneConfigs] 使用内置回退表:{sceneConfigs.Count} 场景(不含 door*)"); } private void Awake() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Expected O, but got Unknown //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Expected O, but got Unknown ModLog.SetFallback(((BaseUnityPlugin)this).Logger); BuildSceneConfigs(); rng = new Random(); Scene activeScene = SceneManager.GetActiveScene(); currentSceneName = ((Scene)(ref activeScene)).name; waitHalfSecond = new WaitForSeconds(0.5f); waitThirdSecond = new WaitForSeconds(0.3f); waitTenthSecond = new WaitForSeconds(0.1f); waitFifthSecond = new WaitForSeconds(0.2f); sceneLabelStyle = new GUIStyle(); cfgShowSceneLabel = GlobalConfig.ShowSceneLabel; cfgTeleportScene = GlobalConfig.TeleportScene; cfgTeleportConfirm = GlobalConfig.TeleportConfirm; cfgEnableRandomization = GlobalConfig.EnableRandomization; EnableRandomization = cfgEnableRandomization.Value; cfgInstantMusicTransition = GlobalConfig.InstantMusicTransition; discoveryFilePath = Path.Combine(Paths.PluginPath, "discovered_exits.txt"); log.LogInfo("RandomSceneLoader loaded. Current scene: " + currentSceneName + ". F5=random, F7=discover"); try { if (sceneConfigs != null) { discoveredScenes.UnionWith(sceneConfigs.Keys); log.LogInfo($"Preloaded {discoveredScenes.Count} known scenes into discovered set"); } } catch { } if (autoDiscoveryMode) { log.LogInfo("Auto-discovery mode enabled. RoomRando disabled. Results saved to: " + discoveryFilePath); return; } try { new Harmony("HardItemRandomizer.HKSilksong_SceneRandomizer").PatchAll(); log.LogInfo("Harmony patches applied successfully"); } catch (Exception ex) { log.LogError("Failed to apply Harmony patches: " + ex.Message); } try { if ((Object)(object)GameObject.Find("__RoomRando") == (Object)null) { GameObject val = new GameObject("__RoomRando"); val.AddComponent<RoomRando>().Initialize(this); Object.DontDestroyOnLoad((Object)val); } } catch (Exception ex2) { log.LogError("Failed to create RoomRando: " + ex2.Message); } try { if ((Object)(object)GameObject.Find("__SeedManager") == (Object)null) { GameObject val2 = new GameObject("__SeedManager"); val2.AddComponent<SeedManager>().Initialize(this); Object.DontDestroyOnLoad((Object)val2); } } catch (Exception ex3) { log.LogError("Failed to create SeedManager: " + ex3.Message); } GameObject obj2 = GameObject.Find("__RoomRando"); RoomRando rando = ((obj2 != null) ? obj2.GetComponent<RoomRando>() : null); HKSilksong_RandomizerAPI.Initialize(this, rando); SceneManager.sceneLoaded += OnSceneLoaded; SceneManager.activeSceneChanged += OnActiveSceneChanged; _apiInitialized = true; } private void OnDestroy() { SceneManager.sceneLoaded -= OnSceneLoaded; SceneManager.activeSceneChanged -= OnActiveSceneChanged; ModLog.Shutdown(); } public string GetCurrentSceneName() { return currentSceneName; } public void SetShowSceneLabel(bool show) { if (cfgShowSceneLabel != null) { cfgShowSceneLabel.Value = show; } } public bool GetShowSceneLabel() { return cfgShowSceneLabel?.Value ?? true; } public void SetLastEntryGate(string gateName) { lastEntryGateUsed = gateName; } public void TeleportToScene(string sceneName) { try { if (isTransitioning) { log.LogInfo("Teleport skipped: transition already in progress"); return; } if (string.IsNullOrWhiteSpace(sceneName)) { log.LogWarning("TeleportToScene called with empty scene name"); return; } string text = null; string scenePart = sceneName.Trim(); int num = scenePart.LastIndexOf(' '); if (num > 0) { text = scenePart.Substring(num + 1).Trim(); scenePart = scenePart.Substring(0, num).Trim(); if (string.IsNullOrEmpty(text)) { text = null; } } string text2 = null; SceneConfig value = null; string text3 = null; if (sceneConfigs != null && sceneConfigs.TryGetValue(scenePart, out value)) { text3 = scenePart; } else if (sceneConfigs != null) { List<string> source = sceneConfigs.Keys.ToList(); string inputLetters = new string(scenePart.Where(char.IsLetter).ToArray()); string inputDigits = new string(scenePart.Where(char.IsDigit).ToArray()); text3 = source.FirstOrDefault((string s) => string.Equals(s, scenePart, StringComparison.OrdinalIgnoreCase)); if (text3 == null && !string.IsNullOrEmpty(inputLetters) && !string.IsNullOrEmpty(inputDigits)) { text3 = source.FirstOrDefault(delegate(string s) { string text4 = new string(s.Where(char.IsDigit).ToArray()); string text5 = new string(s.Where(char.IsLetter).ToArray()); return !string.IsNullOrEmpty(text4) && text5.IndexOf(inputLetters, StringComparison.OrdinalIgnoreCase) >= 0 && text4.IndexOf(inputDigits, StringComparison.OrdinalIgnoreCase) >= 0; }); } if (text3 == null && !string.IsNullOrEmpty(inputLetters) && string.IsNullOrEmpty(inputDigits)) { text3 = source.FirstOrDefault((string s) => string.IsNullOrEmpty(new string(s.Where(char.IsDigit).ToArray())) && s.IndexOf(inputLetters, StringComparison.OrdinalIgnoreCase) >= 0); } if (text3 == null) { text3 = source.FirstOrDefault((string s) => s.IndexOf(scenePart, StringComparison.OrdinalIgnoreCase) >= 0); } } if (text3 != null && sceneConfigs.TryGetValue(text3, out value)) { if (text != null) { if (value.Exits != null && value.Exits.Contains<string>(text, StringComparer.OrdinalIgnoreCase)) { text2 = text; } else { log.LogWarning("TeleportToScene: entry '" + text + "' not valid for scene '" + text3 + "', will pick random."); if (value.Exits != null && value.Exits.Count > 0) { text2 = value.Exits[rng.Next(value.Exits.Count)]; } } } else if (value.Exits != null && value.Exits.Count > 0) { text2 = value.Exits[rng.Next(value.Exits.Count)]; } log.LogInfo("Teleport: " + scenePart + " -> " + text3 + " (entry '" + (text2 ?? "(null)") + "')"); } else { log.LogWarning("TeleportToScene: scene '" + scenePart + "' not found in sceneConfigs. Attempting direct load."); text3 = scenePart; if (text != null) { text2 = text; } } SuppressTransitionPatch = true; ((MonoBehaviour)this).StartCoroutine(LoadSceneCoroutine(text3, text2)); } catch (Exception arg) { log.LogError($"TeleportToScene failed: {arg}"); } } private List<string> GetCachedPreferredLowered() { if (_cachedPreferredLowered == null) { _cachedPreferredLowered = (from s in preferredSceneSubstrings where !string.IsNullOrWhiteSpace(s) select s.ToLower()).ToList(); } return _cachedPreferredLowered; } private void LoadRandomUniqueScene() { if (isTransitioning) { log.LogInfo("LoadRandomUniqueScene skipped: transition already in progress"); return; } List<string> list = sceneConfigs.Keys.Where((string k) => !string.Equals(k, currentSceneName, StringComparison.OrdinalIgnoreCase) && !visitedScenesF6.Contains(k)).ToList(); if (list.Count == 0) { log.LogInfo("F6: All scenes have been visited already (or no candidates available). Clearing visited list."); visitedScenesF6.Clear(); list = sceneConfigs.Keys.Where((string k) => !string.Equals(k, currentSceneName, StringComparison.OrdinalIgnoreCase)).ToList(); if (list.Count == 0) { return; } } List<string> list2 = null; try { List<string> lowered = GetCachedPreferredLowered(); list2 = list.Where((string c) => lowered.Any((string sub) => c.ToLower().Contains(sub))).ToList(); } catch { } List<string> list3 = ((list2 != null && list2.Count > 0) ? list2 : list); string text = list3[rng.Next(list3.Count)]; SceneConfig sceneConfig = (sceneConfigs.ContainsKey(text) ? sceneConfigs[text] : null); string text2 = null; if (sceneConfig != null && sceneConfig.Exits != null && sceneConfig.Exits.Count > 0) { text2 = sceneConfig.Exits[rng.Next(sceneConfig.Exits.Count)]; } visitedScenesF6.Add(text); lastEntryGateUsed = text2; log.LogInfo("[F6] Selected unique random scene: " + text + " (enter via gate '" + (text2 ?? "(null)") + "')"); SuppressTransitionPatch = true; ((MonoBehaviour)this).StartCoroutine(LoadSceneCoroutine(text, text2)); } private void LoadRandomScene() { if (isTransitioning) { log.LogInfo("LoadRandomScene skipped: transition already in progress"); return; } loadRequested = true; List<string> list = sceneConfigs.Keys.Where((string k) => !string.Equals(k, currentSceneName, StringComparison.OrdinalIgnoreCase)).ToList(); if (list.Count == 0) { log.LogWarning("No candidate scenes found in sceneConfigs."); return; } List<string> list2 = null; try { List<string> lowered = GetCachedPreferredLowered(); list2 = list.Where((string c) => lowered.Any((string sub) => c.ToLower().Contains(sub))).ToList(); } catch { } List<string> list3 = ((list2 != null && list2.Count > 0) ? list2 : list); string text = list3[rng.Next(list3.Count)]; SceneConfig sceneConfig = (sceneConfigs.ContainsKey(text) ? sceneConfigs[text] : null); string text2 = null; if (sceneConfig != null && sceneConfig.Exits != null && sceneConfig.Exits.Count > 0) { text2 = sceneConfig.Exits[rng.Next(sceneConfig.Exits.Count)]; } lastEntryGateUsed = text2; log.LogInfo("Selected random scene: " + text + " (enter via gate '" + (text2 ?? "(null)") + "')"); SuppressTransitionPatch = true; ((MonoBehaviour)this).StartCoroutine(LoadSceneCoroutine(text, text2)); } private IEnumerator LoadSceneCoroutine(string sceneName, string entryGate) { if (!isTransitioning) { loadRequested = false; isTransitioning = true; lastEntryGateUsed = entryGate; float timeout = 8f; float startTime = Time.time; if (!string.IsNullOrEmpty(sceneName) && (Object)(object)GameManager.instance != (Object)null) { try { GameManager.instance.BeginSceneTransition(new SceneLoadInfo { SceneName = sceneName, EntryGateName = entryGate, PreventCameraFadeOut = false, WaitForSceneTransitionCameraFade = true, Visualization = (SceneLoadVisualizations)0 }); } catch (Exception ex) { log.LogWarning("BeginSceneTransition failed: " + ex.Message); isTransitioning = false; SuppressTransitionPatch = false; yield break; } while (true) { Scene activeScene = SceneManager.GetActiveScene(); if (!(((Scene)(ref activeScene)).name != sceneName)) { break; } if (Time.time - startTime > timeout) { log.LogWarning("LoadSceneCoroutine timeout waiting for scene " + sceneName); isTransitioning = false; SuppressTransitionPatch = false; yield break; } yield return waitTenthSecond; } yield return waitFifthSecond; isTransitioning = false; } else { try { SceneManager.LoadScene(sceneName); } catch (Exception ex2) { log.LogWarning("SceneManager.LoadScene failed: " + ex2.Message); } finally { isTransitioning = false; } } } SuppressTransitionPatch = false; } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { currentSceneName = ((Scene)(ref scene)).name; cachedSceneLabel = Locale.Get("Scene: ") + currentSceneName; lastRenderedScene = currentSceneName; log.LogInfo("Scene loaded: " + currentSceneName); if (autoDiscoveryMode) { ((MonoBehaviour)this).StartCoroutine(AutoDiscoverAfterLoad()); } else { ((MonoBehaviour)this).StartCoroutine(DetectEntryGateAfterLoad()); } if (cfgInstantMusicTransition != null && cfgInstantMusicTransition.Value) { SetMusicRegionsInstantTransition(); } if (_apiInitialized && ((Scene)(ref scene)).name != "Menu_Title" && ((Scene)(ref scene)).name != "Menu" && ((Scene)(ref scene)).name != "Loading" && (Object)(object)HeroController.instance != (Object)null) { HKSilksong_RandomizerAPI.MarkGameReady(); } } private IEnumerator AutoDiscoverAfterLoad() { yield return waitHalfSecond; DiscoverGatesInCurrentScene(); } private void DiscoverGatesInCurrentScene() { //IL_0100: Unknown result type (might be due to invalid IL or missing references) log.LogInfo("=== DISCOVERING GATES ==="); log.LogInfo("Scene: " + currentSceneName); try { List<GameObject> list = Object.FindObjectsByType<GameObject>((FindObjectsSortMode)0).Where(delegate(GameObject obj) { string text2 = ((Object)obj).name.ToLower(); return (text2.StartsWith("left") || text2.StartsWith("right") || text2.StartsWith("top") || text2.StartsWith("bot")) && text2.Length <= 6 && char.IsDigit(text2[text2.Length - 1]); }).ToList(); log.LogInfo($"Found {list.Count} gates:"); IOrderedEnumerable<IGrouping<string, GameObject>> orderedEnumerable = from g in list group g by ((Object)g).name into g orderby g.Key select g; foreach (IGrouping<string, GameObject> item in orderedEnumerable) { log.LogInfo($" - {item.Key} (count: {item.Count()}, pos: {item.First().transform.position})"); } List<string> list2 = orderedEnumerable.Select((IGrouping<string, GameObject> g) => g.Key).ToList(); if (list2.Count > 0) { string text = "{ \"" + currentSceneName + "\", new SceneConfig(new List<string> { " + string.Join(", ", list2.Select((string e) => "\"" + e + "\"")) + " }) },"; log.LogInfo("Suggested: " + text); if (autoDiscoveryMode) { SaveDiscoveryToFile(currentSceneName, list2, text); } } } catch (Exception ex) { log.LogError("DiscoverGates failed: " + ex.Message); } } private void SaveDiscoveryToFile(string sceneName, List<string> exitNames, string configLine) { try { if (!discoveredScenes.Contains(sceneName)) { if (sceneConfigs != null && sceneConfigs.ContainsKey(sceneName)) { log.LogInfo("Discovery skipped for " + sceneName + ": already exists in sceneConfigs."); discoveredScenes.Add(sceneName); return; } discoveredScenes.Add(sceneName); File.AppendAllText(discoveryFilePath, string.Format("\n[{0:yyyy-MM-dd HH:mm:ss}] {1}\n Gates found: {2}\n Config: {3}\n", DateTime.Now, sceneName, string.Join(", ", exitNames), configLine)); log.LogInfo($"Saved discovery for {sceneName} to file ({exitNames.Count} exits)"); } } catch (Exception ex) { log.LogError("Failed to save discovery to file: " + ex.Message); } } private IEnumerator DetectEntryGateAfterLoad() { yield return waitThirdSecond; try { HeroController instance = HeroController.instance; if ((Object)(object)instance == (Object)null) { yield break; } Vector3 position = ((Component)instance).transform.position; GameObject[] array = Object.FindObjectsByType<GameObject>((FindObjectsSortMode)0); foreach (GameObject val in array) { string text = ((Object)val).name.ToLower(); if ((text.StartsWith("left") || text.StartsWith("right") || text.StartsWith("top") || text.StartsWith("bot")) && text.Length <= 6 && char.IsDigit(text[text.Length - 1]) && (double)Vector3.Distance(position, val.transform.position) < 10.0) { log.LogInfo("Nearby gate after load: " + ((Object)val).name + "(仅诊断,不参与跃迁)"); break; } } } catch (Exception ex) { log.LogWarning("DetectEntryGate failed: " + ex.Message); } } private void OnActiveSceneChanged(Scene prev, Scene next) { if (((Scene)(ref next)).name == "Menu_Title" || ((Scene)(ref next)).name == "Quit_To_Menu") { lastEntryGateUsed = null; return; } previousSceneName = currentSceneName; currentSceneName = ((Scene)(ref next)).name; lastEntryGateUsed = null; } private void OnGUI() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) try { if (sceneLabelStyle.normal.textColor != Color.white || sceneLabelStyle.fontSize != 14) { GUIStyle val = new GUIStyle(GUI.skin.label); val.normal.textColor = Color.white; val.fontSize = 14; sceneLabelStyle = val; } if (cfgShowSceneLabel == null || cfgShowSceneLabel.Value) { if (currentSceneName != lastRenderedScene) { cachedSceneLabel = Locale.Get("Scene: ") + currentSceneName; lastRenderedScene = currentSceneName; } GUI.Label(new Rect(8f, 8f, 300f, 20f), cachedSceneLabel, sceneLabelStyle); } } catch { } } private void SetMusicRegionsInstantTransition() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) try { Type type = Type.GetType("MusicRegion, Assembly-CSharp"); if (type == null) { return; } Object[] array = Resources.FindObjectsOfTypeAll(type); FieldInfo field = type.GetField("enterTransitionTime"); FieldInfo field2 = type.GetField("exitTransitionTime"); FieldInfo field3 = type.GetField("delay"); if (field == null || field2 == null) { return; } int num = 0; Object[] array2 = array; foreach (Object val in array2) { if (val == (Object)null) { continue; } Object obj = ((val is Component) ? val : null); GameObject val2 = ((obj != null) ? ((Component)obj).gameObject : null); if ((Object)(object)val2 != (Object)null && val2.scene == SceneManager.GetActiveScene()) { field.SetValue(val, 0f); field2.SetValue(val, 0f); if (field3 != null) { field3.SetValue(val, 0); } num++; } } if (num > 0) { log.LogInfo($"Set {num} MusicRegion transition times to 0."); } } catch (Exception ex) { log.LogWarning("SetMusicRegionsInstantTransition error: " + ex.Message); } } } public sealed class ModLog { private const int FlushThreshold = 4096; private static readonly Dictionary<string, ModLog> _byTag; private static readonly object _registryGate; private static ManualLogSource _fallback; private static bool _closed; private readonly string _tag; private readonly object _gate = new object(); private readonly StringBuilder _buffer = new StringBuilder(5120); private StreamWriter _writer; private bool _broken; private static ModLog _default; private static ModLog DefaultInstance { get { ModLog modLog = _default; if (modLog != null) { return modLog; } return _default = For(typeof(ModLog).Assembly.GetName().Name); } } private ModLog(string tag) { _tag = tag; } public static ModLog For(string tag) { lock (_registryGate) { if (_byTag.TryGetValue(tag, out var value)) { return value; } value = new ModLog(tag); _byTag[tag] = value; return value; } } public static void SetFallback(ManualLogSource source) { _fallback = source; } public static void Shutdown() { lock (_registryGate) { _closed = true; foreach (KeyValuePair<string, ModLog> item in _byTag) { item.Value.Close(); } _byTag.Clear(); } } static ModLog() { _byTag = new Dictionary<string, ModLog>(4); _registryGate = new object(); try { AppDomain.CurrentDomain.ProcessExit += delegate { Shutdown(); }; AppDomain.CurrentDomain.DomainUnload += delegate { Shutdown(); }; } catch { } } public void LogInfo(object message) { Write("INFO ", message); } public void LogWarning(object message) { Write("WARN ", message); } public void LogError(object message) { Write("ERROR", message); } public void LogDebug(object message) { Write("DEBUG", message); } public void LogMessage(object message) { Write("INFO ", message); } public static void Info(object message) { DefaultInstance.LogInfo(message); } public static void Warning(object message) { DefaultInstance.LogWarning(message); } public static void Error(object message) { DefaultInstance.LogError(message); } public static void Debug(object message) { DefaultInstance.LogDebug(message); } private void Write(string level, object message) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (message == null) { return; } string text = message as string; if (text == null) { text = message.ToString(); } if (string.IsNullOrEmpty(text)) { return; } lock (_gate) { if (_closed) { return; } if (_broken) { if (_fallback != null) { _fallback.Log(LevelOf(level), (object)text); } return; } _buffer.Append(DateTime.Now.ToString("HH:mm:ss.fff")); _buffer.Append(" [").Append(level).Append("] "); _buffer.Append(text); _buffer.Append('\n'); if (_buffer.Length >= 4096 || level == "ERROR") { FlushLocked(); } } } private void FlushLocked() { if (_buffer.Length == 0) { return; } try { if (_writer == null) { OpenLocked(); } _writer.Write(_buffer.ToString()); _writer.Flush(); _buffer.Length = 0; } catch (Exception ex) { _broken = true; _buffer.Length = 0; if (_fallback != null) { _fallback.LogWarning((object)("[ModLog] 写入日志文件失败,后续日志回退到 BepInEx 日志: " + ex.Message)); } } } private void OpenLocked() { string text = Path.Combine(Paths.ConfigPath, "SilksongItemRandomizer", "logs"); Directory.CreateDirectory(text); string path = _tag + ".log"; FileStream stream = new FileStream(Path.Combine(text, path), FileMode.Create, FileAccess.Write, FileShare.ReadWrite); _writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); _writer.AutoFlush = false; } private void Close() { lock (_gate) { if (_buffer.Length > 0 && !_broken) { FlushLocked(); } if (_writer != null) { try { _writer.Flush(); _writer.Dispose(); } catch { } _writer = null; } _buffer.Length = 0; } } private static LogLevel LevelOf(string level) { return (LogLevel)(level switch { "ERROR" => 2, "WARN " => 4, "DEBUG" => 32, _ => 16, }); } } public class RoomRando : MonoBehaviour { private Dictionary<string, (string targetScene, string targetGate)> connections = new Dictionary<string, (string, string)>(StringComparer.OrdinalIgnoreCase); private List<string> availableScenes = new List<string>(); private bool enableRandomization = true; private RandomSceneLoader sceneLoader; private Random rng; private int generationSeed; private bool enableMapGeneration; private List<(string beforeScene, string afterScene)> precedencePairs = new List<(string, string)>(); private static readonly HashSet<string> BlacklistedExits = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Bone_11_top1", "Bellshrine_right1", "Bellshrine_05_right1", "Dock_06_Church_right1", "Bone_East_09_top1", "Bellshrine_02_left1", "Dust_04_right1", "Dust_05_right1", "Dust_06_left1", "Shadow_20_bot1", "Bellshrine_03_right1", "Shellwood_19_left1", "Shellwood_01b_right2", "Bellshrine_02_right1", "Dust_06_right1", "Mosstown_03_top1", "Coral_10_left1", "Song_27_left1", "Dock_01_right1", "Dock_01_right2", "Bone_East_14_right1", "Bone_East_14_right2", "Greymoor_01_right1", "Greymoor_01_right2", "Dust_02_right1", "Dust_02_right2", "Dust_04_left1", "Dust_04_left2", "Song_25_top1", "Song_25_top2", "Arborium_05_top1", "Hang_07_top1", "Hang_07_left1", "Slab_02_left1", "Slab_05_right1", "Cog_06_right1", "Library_11b_right1", "Dock_03_bot1", "Dock_03c_top1", "Dock_03c_left2", "Dock_02_left1", "Shellwood_02_right2", "Shellwood_01_left2", "Dust_Chef_left1", "Song_11_left4", "Slab_03_right1", "Slab_03_right2", "Slab_03_right5", "Slab_03_right7", "Slab_03_left6", "Under_05_left2", "Under_02_right4", "Under_02_left1", "Bone_East_12_right1", "Shadow_27_right1", "Halfway_01_right1", "Wisp_03_top1", "Arborium_01_right1", "Arborium_04_left1", "Library_13_left1", "Hang_03_right2", "Aqueduct_02_right3", "Song_19_entrance_left1", "Weave_04_right2", "Slab_16_right1", "Bone_East_04_left1", "Bone_East_10_right1", "Bone_East_18c_left1", "Greymoor_05_left1", "Hang_08_left1", "Arborium_08_left1" }; private static readonly Dictionary<string, int> SingleExitPairedCounts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); private static readonly HashSet<string> HighPriorityRooms = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Bonegrave", "Shellwood_04c", "Coral_02", "Coral_35", "Coral_32", "Coral_24", "Coral_23", "Coral_25", "Dust_03", "Dust_06", "Shadow_05", "Shadow_08", "Shadow_09", "Shadow_16", "Shadow_10", "Shadow_19", "Shadow_24", "Shadow_01", "Shadow_14", "Aqueduct_04", "Aqueduct_03", "Aqueduct_01", "Arborium_11", "Arborium_09", "Arborium_05", "Song_Enclave", "Song_09b", "Song_11", "Song_01", "Song_19_entrance", "Under_02", "Under_07c", "Under_27", "Under_17", "Under_10", "Under_19c", "Library_11", "Library_12", "Library_12b", "Library_02", "Song_20b", "Song_20", "Library_03", "Slab_06", "Slab_05", "Slab_19b", "Slab_15", "Coral_27", "Coral_44", "Abyss_13", "Abyss_01", "Cog_08", "Cog_09", "Ward_02", "Wisp_05", "Wisp_08", "Slab_07", "Weave_08", "Song_03", "Abyss_05", "Cradle_02", "Hang_02", "Hang_03", "Hang_13", "Hang_10", "Hang_16", "Bone_East_15", "Cog_04", "Arborium_08", "Under_23", "Bellway_03", "Dock_15", "Dust_04" }; private static readonly HashSet<string> SkipExits = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Bone_01_bot1", "Bone_01_left4", "Bone_01_right3", "Aspid_01_bot8", "Aspid_01_left2", "Aspid_01_right4", "Crawl_03b_right1", "Shellwood_10_left3", "Shellwood_10_right3", "Dust_02_left2", "Dust_02_right2", "Coral_24_left1", "Coral_24_right1", "Coral_35b_bot1", "Coral_35b_left5", "Coral_35b_right2", "Peak_07_bot5", "Peak_07_top2", "Peak_01_left4", "Peak_01_right4", "Peak_01_top4", "Peak_02_left3", "Peak_02_right4", "Peak_04_left1", "Peak_04_right1", "Peak_05_bot1", "Peak_05_right3", "Peak_05_top2", "Peak_05c_left2", "Peak_05c_right1", "Peak_05e_left1", "Peak_05e_right2", "Song_05_left5", "Song_05_right4", "Song_11_right3", "Song_01c" }; private RoomRandomConfig _cachedConfig; private bool _hasPendingConfig; private bool _isInitialized; private Dictionary<string, HashSet<string>> _blacklistedExitsByScene; private Dictionary<string, int> _cachedActualExitCounts; private bool _layoutManagedBySIR; private static readonly HashSet<string> Tut01RestrictedExits = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private bool RegionModeEnabled { get { if (_cachedConfig != null) { return _cachedConfig.Mode == 1; } return false; } } public void Initialize(RandomSceneLoader loader) { sceneLoader = loader; if ((Object)(object)sceneLoader != (Object)null) { foreach (string key in sceneLoader.sceneConfigs.Keys) { if (key.StartsWith("Peak_", StringComparison.OrdinalIgnoreCase)) { HighPriorityRooms.Add(key); } if (key.StartsWith("Ward_", StringComparison.OrdinalIgnoreCase)) { HighPriorityRooms.Add(key); } if (key.StartsWith("Clover_", StringComparison.OrdinalIgnoreCase)) { HighPriorityRooms.Add(key); } } } _isInitialized = true; if (_hasPendingConfig && _cachedConfig != null) { ApplyConfig(); } else { InitializeRoomRando(); } } public void SetConfig(RoomRandomConfig config) { _cachedConfig = config; _hasPendingConfig = true; if (_isInitialized) { ApplyConfig(); } } private void ApplyConfig() { if (_cachedConfig != null) { generationSeed = _cachedConfig.Seed; enableRandomization = _cachedConfig.EnableRandomization; enableMapGeneration = _cachedConfig.EnableMapGeneration; precedencePairs = new List<(string, string)>(_cachedConfig.PrecedencePairs); _hasPendingConfig = false; if (enableRandomization) { InitializeRoomRando(); } } } private void InitializeRoomRando() { try { availableScenes = sceneLoader.sceneConfigs.Keys.ToList(); BuildCaches(); } catch (Exception ex) { ModLog.Warning("RoomRando: failed to populate availableScenes from sceneLoader: " + ex.Message); } try { string path = Path.Combine(Paths.PluginPath, "roomrando_connections.txt"); if (File.Exists(path)) { File.Delete(path); ModLog.Info("RoomRando: 已删除废弃的共享连接文件 roomrando_connections.txt(对不上任何槽位种子)"); } } catch (Exception ex2) { ModLog.Warning("RoomRando: 清理旧连接文件失败: " + ex2.Message); } if (enableRandomization) { if (connections.Count > 0) { ModLog.Info($"RoomRando: 已持有 {connections.Count} 条连接(种子 {generationSeed}),等待 SIR 槽位布局覆盖"); return; } if (IsSIRLoaded()) { ModLog.Info("RoomRando: SIR 已加载,连接表等待 SIR 槽位布局下发(不兜底自生成)"); return; } int num = ((generationSeed != 0) ? generationSeed : ((_cachedConfig != null && _cachedConfig.Seed != 0) ? _cachedConfig.Seed : Environment.TickCount)); ModLog.Warning($"RoomRando: 尚未收到 SIR 槽位布局,按种子 {num} 先行生成兜底(随后会被槽位布局覆盖)"); generationSeed = num; RandomSceneLoader.CurrentSeed = generationSeed; GenerateAllConnectionsAtStart(); } } private static bool IsSIRLoaded() { try { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { if (string.Equals(assemblies[i].GetName().Name, "SilksongItemRandomizer", StringComparison.Ordinal)) { return true; } } } catch { } return false; } private void GenerateAllConnectionsAtStart() { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown int num = ((generationSeed == 0) ? Environment.TickCount : generationSeed); connections.Clear(); try { int num2 = ((_cachedConfig != null) ? _cachedConfig.Mode : 0); List<string> list = RoomLayoutGen.Generate(new Context { SceneExits = VanillaExitMap.GetRandomizableSceneExits(), Mode = num2, PrecedencePairs = new List<(string, string)>(precedencePairs) }, num); int num3 = 0; foreach (string item2 in list) { string text = item2?.Trim(); if (string.IsNullOrWhiteSpace(text) || text.StartsWith("#")) { continue; } string[] array = text.Split(new char[1] { '|' }); if (array.Length == 4) { string text2 = array[0] + "_" + array[1]; string item = array[2] + "_" + array[3]; if (!BlacklistedExits.Contains(text2) && !BlacklistedExits.Contains(item)) { connections[text2] = (array[2], array[3]); num3++; } } } generationSeed = num; RandomSceneLoader.CurrentSeed = generationSeed; ModLog.Info($"RoomRando: 核心布局已应用 {num3} 条连接(种子 {num},模式 {num2})"); } catch (Exception ex) { ModLog.Warning("RoomRando: 核心布局生成失败,连接表保持为空(该出口走原生过渡): " + ex.Message); } } private Dictionary<string, List<string>> BuildFreeExits(List<string> scenes) { Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); foreach (string scene in scenes) { dictionary[scene] = ParticipatingExits(scene); } return dictionary; } private int GetActualExitCount(string scene) { if (_cachedActualExitCounts == null || !_cachedActualExitCounts.TryGetValue(scene, out var value)) { return 0; } return value; } private bool IsConnectionAllowed(string sceneA, string exitA, string sceneB, string exitB) { if (string.Equals(sceneA, sceneB, StringComparison.OrdinalIgnoreCase)) { return false; } if ((sceneA == "Tut_01" && HighPriorityRooms.Contains(sceneB)) || (sceneB == "Tut_01" && HighPriorityRooms.Contains(sceneA))) { return false; } string text = MakeKey(sceneA, exitA); string text2 = MakeKey(sceneB, exitB); if (BlacklistedExits.Contains(text) || BlacklistedExits.Contains(text2)) { return false; } if (!RoomLayoutGen.DirectionCompatible(exitA, exitB)) { return false; } int value; int num = ((_cachedActualExitCounts != null && _cachedActualExitCounts.TryGetValue(sceneA, out value)) ? value : 0); int value2; int num2 = ((_cachedActualExitCounts != null && _cachedActualExitCounts.TryGetValue(sceneB, out value2)) ? value2 : 0); if (num == 1 && num2 < 3) { return false; } if (num2 == 1 && num < 3) { return false; } if (num == 1 && num2 >= 3 && (SingleExitPairedCounts.TryGetValue(sceneB, out var value3) ? value3 : 0) >= num2 - 2) { return false; } if (num2 == 1 && num >= 3 && (SingleExitPairedCounts.TryGetValue(sceneA, out var value4) ? value4 : 0) >= num - 2) { return false; } if (text == "Tut_01_left3" || text2 == "Tut_01_left3") { _ = text == "Tut_01_left3"; _ = text == "Tut_01_left3"; string item = ((text == "Tut_01_left3") ? text2 : text); if (((text == "Tut_01_left3") ? num2 : num) == 1) { return false; } if (Tut01RestrictedExits.Contains(item)) { return false; } } return true; } private void UpdateSingleExitCount(string sceneA, string sceneB) { int value; int num = ((_cachedActualExitCounts != null && _cachedActualExitCounts.TryGetValue(sceneA, out value)) ? value : 0); int value2; int num2 = ((_cachedActualExitCounts != null && _cachedActualExitCounts.TryGetValue(sceneB, out value2)) ? value2 : 0); if (num == 1 && num2 >= 3) { if (!SingleExitPairedCounts.ContainsKey(sceneB)) { SingleExitPairedCounts[sceneB] = 1; } else { SingleExitPairedCounts[sceneB]++; } } if (num2 == 1 && num >= 3) { if (!SingleExitPairedCounts.ContainsKey(sceneA)) { SingleExitPairedCounts[sceneA] = 1; } else { SingleExitPairedCounts[sceneA]++; } } } private void TryGenerateMap() { if (!enableMapGeneration) { ModLog.Info("RoomRando: map generation is disabled"); return; } try { List<string> list = new List<string>(); foreach (KeyValuePair<string, (string, string)> connection in connections) { int num = connection.Key.LastIndexOf('_'); if (num > 0) { list.Add(connection.Key.Substring(0, num) + "|" + connection.Key.Substring(num + 1) + "|" + connection.Value.Item1 + "|" + connection.Value.Item2); } } string text = Path.Combine(Paths.PluginPath, "RoomRandoMap.png"); if (RoomMapGenerator.GenerateFromLines(list, text)) { ModLog.Info("RoomRando: generated map image at " + text); } else { ModLog.Warning("RoomRando: map generation reported failure or no data."); } } catch (Exception ex) { ModLog.Warning("RoomRando: map generation failed: " + ex.Message); } } private string MakeKey(string scene, string exit) { return scene + "_" + exit; } private List<string> ParticipatingExits(string scene) { List<string> list = new List<string>(sceneLoader.sceneConfigs[scene].Exits); if (_blacklistedExitsByScene != null && _blacklistedExitsByScene.TryGetValue(scene, out var value)) { foreach (string item in value) { list.Remove(item); } } if (RegionModeEnabled) { list.RemoveAll((string e) => !VanillaExitMap.IsRegionBoundary(scene, e)); } return list; } private void BuildCaches() { _blacklistedExitsByScene = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase); _cachedActualExitCounts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); if ((Object)(object)sceneLoader == (Object)null) { return; } foreach (KeyValuePair<string, RandomSceneLoader.SceneConfig> sceneConfig in sceneLoader.sceneConfigs) { string key = sceneConfig.Key; RandomSceneLoader.SceneConfig value = sceneConfig.Value; HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); int num = 0; foreach (string exit in value.Exits) { string item = MakeKey(key, exit); if (BlacklistedExits.Contains(item)) { hashSet.Add(exit); num++; } } _blacklistedExitsByScene[key] = hashSet; _cachedActualExitCounts[key] = value.Exits.Count - num; } } public (string targetScene, string targetGate)? GetConnection(string currentScene, string exitName) { if (string.IsNullOrEmpty(exitName)) { return null; } if (!connections.TryGetValue(MakeKey(currentScene, exitName), out (string, string) value)) { return null; } return value; } public List<string> GetValidExitsForScene(string sceneName) { if (!((Object)(object)sceneLoader != (Object)null) || !sceneLoader.sceneConfigs.TryGetValue(sceneName, out var value)) { return new List<string>(); } return value.Exits ?? new List<string>(); } public void OnExitUsed(string currentScene, string exitName) { if (string.IsNullOrEmpty(exitName)) { ModLog.Warning("RoomRando: OnExitUsed called with null/empty exitName from " + currentScene); return; } string text = MakeKey(currentScene, exitName); if (connections.TryGetValue(text, out (string, string) value)) { ModLog.Info("RoomRando: using connection " + text + " -> " + value.Item1 + " via " + value.Item2); LoadScene(value.Item1, value.Item2); } else { ModLog.Warning("RoomRando: no connection found for " + text); } } private void LoadScene(string sceneName, string entryGate) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown if ((Object)(object)GameManager.instance == (Object)null) { ModLog.Error("RoomRando: GameManager not available"); return; } try { RandomSceneLoader randomSceneLoader = Object.FindFirstObjectByType<RandomSceneLoader>(); if ((Object)(object)randomSceneLoader != (Object)null) { randomSceneLoader.SetLastEntryGate(entryGate); } } catch (Exception ex) { ModLog.Warning("RoomRando: failed to notify RandomSceneLoader: " + ex.Message); } try { GameManager.instance.BeginSceneTransition(new SceneLoadInfo { SceneName = sceneName, EntryGateName = entryGate, PreventCameraFadeOut = false, WaitForSceneTransitionCameraFade = true, Visualization = (SceneLoadVisualizations)0 }); } catch (Exception arg) { ModLog.Error($"RoomRando: BeginSceneTransition failed: {arg}"); } } public void LogAllConnections() { ModLog.Info($"RoomRando: {connections.Count} connections:"); foreach (KeyValuePair<string, (string, string)> connection in connections) { ModLog.Info(" " + connection.Key + " -> " + connection.Value.Item1 + " (via " + connection.Value.Item2 + ")"); } } public int GetGenerationSeed() { return generationSeed; } public void ClearAdoptedConnections() { if (connections.Count > 0) { ModLog.Info($"RoomRando: 存档重置,清空内存连接表(原 {connections.Count} 条,种子 {generationSeed})"); } connections.Clear(); generationSeed = 0; RandomSceneLoader.CurrentSeed = 0; _layoutManagedBySIR = false; } public void RegenerateWithSeed(int seed) { if (_layoutManagedBySIR) { ModLog.Warning($"RoomRando: 收到种子重掷请求 {seed},但连接表已由 SIR 槽位布局接管(权威种子 {generationSeed}),拒绝重掷"); return; } if (seed == generationSeed && connections.Count > 0 && _isInitialized) { RandomSceneLoader.CurrentSeed = generationSeed; ModLog.Info($"RoomRando: 种子未变({seed}),复用已加载的 {connections.Count} 条连接,跳过重掷"); return; } generationSeed = seed; RandomSceneLoader.CurrentSeed = generationSeed; rng = new Random(generationSeed); connections.Clear(); ModLog.Info($"RoomRando: regenerating with exact seed {seed}"); GenerateAllConnectionsAtStart(); ModLog.Info($"RoomRando: regeneration complete with seed {generationSeed}(共享文件已废弃,布局由 SIR 槽位存档下发)"); } public bool ApplyExternalConnections(IEnumerable<string> lines, int authoritativeSeed) { try { if (lines == null) { return false; } Dictionary<string, (string, string)> dictionary = new Dictionary<string, (string, string)>(StringComparer.OrdinalIgnoreCase); foreach (string line in lines) { string text = line?.Trim(); if (string.IsNullOrWhiteSpace(text) || text.StartsWith("#")) { continue; } string[] array = text.Split(new char[1] { '|' }); if (array.Length == 4) { string text2 = array[0] + "_" + array[1]; string item = array[2] + "_" + array[3]; if (!BlacklistedExits.Contains(text2) && !BlacklistedExits.Contains(item)) { dictionary[text2] = (array[2], array[3]); } } } if (dictionary.Count == 0) { ModLog.Warning("RoomRando: ApplyExternalConnections 收到空布局,拒绝接入"); return false; } connections.Clear(); foreach (KeyValuePair<string, (string, string)> item2 in dictionary) { connections[item2.Key] = item2.Value; } generationSeed = authoritativeSeed; RandomSceneLoader.CurrentSeed = generationSeed; _layoutManagedBySIR = true; ModLog.Info($"RoomRando: 已接入槽位布局 {connections.Count} 条(权威种子 {authoritativeSeed}),布局本体随槽位存档持久化,不落共享文件"); if (enableMapGeneration) { TryGenerateMap(); } return true; } catch (Exception ex) { ModLog.Warning("RoomRando: ApplyExternalConnections 失败: " + ex.Message); return false; } } } public class RoomRandomConfig { public int Seed; public bool EnableRandomization; public bool EnableMapGeneration; public List<(string before, string after)> PrecedencePairs = new List<(string, string)>(); public int Mode; } public static class HKSilksong_RandomizerAPI { private static RandomSceneLoader _sceneLoader; private static RoomRando _roomRando; private static SeedManager _seedManager; private static RoomRandomConfig _cachedConfig = new RoomRandomConfig(); private static bool _hasPendingChanges = false; private static bool _isGameReady = false; private static bool _pendingShowSeed = true; private static int _pendingNewSeed = 0; private static bool _pendingRegenerate = false; internal static void Initialize(RandomSceneLoader loader, RoomRando rando) { _sceneLoader = loader; _roomRando = rando; GameObject obj = GameObject.Find("__SeedManager"); _seedManager = ((obj != null) ? obj.GetComponent<SeedManager>() : null); _cachedConfig.Mode = GlobalConfig.RandomMode.Value; } internal static void MarkGameReady() { _isGameReady = true; if (_hasPendingChanges) { ApplyPending(); } } public static void SetConfig(RoomRandomConfig config) { if (config != null) { _cachedConfig.Seed = config.Seed; _cachedConfig.EnableRandomization = config.EnableRandomization; _cachedConfig.EnableMapGeneration = config.EnableMapGeneration; _cachedConfig.PrecedencePairs = new List<(string, string)>(config.PrecedencePairs); _cachedConfig.Mode = config.Mode; _hasPendingChanges = true; if (_isGameReady) { ApplyPending(); } } } public static void SetSeed(int seed) { _cachedConfig.Seed = seed; _hasPendingChanges = true; if (_isGameReady) { ApplyPending(); } } public static void SetEnabled(bool enabled) { _cachedConfig.EnableRandomization = enabled; GlobalConfig.EnableRandomization.Value = enabled; _hasPendingChanges = true; ApplyPending(); GlobalConfig.Save(); } public static void SetMapGenerationEnabled(bool enabled) { _cachedConfig.EnableMapGeneration = enabled; _hasPendingChanges = true; if (_isGameReady) { ApplyPending(); } } public static void SetPrecedencePairs(List<(string, string)> pairs) { _cachedConfig.PrecedencePairs = pairs; _hasPendingChanges = true; if (_isGameReady) { ApplyPending(); } } public static RoomRandomConfig GetConfig() { return new RoomRandomConfig { Seed = _cachedConfig.Seed, EnableRandomization = _cachedConfig.EnableRandomization, EnableMapGeneration = _cachedConfig.EnableMapGeneration, PrecedencePairs = new List<(string, string)>(_cachedConfig.PrecedencePairs), Mode = _cachedConfig.Mode }; } public static void SetMode(int mode) { _cachedConfig.Mode = mode; GlobalConfig.RandomMode.Value = mode; _hasPendingChanges = true; ApplyPending(); GlobalConfig.Save(); } public static int GetMode() { return _cachedConfig.Mode; } public static void ApplyPending() { if ((Object)(object)_roomRando != (Object)null) { _roomRando.SetConfig(_cachedConfig); } RandomSceneLoader.EnableRandomization = _cachedConfig.EnableRandomization; if ((Object)(object)_seedManager != (Object)null && _pendingShowSeed != _seedManager.GetShowSeedOnScreen()) { _seedManager.SetShowSeedOnScreen(_pendingShowSeed); } if (_pendingRegenerate && _pendingNewSeed != 0 && (Object)(object)_roomRando != (Object)null) { _roomRando.RegenerateWithSeed(_pendingNewSeed); _pendingRegenerate = false; } _hasPendingChanges = false; } public static void SetShowSeedOnScreen(bool show) { _pendingShowSeed = show; if (_isGameReady && (Object)(object)_seedManager != (Object)null) { _seedManager.SetShowSeedOnScreen(show); } } public static bool GetShowSeedOnScreen() { return _seedManager?.GetShowSeedOnScreen() ?? true; } public static void RegenerateWithSeed(int seed) { if (_isGameReady && (Object)(object)_roomRando != (Object)null) { _roomRando.RegenerateWithSeed(seed); return; } _pendingNewSeed = seed; _pendingRegenerate = true;
BepInEx/plugins/MenuChanger.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using BepInEx; using BepInEx.Logging; using GlobalEnums; using HKSilksong_Randomizer; using HarmonyLib; using HutongGames.PlayMaker; using HutongGames.PlayMaker.Actions; using Microsoft.CodeAnalysis; using NativeUIMaker; using PharloomCore; using PharloomCore.Data; using PharloomCore.Logic; using PharloomCore.Model; using SilksongItemRandomizer; using StartingAbilityPicker; using UnityEngine; using UnityEngine.Audio; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("0.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 MenuChanger { [BepInPlugin("YourName.MenuChanger", "Menu Changer", "1.0.0")] public class MenuChangerMod : BaseUnityPlugin { private Coroutine _delayedFullApplyCoroutine; private bool _uiRebuildInProgress; private static readonly PropertyInfo EnemyRandoEnabledProp = Type.GetType("SilksongItemRandomizer.EnemyRandoAdjuster, SilksongItemRandomizer")?.GetProperty("Enabled", BindingFlags.Static | BindingFlags.Public); private static readonly WaitForSeconds PointOneSecond = new WaitForSeconds(0.1f); private static readonly WaitForSeconds SettingsStabilizeDelay = new WaitForSeconds(20f); private static readonly Action[] ApplyActions = new Action[24] { delegate { StartingAbilityPickerAPI.SetAttackPermissions(SharedRuntimeSettings.AttackUp, SharedRuntimeSettings.AttackLeft, SharedRuntimeSettings.AttackRight); }, delegate { StartingAbilityPickerAPI.SetSkillRandomMode(SharedRuntimeSettings.UseTypeMode); }, delegate { StartingAbilityPickerAPI.SetSkillCounts(SharedRuntimeSettings.SkillTotal, SharedRuntimeSettings.SkillVertical, SharedRuntimeSettings.SkillHorizontal, SharedRuntimeSettings.SkillSpecial, SharedRuntimeSettings.SkillAttack); }, delegate { StartingAbilityPickerAPI.SetStartingItemCount(SharedRuntimeSettings.ItemCount); }, delegate { StartingAbilityPickerAPI.SetSeed(SharedRuntimeSettings.Seed); }, delegate { StartingAbilityPickerAPI.SetResetSeedWorld(SharedRuntimeSettings.ResetSeedWorld); }, delegate { StartingAbilityPickerAPI.SetFullRandomMode(SharedRuntimeSettings.FullRandomMode); }, delegate { StartingAbilityPickerAPI.SetForceCompletionDisplay(SharedRuntimeSettings.ForceCompletionDisplay); }, delegate { StartingAbilityPickerAPI.SetMovementPermissions(NativeConfigPanel.BuildCurrentDirectionPermissions()); }, delegate { SilksongItemRandomizerAPI.SetEnabled(SharedRuntimeSettings.ItemRandomEnabled); }, delegate { SilksongItemRandomizerAPI.SetCrestRandomEnabled(SharedRuntimeSettings.CrestRandomEnabled); }, delegate { SilksongItemRandomizerAPI.SetSkillItemRandomEnabled(SharedRuntimeSettings.SkillItemRandomEnabled); }, delegate { SilksongItemRandomizerAPI.SetRelicRandomEnabled(SharedRuntimeSettings.RelicRandomEnabled); }, delegate { SilksongItemRandomizerAPI.SetSilkRandomEnabled(SharedRuntimeSettings.SilkRandomEnabled); }, delegate { SilksongItemRandomizerAPI.SetTrapEnabled(SharedRuntimeSettings.TrapEnabled); }, delegate { SilksongItemRandomizerAPI.SetTrapMovementEnabled(SharedRuntimeSettings.TrapMovementEnabled); }, delegate { SilksongItemRandomizerAPI.SetTrapDifficulty(SharedRuntimeSettings.TrapDifficulty); }, delegate { SilksongItemRandomizerAPI.SetCurrencyThresholds(SharedRuntimeSettings.CurrencyFirstThreshold, SharedRuntimeSettings.CurrencySecondThreshold); }, delegate { SilksongItemRandomizerAPI.SetSkillTriggerRandomEnabled(SharedRuntimeSettings.SkillTriggerRandomEnabled); }, delegate { HKSilksong_RandomizerAPI.SetMode(SharedRuntimeSettings.RoomRandomizerMode); }, delegate { HKSilksong_RandomizerAPI.SetEnabled(SharedRuntimeSettings.SceneRandomEnabled); }, delegate { HKSilksong_RandomizerAPI.SetShowSceneLabel(SharedRuntimeSettings.ShowSceneLabel); }, delegate { HKSilksong_RandomizerAPI.SetShowSeedOnScreen(SharedRuntimeSettings.ShowSeedLabel); }, delegate { EnemyRandoEnabledProp?.SetValue(null, SharedRuntimeSettings.EnemyRandomEnabled); } }; internal static MenuChangerMod Instance { get; private set; } private void Awake() { Instance = this; ModLog.SetFallback(((BaseUnityPlugin)this).Logger); Harmony.CreateAndPatchAll(typeof(PlayModeMenuPatch), (string)null); Harmony.CreateAndPatchAll(typeof(SkipToFirstAct), (string)null); SceneManager.sceneLoaded += OnSceneLoaded; ((MonoBehaviour)this).StartCoroutine(DelayedInit()); } private void OnDestroy() { SceneManager.sceneLoaded -= OnSceneLoaded; ModLog.Shutdown(); } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (((Scene)(ref scene)).name == "Menu_Title") { ((MonoBehaviour)this).StartCoroutine(EnsureUIRebuiltAfterSceneReload()); } } private IEnumerator EnsureUIRebuiltAfterSceneReload() { if (_uiRebuildInProgress) { yield break; } _uiRebuildInProgress = true; try { UIManager ui = null; while ((Object)(object)ui == (Object)null) { ui = Object.FindObjectOfType<UIManager>(); if ((Object)(object)ui == (Object)null) { yield return PointOneSecond; } else { yield return null; } } while ((Object)(object)ui.UICanvas == (Object)null) { yield return null; } yield return null; if (UIManagerEx.IsUIReady && UIManagerEx.IsUIDestroyed()) { ModLog.Info("[MenuChanger] 检测到 UI 已随场景销毁,开始重建 UI..."); UIManagerEx.ResetUI(); NativeConfigPanel.Instance.Reset(); yield return PerformUIFullInit(); } } finally { _uiRebuildInProgress = false; } } private void OnDisable() { SceneManager.sceneLoaded -= OnSceneLoaded; } private IEnumerator DelayedInit() { yield return PerformUIFullInit(); } private IEnumerator PerformUIFullInit() { UIManager ui = null; while ((Object)(object)ui == (Object)null) { ui = Object.FindObjectOfType<UIManager>(); if ((Object)(object)ui == (Object)null) { yield return PointOneSecond; } else { yield return null; } } while ((Object)(object)ui.UICanvas == (Object)null) { yield return null; } yield return null; PrefabMenuObjects.Initialize(); yield return null; NativeConfigPanel.Instance.Initialize(); yield return null; string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "NativeUIMaker_Config.json"); if (!File.Exists(text)) { text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "PageConfigs", "NativeUIMaker_Config.json"); } UIManagerEx.InitializeUI(text); yield return null; while (!UIManagerEx.IsUIReady) { yield return null; } LoadSharedSettingsFromAPIs(); NativeConfigPanel.Instance.RefreshPageList(); NativeConfigPanel.Instance.RefreshAllValues(); Canvas.ForceUpdateCanvases(); ModLog.Info("[MenuChanger] 初始化完成"); ApplyModeSelectButtonIcons(); ApplySharedSettingsToModules(); if ((Object)(object)Plugin.Instance != (Object)null && Plugin.Instance.ShowUI) { Plugin.Instance.ShowUI = false; Plugin.Instance.ShowUI = true; } } private void ApplyModeSelectButtonIcons() { try { Dictionary<string, string> dictionary = new Dictionary<string, string> { { "ClassicModeBtn", "Icons/classic.png" }, { "SteelModeBtn", "Icons/steel.png" }, { "RandomModeBtn", "Icons/random.png" } }; foreach (NativeButton allInstance in NativeButton.AllInstances) { if (allInstance != null && !((Object)(object)allInstance.gameObject == (Object)null) && dictionary.TryGetValue(((Object)allInstance.gameObject).name, out var value)) { allInstance.SetIconFromFile(value); allInstance.SetIconScale(2f / 3f); } } } catch (Exception ex) { ModLog.Warning("[MenuChanger] 应用模式按钮图标失败: " + ex.Message); } } public void LoadSharedSettingsFromAPIs() { try { SharedRuntimeSettings.SceneRandomEnabled = HKSilksong_RandomizerAPI.IsSceneRandomEnabled(); SharedRuntimeSettings.ShowSceneLabel = HKSilksong_RandomizerAPI.GetShowSceneLabel(); SharedRuntimeSettings.ShowSeedLabel = HKSilksong_RandomizerAPI.GetShowSeedOnScreen(); SharedRuntimeSettings.RoomSeed = HKSilksong_RandomizerAPI.GetCurrentRoomSeed(); SharedRuntimeSettings.RoomRandomizerMode = HKSilksong_RandomizerAPI.GetMode(); } catch (Exception ex) { ModLog.Warning("[MenuChanger] 加载 SceneRandomizer 配置失败: " + ex.Message); } try { SharedRuntimeSettings.ItemRandomEnabled = SilksongItemRandomizerAPI.IsEnabled(); SharedRuntimeSettings.CrestRandomEnabled = SilksongItemRandomizerAPI.IsCrestRandomEnabled(); SharedRuntimeSettings.SkillItemRandomEnabled = SilksongItemRandomizerAPI.IsSkillItemRandomEnabled(); SharedRuntimeSettings.RelicRandomEnabled = SilksongItemRandomizerAPI.IsRelicRandomEnabled(); SharedRuntimeSettings.SilkRandomEnabled = SilksongItemRandomizerAPI.IsSilkRandomEnabled(); SharedRuntimeSettings.TrapEnabled = SilksongItemRandomizerAPI.IsTrapEnabled(); SharedRuntimeSettings.TrapMovementEnabled = SilksongItemRandomizerAPI.IsTrapMovementEnabled(); SharedRuntimeSettings.TrapDifficulty = SilksongItemRandomizerAPI.GetTrapDifficulty(); ValueTuple<int, int> currencyThresholds = SilksongItemRandomizerAPI.GetCurrencyThresholds(); SharedRuntimeSettings.CurrencyFirstThreshold = currencyThresholds.Item1; SharedRuntimeSettings.CurrencySecondThreshold = currencyThresholds.Item2; SharedRuntimeSettings.SkillTriggerRandomEnabled = SilksongItemRandomizerAPI.IsSkillTriggerRandomEnabled(); SharedRuntimeSettings.AttackUp = GlobalConfig.AttackUp.Value; SharedRuntimeSettings.AttackLeft = GlobalConfig.AttackLeft.Value; SharedRuntimeSettings.AttackRight = GlobalConfig.AttackRight.Value; } catch (Exception ex2) { ModLog.Warning("[MenuChanger] 加载 SilksongItemRandomizer 配置失败: " + ex2.Message); } try { if ((Object)(object)Plugin.Instance != (Object)null) { SharedRuntimeSettings.Seed = Plugin.RandomSeed.Value; SharedRuntimeSettings.FullRandomMode = Plugin.CfgFullRandomMode.Value; SharedRuntimeSettings.DashLeft = Plugin.CfgAllowDashLeft.Value; SharedRuntimeSettings.DashRight = Plugin.CfgAllowDashRight.Value; SharedRuntimeSettings.HarpoonLeft = Plugin.CfgAllowHarpoonLeft.Value; SharedRuntimeSettings.HarpoonRight = Plugin.CfgAllowHarpoonRight.Value; SharedRuntimeSettings.FloatLeft = Plugin.CfgAllowFloatLeft.Value; SharedRuntimeSettings.FloatRight = Plugin.CfgAllowFloatRight.Value; SharedRuntimeSettings.WallJumpLeft = Plugin.CfgAllowWallJumpLeft.Value; SharedRuntimeSettings.WallJumpRight = Plugin.CfgAllowWallJumpRight.Value; SharedRuntimeSettings.AllowHeal = Plugin.CfgAllowHeal.Value; } } catch (Exception ex3) { ModLog.Warning("[MenuChanger] 加载 StartingAbilityPicker 配置失败: " + ex3.Message); } try { SharedRuntimeSettings.SkillTriggerEnabled = false; } catch (Exception ex4) { ModLog.Warning("[MenuChanger] SkillTriggerMod 已停用: " + ex4.Message); } try { if (EnemyRandoEnabledProp != null) { SharedRuntimeSettings.EnemyRandomEnabled = (bool)EnemyRandoEnabledProp.GetValue(null); } } catch (Exception ex5) { ModLog.Warning("[MenuChanger] 加载 EnemyRandomizer 配置失败: " + ex5.Message); } ModLog.Info("[MenuChanger] SharedRuntimeSettings 已从各模块配置填充"); } public void ApplySharedSettingsToModules() { for (int i = 0; i < ApplyActions.Length; i++) { ApplyActions[i](); } } public IEnumerator ApplySharedSettingsStaggered() { for (int i = 0; i < ApplyActions.Length; i++) { ApplyActions[i](); yield return null; } } public static void HideAllMenuPages() { if (NativeConfigPanel.Instance != null && NativeConfigPanel.Instance.IsShowing) { NativeConfigPanel.Instance.Hide(); } } public void StartDelayedFullApply() { if (_delayedFullApplyCoroutine != null) { ((MonoBehaviour)this).StopCoroutine(_delayedFullApplyCoroutine); } _delayedFullApplyCoroutine = ((MonoBehaviour)this).StartCoroutine(DelayedFullApplyCoroutine()); } private IEnumerator DelayedFullApplyCoroutine() { yield return SettingsStabilizeDelay; ModLog.Info("[MenuChanger] 稳定等待到达,重新应用共享设置..."); ApplySharedSettingsToModules(); _delayedFullApplyCoroutine = null; } } public sealed class ModLog { private const int FlushThreshold = 4096; private static readonly Dictionary<string, ModLog> _byTag; private static readonly object _registryGate; private static ManualLogSource _fallback; private static bool _closed; private readonly string _tag; private readonly object _gate = new object(); private readonly StringBuilder _buffer = new StringBuilder(5120); private StreamWriter _writer; private bool _broken; private static ModLog _default; private static ModLog DefaultInstance { get { ModLog modLog = _default; if (modLog != null) { return modLog; } return _default = For(typeof(ModLog).Assembly.GetName().Name); } } private ModLog(string tag) { _tag = tag; } public static ModLog For(string tag) { lock (_registryGate) { if (_byTag.TryGetValue(tag, out var value)) { return value; } value = new ModLog(tag); _byTag[tag] = value; return value; } } public static void SetFallback(ManualLogSource source) { _fallback = source; } public static void Shutdown() { lock (_registryGate) { _closed = true; foreach (KeyValuePair<string, ModLog> item in _byTag) { item.Value.Close(); } _byTag.Clear(); } } static ModLog() { _byTag = new Dictionary<string, ModLog>(4); _registryGate = new object(); try { AppDomain.CurrentDomain.ProcessExit += delegate { Shutdown(); }; AppDomain.CurrentDomain.DomainUnload += delegate { Shutdown(); }; } catch { } } public void LogInfo(object message) { Write("INFO ", message); } public void LogWarning(object message) { Write("WARN ", message); } public void LogError(object message) { Write("ERROR", message); } public void LogDebug(object message) { Write("DEBUG", message); } public void LogMessage(object message) { Write("INFO ", message); } public static void Info(object message) { DefaultInstance.LogInfo(message); } public static void Warning(object message) { DefaultInstance.LogWarning(message); } public static void Error(object message) { DefaultInstance.LogError(message); } public static void Debug(object message) { DefaultInstance.LogDebug(message); } private void Write(string level, object message) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (message == null) { return; } string text = message as string; if (text == null) { text = message.ToString(); } if (string.IsNullOrEmpty(text)) { return; } lock (_gate) { if (_closed) { return; } if (_broken) { if (_fallback != null) { _fallback.Log(LevelOf(level), (object)text); } return; } _buffer.Append(DateTime.Now.ToString("HH:mm:ss.fff")); _buffer.Append(" [").Append(level).Append("] "); _buffer.Append(text); _buffer.Append('\n'); if (_buffer.Length >= 4096 || level == "ERROR") { FlushLocked(); } } } private void FlushLocked() { if (_buffer.Length == 0) { return; } try { if (_writer == null) { OpenLocked(); } _writer.Write(_buffer.ToString()); _writer.Flush(); _buffer.Length = 0; } catch (Exception ex) { _broken = true; _buffer.Length = 0; if (_fallback != null) { _fallback.LogWarning((object)("[ModLog] 写入日志文件失败,后续日志回退到 BepInEx 日志: " + ex.Message)); } } } private void OpenLocked() { string text = Path.Combine(Paths.ConfigPath, "SilksongItemRandomizer", "logs"); Directory.CreateDirectory(text); string path = _tag + ".log"; FileStream stream = new FileStream(Path.Combine(text, path), FileMode.Create, FileAccess.Write, FileShare.ReadWrite); _writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); _writer.AutoFlush = false; } private void Close() { lock (_gate) { if (_buffer.Length > 0 && !_broken) { FlushLocked(); } if (_writer != null) { try { _writer.Flush(); _writer.Dispose(); } catch { } _writer = null; } _buffer.Length = 0; } } private static LogLevel LevelOf(string level) { return (LogLevel)(level switch { "ERROR" => 2, "WARN " => 4, "DEBUG" => 32, _ => 16, }); } } [HarmonyPatch(typeof(UIManager))] public static class PlayModeMenuPatch { private static readonly MethodInfo SetMenuStateMethod = typeof(UIManager).GetMethod("SetMenuState", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly object[] SetMenuStateArgs = new object[1]; [HarmonyPrefix] [HarmonyPatch("UIGoToPlayModeMenu")] public static bool Prefix(UIManager __instance) { if (!UIManagerEx.IsUIReady) { return true; } ((MonoBehaviour)__instance).StartCoroutine(ShowModeSelect(__instance)); return false; } private static IEnumerator ShowModeSelect(UIManager ui) { ManagerSingleton<InputHandler>.Instance.StopUIInput(); if ((int)ui.menuState == 6) { yield return ui.HideSaveProfileMenu(true); } UIManagerEx.ShowPage("ModeSelect"); ProfileManager.PrepareForTarget(); if ((Object)(object)MenuChangerMod.Instance != (Object)null) { MenuChangerMod.Instance.LoadSharedSettingsFromAPIs(); } NativeConfigPanel.Instance.RefreshAllValues(); ManagerSingleton<InputHandler>.Instance.StartUIInput(); SetMenuStateArgs[0] = (object)(MainMenuState)18; SetMenuStateMethod?.Invoke(ui, SetMenuStateArgs); } } public class NativeConfigPanel { private sealed class CalcJob { public int Seed; public volatile bool Done; public bool Live; public string Summary; public double ElapsedSeconds; } private static NativeConfigPanel _instance; private GameObject root; private CanvasGroup canvasGroup; private UIManager uiManager; private NativePage parentPage; private NativeLabel pageIndicator; private List<string> pageOrder = new List<string>(); private bool _seedRolling; private bool _liveSeedReady; private bool _seedRolledOnce; private bool _seedRollCanceled; private bool _seedUserProvided; private NativeLabel _calcTitle; private NativeLabel _calcTimer; private NativeLabel _calcAttempt; private NativeLabel _calcLog; private NativeLabel _calcResultBig; private Coroutine _calcTimerCo; private int _triedTotal; private readonly List<string> _calcLogLines = new List<string>(); private const int CalcLogMaxLines = 10; private Stopwatch _calcStopwatch; private List<NativeInput> _repeatLimitInputs = new List<NativeInput>(); private static readonly Type EnemyRandoAdjusterType = Type.GetType("SilksongItemRandomizer.EnemyRandoAdjuster, SilksongItemRandomizer"); private static readonly PropertyInfo EnemyEnabledProp = EnemyRandoAdjusterType?.GetProperty("Enabled", BindingFlags.Static | BindingFlags.Public); private static readonly PropertyInfo ScaleRandomEnabledProp = EnemyRandoAdjusterType?.GetProperty("ScaleRandomEnabled", BindingFlags.Static | BindingFlags.Public); private static readonly PropertyInfo ScaleMinProp = EnemyRandoAdjusterType?.GetProperty("ScaleMin", BindingFlags.Static | BindingFlags.Public); private static readonly PropertyInfo ScaleMaxProp = EnemyRandoAdjusterType?.GetProperty("ScaleMax", BindingFlags.Static | BindingFlags.Public); private static readonly Type ExtraCurrencyType = Type.GetType("SilksongItemRandomizer.Extracurrencypickup, SilksongItemRandomizer"); private static readonly MethodInfo ExtraCurrencyResetAll = ExtraCurrencyType?.GetMethod("ResetAll", BindingFlags.Static | BindingFlags.Public); private static readonly Type TrapRandomizerType = Type.GetType("SilksongItemRandomizer.TrapRandomizer, SilksongItemRandomizer"); private static readonly MethodInfo ResetFrostBanned = TrapRandomizerType?.GetMethod("ResetFrostBannedScenes", BindingFlags.Static | BindingFlags.Public); private readonly Dictionary<string, NativeButton> _buttonCache = new Dictionary<string, NativeButton>(); private readonly Dictionary<string, NativeSlider> _sliderCache = new Dictionary<string, NativeSlider>(); private readonly Dictionary<string, NativeInput> _inputCache = new Dictionary<string, NativeInput>(); private readonly Dictionary<string, NativeOption> _optionCache = new Dictionary<string, NativeOption>(); private readonly Dictionary<string, NativeLabel> _labelCache = new Dictionary<string, NativeLabel>(); private static readonly string[] CategoryButtonNames = new string[6] { "CategoryBtn1", "CategoryBtn2", "CategoryBtn3", "CategoryBtn4", "CategoryBtn5", "CategoryBtn6" }; private static readonly Color DisabledTextColor = new Color(0.8f, 0.8f, 0.8f); private static readonly string[] TrapDifficultyNames = new string[3] { "初猎", "专注", "满溢" }; private static readonly string[] DifficultyNames = new string[4] { "简单", "普通", "困难", "极限" }; private static readonly string[] DifficultyTips = new string[4] { "简单", "普通", "困难", "极限" }; private EventHandler<NativeUIEventArgs> _uiEventHandler; private const string InitialSaveDirName = "InitialSave"; private const string InitialSaveFileName = "user1.dat"; public static NativeConfigPanel Instance => _instance ?? (_instance = new NativeConfigPanel()); public bool IsShowing { get { if ((Object)(object)root != (Object)null) { return root.activeSelf; } return false; } } private NativeButton GetCachedButton(string name) { if (!_buttonCache.TryGetValue(name, out var value)) { value = ((IEnumerable<NativeButton>)NativeButton.AllInstances).FirstOrDefault((Func<NativeButton, bool>)((NativeButton b) => ((Object)b.gameObject).name == name)); if (value != null) { _buttonCache[name] = value; } } return value; } private NativeSlider GetCachedSlider(string name) { if (!_sliderCache.TryGetValue(name, out var value)) { value = ((IEnumerable<NativeSlider>)NativeSlider.AllInstances).FirstOrDefault((Func<NativeSlider, bool>)((NativeSlider sl) => ((Object)sl.gameObject).name == name)); if (value != null) { _sliderCache[name] = value; } } return value; } private NativeInput GetCachedInput(string name) { if (!_inputCache.TryGetValue(name, out var value)) { value = ((IEnumerable<NativeInput>)NativeInput.AllInstances).FirstOrDefault((Func<NativeInput, bool>)((NativeInput inp) => ((Object)inp.gameObject).name == name)); if (value != null) { _inputCache[name] = value; } } return value; } private NativeOption GetCachedOption(string name) { if (!_optionCache.TryGetValue(name, out var value)) { value = ((IEnumerable<NativeOption>)NativeOption.AllInstances).FirstOrDefault((Func<NativeOption, bool>)((NativeOption opt) => ((Object)opt.gameObject).name == name)); if (value != null) { _optionCache[name] = value; } } return value; } private NativeLabel GetCachedLabel(string name) { if (!_labelCache.TryGetValue(name, out var value)) { value = ((IEnumerable<NativeLabel>)NativeLabel.AllInstances).FirstOrDefault((Func<NativeLabel, bool>)((NativeLabel lb) => ((Object)lb.gameObject).name == name)); if (value != null) { _labelCache[name] = value; } } return value; } private void SetCalcStatus(string text) { NativeLabel cachedLabel = GetCachedLabel("SeedCalcStatus"); if (cachedLabel != null) { cachedLabel.SetText(UILocale.Get(text)); } } private NativeConfigPanel() { } public void Reset() { root = null; canvasGroup = null; uiManager = null; parentPage = null; pageIndicator = null; pageOrder.Clear(); _repeatLimitInputs.Clear(); _buttonCache.Clear(); _sliderCache.Clear(); _inputCache.Clear(); _optionCache.Clear(); _labelCache.Clear(); } public void Initialize() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)root != (Object)null)) { PrefabMenuObjects.Initialize(); uiManager = UIManager.instance; if (!((Object)(object)uiManager == (Object)null)) { root = new GameObject("NativeConfigPanel"); root.transform.SetParent(((Component)uiManager.UICanvas).transform, false); canvasGroup = root.AddComponent<CanvasGroup>(); canvasGroup.alpha = 0f; canvasGroup.interactable = false; canvasGroup.blocksRaycasts = false; root.SetActive(false); GameObject val = new GameObject("Panel"); val.transform.SetParent(root.transform, false); RectTransform val2 = val.AddComponent<RectTransform>(); val2.sizeDelta = new Vector2(1200f, 800f); val2.anchorMin = Vector2.zero; val2.anchorMax = Vector2.one; val2.pivot = new Vector2(0.5f, 0.5f); val2.anchoredPosition = Vector2.zero; pageIndicator = NativeLabel.Create(val2); pageIndicator.SetText("1/1"); pageIndicator.SetFontSize(32); pageIndicator.SetPosition(new Vector2(0f, -420f)); pageIndicator.SetSize(200f, 60f); pageIndicator.SetAlignment((TextAnchor)4); pageIndicator.gameObject.SetActive(false); SubscribeToGlobalEvents(); BindRepeatLimitInputs(); RefreshAllValues(); } } } public void StartAutoSeedRoll() { if (!_seedRolledOnce) { _seedRolledOnce = true; if ((Object)(object)uiManager != (Object)null) { ((MonoBehaviour)uiManager).StartCoroutine(RollSeedCoroutine()); } } } public unsafe void ResetAllToDefaults() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) PersistScope val = GlobalConfig.SuspendPersist(); try { SharedRuntimeSettings.SceneRandomEnabled = false; SharedRuntimeSettings.ItemRandomEnabled = true; SharedRuntimeSettings.TrapEnabled = false; SharedRuntimeSettings.FullRandomMode = false; SharedRuntimeSettings.CrestRandomEnabled = false; SharedRuntimeSettings.SkillItemRandomEnabled = SilksongItemRandomizerAPI.IsSkillItemRandomEnabled(); SharedRuntimeSettings.RelicRandomEnabled = SilksongItemRandomizerAPI.IsRelicRandomEnabled(); SharedRuntimeSettings.SilkRandomEnabled = false; SharedRuntimeSettings.EnemyRandomEnabled = false; StartingAbilityPickerAPI.SetEnemyRandomEnabled(false); SharedRuntimeSettings.ShowSceneLabel = true; SharedRuntimeSettings.ShowSeedLabel = true; SharedRuntimeSettings.TrapMovementEnabled = false; SharedRuntimeSettings.ForceCompletionDisplay = true; SilksongItemRandomizerAPI.SetEnabled(true); SilksongItemRandomizerAPI.SetTrapEnabled(false); SilksongItemRandomizerAPI.SetTrapMovementEnabled(false); SilksongItemRandomizerAPI.SetCrestRandomEnabled(false); SilksongItemRandomizerAPI.SetRelicRandomEnabled(SilksongItemRandomizerAPI.IsRelicRandomEnabled()); SilksongItemRandomizerAPI.SetSilkRandomEnabled(false); SharedRuntimeSettings.SkillTotal = 0; SharedRuntimeSettings.SkillVertical = 0; SharedRuntimeSettings.SkillHorizontal = 0; SharedRuntimeSettings.SkillSpecial = 0; SharedRuntimeSettings.SkillAttack = 0; StartingAbilityPickerAPI.SetSkillCounts(0, 0, 0, 0, 0); SharedRuntimeSettings.ItemCount = 0; StartingAbilityPickerAPI.SetStartingItemCount(0); if (ScaleRandomEnabledProp != null) { ScaleRandomEnabledProp.SetValue(null, true); } if (ScaleMinProp != null) { ScaleMinProp.SetValue(null, 1f); } if (ScaleMaxProp != null) { ScaleMaxProp.SetValue(null, 1f); } SharedRuntimeSettings.AllowHeal = false; SharedRuntimeSettings.DashLeft = false; SharedRuntimeSettings.DashRight = false; SharedRuntimeSettings.HarpoonLeft = false; SharedRuntimeSettings.HarpoonRight = false; SharedRuntimeSettings.FloatLeft = false; SharedRuntimeSettings.FloatRight = false; SharedRuntimeSettings.WallJumpLeft = false; SharedRuntimeSettings.WallJumpRight = false; StartingAbilityPickerAPI.SetAttackPermissions(true, true, true); SharedRuntimeSettings.ColdResistOwned = false; SharedRuntimeSettings.SwimOwned = false; SharedRuntimeSettings.TrapDifficulty = 0; StartingAbilityPickerAPI.SaveAllSettingsToConfig(); RefreshAllValues(); try { SilksongItemRandomizerAPI.ResetAllData(false); } catch (Exception ex) { ModLog.Warning("[MenuChanger] 重置 SIR 本地数据失败: " + ex.Message); } if ((Object)(object)MenuChangerMod.Instance != (Object)null) { ((MonoBehaviour)MenuChangerMod.Instance).StartCoroutine(MenuChangerMod.Instance.ApplySharedSettingsStaggered()); } } finally { ((IDisposable)(*(PersistScope*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } private void BindRepeatLimitInputs() { NativePage val = ((IEnumerable<NativePage>)NativePage.AllInstances).FirstOrDefault((Func<NativePage, bool>)((NativePage p) => ((Object)p.gameObject).name == "RepeatLimitPage")); if (val == null) { return; } _repeatLimitInputs = val.gameObject.GetComponentsInChildren<NativeInput>(true).ToList(); if (_repeatLimitInputs.Count == 0) { ModLog.Warning("[NativeConfigPanel] RepeatLimitPage 下没有找到任何 NativeInput 控件"); return; } foreach (NativeInput repeatLimitInput in _repeatLimitInputs) { string name = ((Object)repeatLimitInput.gameObject).name; repeatLimitInput.AddTextChangedListener((Action<string>)delegate(string text) { if (int.TryParse(text, out var result)) { int limitValue = GetLimitValue(name); switch (name) { case "Input_LimitSkillItem": ItemLimitConfig.LimitSkillItem = result; break; case "Input_LimitRelic": ItemLimitConfig.LimitRelic = result; break; case "Input_LimitOtherItem": ItemLimitConfig.LimitOtherItem = result; break; case "Input_LimitUpSlash": ItemLimitConfig.LimitUpSlash = result; break; case "Input_LimitLeftSlash": ItemLimitConfig.LimitLeftSlash = result; break; case "Input_LimitRightSlash": ItemLimitConfig.LimitRightSlash = result; break; case "Input_LimitDashLeft": ItemLimitConfig.LimitDashLeft = result; break; case "Input_LimitDashRight": ItemLimitConfig.LimitDashRight = result; break; case "Input_LimitHarpoonLeft": ItemLimitConfig.LimitHarpoonLeft = result; break; case "Input_LimitHarpoonRight": ItemLimitConfig.LimitHarpoonRight = result; break; case "Input_LimitFloatLeft": ItemLimitConfig.LimitFloatLeft = result; break; case "Input_LimitFloatRight": ItemLimitConfig.LimitFloatRight = result; break; case "Input_LimitWallJumpLeft": ItemLimitConfig.LimitWallJumpLeft = result; break; case "Input_LimitWallJumpRight": ItemLimitConfig.LimitWallJumpRight = result; break; case "Input_LimitHeal": ItemLimitConfig.LimitHeal = result; break; case "Input_LimitNeedleThrow": ItemLimitConfig.LimitNeedleThrow = result; break; case "Input_LimitThreadSphere": ItemLimitConfig.LimitThreadSphere = result; break; case "Input_LimitHarpoonDash": ItemLimitConfig.LimitHarpoonDash = result; break; case "Input_LimitSilkCharge": ItemLimitConfig.LimitSilkCharge = result; break; case "Input_LimitSilkBomb": ItemLimitConfig.LimitSilkBomb = result; break; case "Input_LimitSilkBossNeedle": ItemLimitConfig.LimitSilkBossNeedle = result; break; case "Input_LimitNeedolin": ItemLimitConfig.LimitNeedolin = result; break; case "Input_LimitParry": ItemLimitConfig.LimitParry = result; break; case "Input_LimitNeedolinMemory": ItemLimitConfig.LimitNeedolinMemory = result; break; case "Input_LimitFastTravel": ItemLimitConfig.LimitFastTravel = result; break; case "Input_LimitEvaHeal": ItemLimitConfig.LimitEvaHeal = result; break; case "Input_LimitDash": ItemLimitConfig.LimitDash = result; break; case "Input_LimitBrolly": ItemLimitConfig.LimitBrolly = result; break; case "Input_LimitDoubleJump": ItemLimitConfig.LimitDoubleJump = result; break; case "Input_LimitSuperJump": ItemLimitConfig.LimitSuperJump = result; break; case "Input_LimitWallJump": ItemLimitConfig.LimitWallJump = result; break; case "Input_LimitChargeSlash": ItemLimitConfig.LimitChargeSlash = result; break; case "Input_LimitHeartPiece": ItemLimitConfig.LimitHeartPiece = result; break; case "Input_LimitSpoolPart": ItemLimitConfig.LimitSpoolPart = result; break; case "Input_LimitMaxSilkRegenUp": ItemLimitConfig.LimitMaxSilkRegenUp = result; break; case "Input_LimitUnlockCrestSlot": ItemLimitConfig.LimitUnlockCrestSlot = result; break; } if (GetLimitValue(name) != limitValue) { SilksongItemRandomizerAPI.SaveLimitsAndRegenerateMappings(); } } }); repeatLimitInput.SetText(GetLimitValue(name).ToString()); } } private int GetLimitValue(string inputName) { return inputName switch { "Input_LimitSkillItem" => ItemLimitConfig.LimitSkillItem, "Input_LimitRelic" => ItemLimitConfig.LimitRelic, "Input_LimitOtherItem" => ItemLimitConfig.LimitOtherItem, "Input_LimitUpSlash" => ItemLimitConfig.LimitUpSlash, "Input_LimitLeftSlash" => ItemLimitConfig.LimitLeftSlash, "Input_LimitRightSlash" => ItemLimitConfig.LimitRightSlash, "Input_LimitDashLeft" => ItemLimitConfig.LimitDashLeft, "Input_LimitDashRight" => ItemLimitConfig.LimitDashRight, "Input_LimitHarpoonLeft" => ItemLimitConfig.LimitHarpoonLeft, "Input_LimitHarpoonRight" => ItemLimitConfig.LimitHarpoonRight, "Input_LimitFloatLeft" => ItemLimitConfig.LimitFloatLeft, "Input_LimitFloatRight" => ItemLimitConfig.LimitFloatRight, "Input_LimitWallJumpLeft" => ItemLimitConfig.LimitWallJumpLeft, "Input_LimitWallJumpRight" => ItemLimitConfig.LimitWallJumpRight, "Input_LimitHeal" => ItemLimitConfig.LimitHeal, "Input_LimitNeedleThrow" => ItemLimitConfig.LimitNeedleThrow, "Input_LimitThreadSphere" => ItemLimitConfig.LimitThreadSphere, "Input_LimitHarpoonDash" => ItemLimitConfig.LimitHarpoonDash, "Input_LimitSilkCharge" => ItemLimitConfig.LimitSilkCharge, "Input_LimitSilkBomb" => ItemLimitConfig.LimitSilkBomb, "Input_LimitSilkBossNeedle" => ItemLimitConfig.LimitSilkBossNeedle, "Input_LimitNeedolin" => ItemLimitConfig.LimitNeedolin, "Input_LimitParry" => ItemLimitConfig.LimitParry, "Input_LimitNeedolinMemory" => ItemLimitConfig.LimitNeedolinMemory, "Input_LimitFastTravel" => ItemLimitConfig.LimitFastTravel, "Input_LimitEvaHeal" => ItemLimitConfig.LimitEvaHeal, "Input_LimitDash" => ItemLimitConfig.LimitDash, "Input_LimitBrolly" => ItemLimitConfig.LimitBrolly, "Input_LimitDoubleJump" => ItemLimitConfig.LimitDoubleJump, "Input_LimitSuperJump" => ItemLimitConfig.LimitSuperJump, "Input_LimitWallJump" => ItemLimitConfig.LimitWallJump, "Input_LimitChargeSlash" => ItemLimitConfig.LimitChargeSlash, "Input_LimitHeartPiece" => ItemLimitConfig.LimitHeartPiece, "Input_LimitSpoolPart" => ItemLimitConfig.LimitSpoolPart, "Input_LimitMaxSilkRegenUp" => ItemLimitConfig.LimitMaxSilkRegenUp, "Input_LimitUnlockCrestSlot" => ItemLimitConfig.LimitUnlockCrestSlot, _ => 0, }; } private void RefreshRepeatLimitInputs() { foreach (NativeInput repeatLimitInput in _repeatLimitInputs) { repeatLimitInput.SetText(GetLimitValue(((Object)repeatLimitInput.gameObject).name).ToString()); } } private void SubscribeToGlobalEvents() { if (_uiEventHandler != null) { NativeUIEventDispatcher.OnNativeUIEvent -= _uiEventHandler; } _uiEventHandler = delegate(object sender, NativeUIEventArgs args) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Invalid comparison between Unknown and I4 if ((int)args.EventType == 0) { HandleClickEvent(args); } else if ((int)args.EventType == 1) { HandleValueChangedEvent(args); } else if ((int)args.EventType == 2) { HandleOptionChangedEvent(args); } }; NativeUIEventDispatcher.OnNativeUIEvent += _uiEventHandler; } private void HandleClickEvent(NativeUIEventArgs args) { if (args.ControlName == "RandomModeBtn") { ResetAllToDefaults(); ShowPage(pageOrder.Contains("Main") ? "Main" : pageOrder[0]); } else if (args.ControlName == "ClassicModeBtn") { StartGame(permaDeath: false); } else if (args.ControlName == "SteelModeBtn") { StartGame(permaDeath: true); } else if (args.ControlName == "DetailBtn") { UIManagerEx.ShowPage("Detail0"); } else if (args.ControlName == "BackToMainBtn_Calc") { _seedRollCanceled = true; NativeLabel cachedLabel = GetCachedLabel("SeedCalcStatus"); if (cachedLabel != null) { cachedLabel.SetText(UILocale.Get("计算已取消,返回设置页")); } SeedCalcResetDynamic(); ShowPage("Main"); } else if (args.ControlName.StartsWith("BackToMainBtn")) { ShowPage("Main"); } else if (args.ControlName == "BackToModeSelectBtn") { ShowPage("ModeSelect"); } else if (args.ControlName == "BackToSaveProfileBtn") { ModLog.Info("[MenuChanger] 返回存档页面(原生存档槽选择界面)"); UIManagerEx.HideAllPages(); Hide(); uiManager.UIGoBackToSaveProfiles(); } else if (args.ControlName == "ItemPoolBtn") { ShowPage("ItemPoolPage"); } else if (args.ControlName == "DifficultyBtn") { ShowPage("DifficultyPage"); } else if (args.ControlName != null && args.ControlName.StartsWith("DifficultyBtn")) { if (int.TryParse(args.ControlName.Substring("DifficultyBtn".Length), out var result)) { SilksongItemRandomizerAPI.SetDifficulty(result); UpdateDifficultyUI(); } } else if (args.ControlName == "RepeatBtn") { ShowPage("RepeatLimitPage"); } else if (args.ControlName.StartsWith("LeftArrow")) { SwitchPage(-1); } else if (args.ControlName.StartsWith("RightArrow")) { SwitchPage(1); } if (args.ControlType == "Button") { object source = args.Source; NativeButton val = (NativeButton)((source is NativeButton) ? source : null); if (val == null) { return; } switch (args.ControlName) { case "RoomBtn": StartingAbilityPickerAPI.SetSceneRandomEnabled(SharedRuntimeSettings.SceneRandomEnabled = !SharedRuntimeSettings.SceneRandomEnabled); break; case "ItemBtn": StartingAbilityPickerAPI.SetItemRandomEnabled(SharedRuntimeSettings.ItemRandomEnabled = !SharedRuntimeSettings.ItemRandomEnabled); break; case "TrapBtn": StartingAbilityPickerAPI.SetTrapRandomEnabled(SharedRuntimeSettings.TrapEnabled = !SharedRuntimeSettings.TrapEnabled); break; case "EnemyBtn": StartingAbilityPickerAPI.SetEnemyRandomEnabled(SharedRuntimeSettings.EnemyRandomEnabled = !SharedRuntimeSettings.EnemyRandomEnabled); break; case "FullRandomBtn": case "RandomModeMainBtn": StartingAbilityPickerAPI.SetFullRandomMode(SharedRuntimeSettings.FullRandomMode = !SharedRuntimeSettings.FullRandomMode); UpdateFullRandomUI(); break; case "TrapMovementBtn": SilksongItemRandomizerAPI.SetTrapMovementEnabled(SharedRuntimeSettings.TrapMovementEnabled = !SharedRuntimeSettings.TrapMovementEnabled); break; case "SkillTriggerBtn": SilksongItemRandomizerAPI.SetSkillTriggerRandomEnabled(SharedRuntimeSettings.SkillTriggerRandomEnabled = !SharedRuntimeSettings.SkillTriggerRandomEnabled); break; case "EnemyScaleRandomBtn": if (ScaleRandomEnabledProp != null) { bool flag2 = (bool)ScaleRandomEnabledProp.GetValue(null); ScaleRandomEnabledProp.SetValue(null, !flag2); } break; case "SilkRandomBtn": SilksongItemRandomizerAPI.SetSilkRandomEnabled(SharedRuntimeSettings.SilkRandomEnabled = !SharedRuntimeSettings.SilkRandomEnabled); break; case "UpBtn": { bool flag = (SharedRuntimeSettings.AttackUp = !SharedRuntimeSettings.AttackUp); (bool, bool, bool) attackPermissions = StartingAbilityPickerAPI.GetAttackPermissions(); StartingAbilityPickerAPI.SetAttackPermissions(flag, attackPermissions.Item2, attackPermissions.Item3); UpdateCategoryButtonStates(); break; } case "LeftBtn": { bool flag = (SharedRuntimeSettings.AttackLeft = !SharedRuntimeSettings.AttackLeft); (bool, bool, bool) attackPermissions = StartingAbilityPickerAPI.GetAttackPermissions(); StartingAbilityPickerAPI.SetAttackPermissions(attackPermissions.Item1, flag, attackPermissions.Item3); UpdateCategoryButtonStates(); break; } case "RightBtn": { bool flag = (SharedRuntimeSettings.AttackRight = !SharedRuntimeSettings.AttackRight); (bool, bool, bool) attackPermissions = StartingAbilityPickerAPI.GetAttackPermissions(); StartingAbilityPickerAPI.SetAttackPermissions(attackPermissions.Item1, attackPermissions.Item2, flag); UpdateCategoryButtonStates(); break; } case "ShowRoomNameBtn": HKSilksong_RandomizerAPI.SetShowSceneLabel(SharedRuntimeSettings.ShowSceneLabel = !SharedRuntimeSettings.ShowSceneLabel); break; case "ShowRoomSeedBtn": HKSilksong_RandomizerAPI.SetShowSeedOnScreen(SharedRuntimeSettings.ShowSeedLabel = !SharedRuntimeSettings.ShowSeedLabel); break; case "RoomModeBtn": HKSilksong_RandomizerAPI.SetMode(SharedRuntimeSettings.RoomRandomizerMode = ((SharedRuntimeSettings.RoomRandomizerMode != 1) ? 1 : 0)); break; case "QuestRewardBtn": { bool flag = !GlobalConfig.QuestRewardEnabled.Value; GlobalConfig.QuestRewardEnabled.Value = flag; GlobalConfig.Save(); SilksongItemRandomizerAPI.SaveLimitsAndRegenerateMappings(); break; } case "BossRewardBtn": { bool flag = !GlobalConfig.BossRewardEnabled.Value; GlobalConfig.BossRewardEnabled.Value = flag; GlobalConfig.Save(); SilksongItemRandomizerAPI.SaveLimitsAndRegenerateMappings(); break; } case "SilkHeartBtn": RoomRandomMode.Toggle(); break; case "CompletionBtn": StartingAbilityPickerAPI.SetForceCompletionDisplay(SharedRuntimeSettings.ForceCompletionDisplay = !SharedRuntimeSettings.ForceCompletionDisplay); break; case "TrapDifficultyBtn": SilksongItemRandomizerAPI.SetTrapDifficulty(SharedRuntimeSettings.TrapDifficulty = (SharedRuntimeSettings.TrapDifficulty + 1) % 3); if (SharedRuntimeSettings.TrapEnabled) { SilksongItemRandomizerAPI.RegenerateTrapsNow(); } break; case "CategoryBtn1": if (SharedRuntimeSettings.FullRandomMode) { SharedRuntimeSettings.DashRight = (SharedRuntimeSettings.DashLeft = !SharedRuntimeSettings.DashLeft); StartingAbilityPickerAPI.SetMovementPermissions(BuildCurrentDirectionPermissions()); } break; case "CategoryBtn2": if (SharedRuntimeSettings.FullRandomMode) { SharedRuntimeSettings.HarpoonRight = (SharedRuntimeSettings.HarpoonLeft = !SharedRuntimeSettings.HarpoonLeft); StartingAbilityPickerAPI.SetMovementPermissions(BuildCurrentDirectionPermissions()); } break; case "CategoryBtn3": if (SharedRuntimeSettings.FullRandomMode) { SharedRuntimeSettings.FloatRight = (SharedRuntimeSettings.FloatLeft = !SharedRuntimeSettings.FloatLeft); StartingAbilityPickerAPI.SetMovementPermissions(BuildCurrentDirectionPermissions()); } break; case "CategoryBtn4": if (SharedRuntimeSettings.FullRandomMode) { SharedRuntimeSettings.WallJumpRight = (SharedRuntimeSettings.WallJumpLeft = !SharedRuntimeSettings.WallJumpLeft); StartingAbilityPickerAPI.SetMovementPermissions(BuildCurrentDirectionPermissions()); } break; case "CategoryBtn5": if (SharedRuntimeSettings.FullRandomMode) { bool flag = !SharedRuntimeSettings.AllowHeal; SharedRuntimeSettings.AllowHeal = flag; StartingAbilityPickerAPI.SetMovementPermissions(BuildCurrentDirectionPermissions()); } break; case "CategoryBtn6": { bool flag = (SharedRuntimeSettings.AttackRight = (SharedRuntimeSettings.AttackLeft = (SharedRuntimeSettings.AttackUp = !SharedRuntimeSettings.AttackUp || !SharedRuntimeSettings.AttackLeft || !SharedRuntimeSettings.AttackRight))); StartingAbilityPickerAPI.SetAttackPermissions(flag, flag, flag); break; } case "CrestTypeBtn": { bool flag = (SharedRuntimeSettings.CrestRandomEnabled = !SharedRuntimeSettings.CrestRandomEnabled); SilksongItemRandomizerAPI.SetCrestRandomEnabled(flag); UpdateTypeButtonColor(val, flag); break; } case "SkillTypeBtn": { bool flag = (SharedRuntimeSettings.SkillItemRandomEnabled = !SharedRuntimeSettings.SkillItemRandomEnabled); SilksongItemRandomizerAPI.SetSkillItemRandomEnabled(flag); UpdateTypeButtonColor(val, flag); break; } case "RelicTypeBtn": { bool flag = (SharedRuntimeSettings.RelicRandomEnabled = !SharedRuntimeSettings.RelicRandomEnabled); SilksongItemRandomizerAPI.SetRelicRandomEnabled(flag); UpdateTypeButtonColor(val, flag); break; } } } switch (args.ControlName) { case "ConfirmBtn": StartSeedCalc(); break; case "CalcStartGameBtn": Confirm(); break; case "ResetShopBtn": SilksongItemRandomizerAPI.ResetAllData(true); break; case "ResetPickupBtn": ExtraCurrencyResetAll?.Invoke(null, null); break; case "ResetFrostBlacklistBtn": ResetFrostBanned?.Invoke(null, null); break; } } private IEnumerator RollSeedCoroutine() { if (_seedRolling) { yield break; } _seedRolling = true; _liveSeedReady = false; _seedRollCanceled = false; SilksongItemRandomizerAPI.BeginSeedValidation(); NativeLabel statusLabel = GetCachedLabel("SeedCalcStatus"); NativeLabel resultLabel = GetCachedLabel("SeedCalcResult"); try { SetStatus("正在准备检查点数据…"); EnsureSeedCalcDynamicControls(); SeedCalcResetDynamic(); CalcTimerStart(); _triedTotal = 0; NativeInput seedInput = GetCachedInput("SeedInput"); int wait; if (seedInput == null) { for (wait = 0; wait < 120; wait++) { if (seedInput != null) { break; } seedInput = GetCachedInput("SeedInput"); yield return null; } if (seedInput == null) { ModLog.Warning("[MenuChanger] SeedInput 控件 2 秒内未出现,跳过随机种子"); SetStatus("SeedInput 控件未就绪,跳过随机种子"); CalcTimerStop(); yield break; } } long baseTicks = DateTime.UtcNow.Ticks; int tickCount = Environment.TickCount; wait = 0; while (!_seedRollCanceled) { if (_calcAttempt != null) { _calcAttempt.SetText(UILocale.Get("尝试") + ": " + (wait + 1) + " " + UILocale.Get("已试候选") + ": " + _triedTotal); } SetStatus("正在判定候选种子(已试 " + _triedTotal + " 个)…"); for (int i = 0; i < 20; i++) { if (_seedRollCanceled) { SetStatus("计算已取消,保留当前种子"); CalcTimerStop("已取消"); yield break; } int s = GameSeedValidator.NextDynamicSeed(baseTicks, tickCount, wait * 20 + i); seedInput.SetTextSilent(s.ToString()); SetResult("判定中… 候选: " + s); CalcLogAppend(UILocale.Get("候选") + " " + s + " …"); yield return null; try { if (HKSilksong_RandomizerAPI.IsSceneRandomEnabled()) { HKSilksong_RandomizerAPI.RegenerateWithSeed(s); } } catch (Exception ex) { ModLog.Warning("[MenuChanger] 候选种子房间连接生成失败: " + ex.Message); } CalcJob job = new CalcJob { Seed = s }; Stopwatch jobSw = Stopwatch.StartNew(); Thread thread = new Thread((ThreadStart)delegate { try { if (!GameSeedValidator.IsSimulatedLive(s)) { job.Live = false; job.Summary = UILocale.Get("模拟预筛未过"); } else { string summary = default(string); job.Live = SilksongItemRandomizerAPI.TryGenerateLiveMapping(s, ref summary); job.Summary = summary; } } catch (Exception ex2) { job.Summary = UILocale.Get("异常") + ": " + ex2.Message; job.Live = false; } job.ElapsedSeconds = jobSw.Elapsed.TotalSeconds; job.Done = true; }); thread.IsBackground = true; thread.Start(); while (!job.Done) { yield return null; } double elapsedSeconds = job.ElapsedSeconds; _triedTotal++; if (job.Live) { ModLog.Info("[MenuChanger] 已筛选出可行随机种子: " + s); CalcLogReplaceLast("✓ " + UILocale.Get("候选") + " " + s + " " + UILocale.Get("活种") + $"({elapsedSeconds:F1}s)"); ApplySeed(s, seedInput); _liveSeedReady = true; SetStatus("活种确认完成,可以开始游戏"); SetResult("可行种子: " + s); if (_calcResultBig != null) { _calcResultBig.SetText("✓ " + UILocale.Get("可行种子") + "\n" + s); _calcResultBig.Show(); } CalcTimerStop(); yield break; } string text = (string.IsNullOrEmpty(job.Summary) ? "" : (":" + job.Summary)); CalcLogReplaceLast("✗ " + UILocale.Get("候选") + " " + s + " " + UILocale.Get("死种") + text + $"({elapsedSeconds:F1}s)"); SetResult("候选 " + s + " 非活种,继续寻找…"); yield return null; } wait++; } SetStatus("计算已取消,保留当前种子"); CalcTimerStop("已取消"); } finally { NativeConfigPanel nativeConfigPanel = this; nativeConfigPanel.CalcTimerStop(); nativeConfigPanel._seedRolling = false; SilksongItemRandomizerAPI.EndSeedValidation(); } void SetResult(string text2) { if (resultLabel != null) { resultLabel.SetText(UILocale.Get(text2)); } } void SetStatus(string text2) { if (statusLabel != null) { statusLabel.SetText(UILocale.Get(text2)); } } } private void EnsureSeedCalcDynamicControls() { //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) if (_calcTitle != null && (Object)(object)_calcTitle.gameObject != (Object)null) { return; } NativePage val = ((IEnumerable<NativePage>)NativePage.AllInstances).FirstOrDefault((Func<NativePage, bool>)((NativePage p) => ((Object)p.gameObject).name == "SeedCalcPage")); RectTransform parent; if (val != null) { parent = val.rectTransform; Color color = default(Color); ((Color)(ref color))..ctor(0.92f, 0.92f, 0.92f); Color color2 = default(Color); ((Color)(ref color2))..ctor(0.95f, 0.88f, 0.55f); _calcTimer = Make("SeedCalcDynTimer", 24, new Vector2(0f, 336f), new Vector2(560f, 40f), (TextAnchor)4, color2); _calcTitle = Make("SeedCalcDynTitle", 28, new Vector2(0f, 292f), new Vector2(560f, 40f), (TextAnchor)4, color2); _calcTitle.SetText(UILocale.Get("随机化进度")); _calcAttempt = Make("SeedCalcDynAttempt", 22, new Vector2(0f, 125f), new Vector2(560f, 32f), (TextAnchor)4, color); _calcLog = Make("SeedCalcDynLog", 18, new Vector2(0f, -105f), new Vector2(560f, 290f), (TextAnchor)1, color); NativeLabel cachedLabel = GetCachedLabel("SeedCalcStatus"); if (cachedLabel != null) { cachedLabel.SetAlignment((TextAnchor)4); } NativeLabel cachedLabel2 = GetCachedLabel("SeedTitle"); if (cachedLabel2 != null) { cachedLabel2.SetAlignment((TextAnchor)4); } _calcResultBig = Make("SeedCalcDynResult", 34, new Vector2(600f, 240f), new Vector2(620f, 60f), (TextAnchor)4, new Color(0.55f, 0.95f, 0.6f)); _calcResultBig.Hide(); } NativeLabel Make(string name, int fontSize, Vector2 pos, Vector2 size, TextAnchor anchor, Color color3) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) NativeLabel obj = NativeLabel.Create(parent); ((Object)obj.gameObject).name = name; obj.SetText(""); obj.SetFontSize(fontSize); obj.SetPosition(pos); obj.SetSize(size.x, size.y); obj.SetAlignment(anchor); obj.SetColor(color3); return obj; } } private void CalcLogAppend(string line) { _calcLogLines.Add(line); while (_calcLogLines.Count > 10) { _calcLogLines.RemoveAt(0); } NativeLabel calcLog = _calcLog; if (calcLog != null) { calcLog.SetText(string.Join("\n", _calcLogLines)); } } private void CalcLogReplaceLast(string line) { if (_calcLogLines.Count > 0) { _calcLogLines[_calcLogLines.Count - 1] = line; } else { _calcLogLines.Add(line); } NativeLabel calcLog = _calcLog; if (calcLog != null) { calcLog.SetText(string.Join("\n", _calcLogLines)); } } private static string CalcClockText(double seconds) { TimeSpan timeSpan = TimeSpan.FromSeconds(seconds); if (timeSpan.Hours <= 0) { return $"{timeSpan.Minutes}:{timeSpan.Seconds:D2}.{timeSpan.Milliseconds:D3}"; } return $"{timeSpan.Hours}:{timeSpan.Minutes:D2}:{timeSpan.Seconds:D2}.{timeSpan.Milliseconds:D3}"; } private IEnumerator CalcTimerCoroutine() { while (true) { if (_calcTimer != null && _calcStopwatch != null) { _calcTimer.SetText(UILocale.Get("耗时") + ": " + CalcClockText(_calcStopwatch.Elapsed.TotalSeconds)); } yield return (object)new WaitForSecondsRealtime(0.05f); } } private void CalcTimerStart() { CalcTimerStop(); _calcStopwatch = Stopwatch.StartNew(); if ((Object)(object)uiManager != (Object)null) { _calcTimerCo = ((MonoBehaviour)uiManager).StartCoroutine(CalcTimerCoroutine()); } } private void CalcTimerStop(string stopText = null) { if (_calcTimerCo != null && (Object)(object)uiManager != (Object)null) { ((MonoBehaviour)uiManager).StopCoroutine(_calcTimerCo); _calcTimerCo = null; } if (stopText != null && _calcTimer != null && _calcStopwatch != null) { _calcTimer.SetText(UILocale.Get("耗时") + ": " + CalcClockText(_calcStopwatch.Elapsed.TotalSeconds) + " (" + UILocale.Get(stopText) + ")"); } } private void SeedCalcResetDynamic() { CalcTimerStop(); _calcLogLines.Clear(); NativeLabel calcLog = _calcLog; if (calcLog != null) { calcLog.SetText(""); } NativeLabel calcAttempt = _calcAttempt; if (calcAttempt != null) { calcAttempt.SetText(""); } NativeLabel calcResultBig = _calcResultBig; if (calcResultBig != null) { calcResultBig.Hide(); } } private void StartSeedCalc() { if (_seedRolling) { ModLog.Info("[MenuChanger] 活种计算正在进行中,忽略重复点击"); return; } UIManagerEx.ShowPage("SeedCalcPage"); EnsureSeedCalcDynamicControls(); NativeLabel cachedLabel = GetCachedLabel("SeedCalcStatus"); NativeLabel cachedLabel2 = GetCachedLabel("SeedCalcResult"); if (_seedUserProvided) { int seed = SharedRuntimeSettings.Seed; ModLog.Info("[MenuChanger] 检测到手填种子 " + seed + ",直接采用不重新计算"); _liveSeedReady = true; if (cachedLabel != null) { cachedLabel.SetText(UILocale.Get("已采用手填种子")); } if (cachedLabel2 != null) { cachedLabel2.SetText(UILocale.Get("种子: ") + seed); } if (_calcResultBig != null) { _calcResultBig.SetText("✓ " + UILocale.Get("种子") + "\n" + seed); _calcResultBig.Show(); } } else { if (cachedLabel != null) { cachedLabel.SetText(UILocale.Get("正在计算可行种子,请稍候…")); } if ((Object)(object)uiManager != (Object)null) { ((MonoBehaviour)uiManager).StartCoroutine(RollSeedCoroutine()); } } } private void ApplySeed(int seed, NativeInput seedInput) { SharedRuntimeSettings.Seed = seed; StartingAbilityPickerAPI.SetSeed(seed); SilksongItemRandomizerAPI.SetSeed(seed); _seedUserProvided = false; seedInput.SetTextSilent(seed.ToString()); } private void HandleValueChangedEvent(NativeUIEventArgs args) { if (args.ControlType == "Slider") { float num = (float)args.Value; string controlName = args.ControlName; if (controlName == null) { return; } switch (controlName.Length) { case 7: switch (controlName[0]) { case 'V': if (controlName == "VSlider") { SharedRuntimeSettings.SkillVertical = (int)num; StartingAbilityPickerAPI.SetSkillCounts(SharedRuntimeSettings.SkillTotal, (int)num, SharedRuntimeSettings.SkillHorizontal, SharedRuntimeSettings.SkillSpecial, SharedRuntimeSettings.SkillAttack); } break; case 'H': if (controlName == "HSlider") { SharedRuntimeSettings.SkillHorizontal = (int)num; StartingAbilityPickerAPI.SetSkillCounts(SharedRuntimeSettings.SkillTotal, SharedRuntimeSettings.SkillVertical, (int)num, SharedRuntimeSettings.SkillSpecial, SharedRuntimeSettings.SkillAttack); } break; case 'S': if (controlName == "SSlider") { SharedRuntimeSettings.SkillSpecial = (int)num; StartingAbilityPickerAPI.SetSkillCounts(SharedRuntimeSettings.SkillTotal, SharedRuntimeSettings.SkillVertical, SharedRuntimeSettings.SkillHorizontal, (int)num, SharedRuntimeSettings.SkillAttack); } break; case 'A': if (controlName == "ASlider") { SharedRuntimeSettings.SkillAttack = (int)num; StartingAbilityPickerAPI.SetSkillCounts(SharedRuntimeSettings.SkillTotal, SharedRuntimeSettings.SkillVertical, SharedRuntimeSettings.SkillHorizontal, SharedRuntimeSettings.SkillSpecial, (int)num); } break; } break; case 19: switch (controlName[11]) { case 'i': if (controlName == "EnemyScaleMinSlider") { ScaleMinProp?.SetValue(null, num); } break; case 'a': if (controlName == "EnemyScaleMaxSlider") { ScaleMaxProp?.SetValue(null, num); } break; } break; case 15: if (controlName == "ItemCountSlider") { SharedRuntimeSettings.ItemCount = (int)num; StartingAbilityPickerAPI.SetStartingItemCount((int)num); } break; case 16: if (controlName == "TotalSkillSlider") { SharedRuntimeSettings.SkillTotal = (int)num; StartingAbilityPickerAPI.SetSkillCounts((int)num, SharedRuntimeSettings.SkillVertical, SharedRuntimeSettings.SkillHorizontal, SharedRuntimeSettings.SkillSpecial, SharedRuntimeSettings.SkillAttack); } break; } } else { if (!(args.ControlType == "Input")) { return; } string s = (string)args.Value; switch (args.ControlName) { case "CurrencyFirstThresholdInput": { if (int.TryParse(s, out var result2)) { SharedRuntimeSettings.CurrencyFirstThreshold = result2; SilksongItemRandomizerAPI.SetCurrencyThresholds(result2, SharedRuntimeSettings.CurrencySecondThreshold); } break; } case "CurrencySecondThresholdInput": { if (int.TryParse(s, out var result3)) { SharedRuntimeSettings.CurrencySecondThreshold = result3; SilksongItemRandomizerAPI.SetCurrencyThresholds(SharedRuntimeSettings.CurrencyFirstThreshold, result3); } break; } case "SeedInput": { if (int.TryParse(s, out var result)) { _seedRollCanceled = true; _seedUserProvided = true; _liveSeedReady = true; SharedRuntimeSettings.Seed = result; StartingAbilityPickerAPI.SetSeed(result); SilksongItemRandomizerAPI.SetSeed(result); } break; } } } } private void HandleOptionChangedEvent(NativeUIEventArgs args) { if (!(args.ControlType == "Option")) { return; } int num = (int)args.Value; string controlName = args.ControlName; if (!(controlName == "SkillModeOption")) { if (controlName == "ResetOption") { SharedRuntimeSettings.ResetSeedWorld = num == 1; StartingAbilityPickerAPI.SetResetSeedWorld(num == 1); } } else { SharedRuntimeSettings.UseTypeMode = num == 1; StartingAbilityPickerAPI.SetSkillRandomMode(num == 1); UpdateSlidersVisibility(); } } private bool IsFullRandomEnabled() { return SharedRuntimeSettings.FullRandomMode; } internal static DirectionPermissions BuildCurrentDirectionPermissions() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown return new DirectionPermissions { DashLeft = SharedRuntimeSettings.DashLeft, DashRight = SharedRuntimeSettings.DashRight, HarpoonLeft = SharedRuntimeSettings.HarpoonLeft, HarpoonRight = SharedRuntimeSettings.HarpoonRight, FloatLeft = SharedRuntimeSettings.FloatLeft, FloatRight = SharedRuntimeSettings.FloatRight, WallJumpLeft = SharedRuntimeSettings.WallJumpLeft, WallJumpRight = SharedRuntimeSettings.WallJumpRight, AllowHeal = SharedRuntimeSettings.AllowHeal }; } private void UpdateFullRandomUI() { bool interactable = IsFullRandomEnabled(); string[] categoryButtonNames = CategoryButtonNames; foreach (string name in categoryButtonNames) { NativeButton cachedButton = GetCachedButton(name); if (cachedButton != null && (Object)(object)cachedButton.menuButton != (Object)null) { ((Selectable)cachedButton.menuButton).interactable = interactable; } } NativeButton cachedButton2 = GetCachedButton("UpBtn"); NativeButton cachedButton3 = GetCachedButton("LeftBtn"); NativeButton cachedButton4 = GetCachedButton("RightBtn"); if (cachedButton2 != null && (Object)(object)cachedButton2.menuButton != (Object)null) { ((Selectable)cachedButton2.menuButton).interactable = true; } if (cachedButton3 != null && (Object)(object)cachedButton3.menuButton != (Object)null) { ((Selectable)cachedButton3.menuButton).interactable = true; } if (cachedButton4 != null && (Object)(object)cachedButton4.menuButton != (Object)null) { ((Selectable)cachedButton4.menuButton).interactable = true; } } private void UpdateCategoryButtonStates() { if (IsFullRandomEnabled()) { NativeButton cachedButton = GetCachedButton("CategoryBtn1"); if (cachedButton != null) { cachedButton.SetToggleIndex((SharedRuntimeSettings.DashLeft && SharedRuntimeSettings.DashRight) ? 1 : 0); } NativeButton cachedButton2 = GetCachedButton("CategoryBtn2"); if (cachedButton2 != null) { cachedButton2.SetToggleIndex((SharedRuntimeSettings.HarpoonLeft && SharedRuntimeSettings.HarpoonRight) ? 1 : 0); } NativeButton cachedButton3 = GetCachedButton("CategoryBtn3"); if (cachedButton3 != null) { cachedButton3.SetToggleIndex((SharedRuntimeSettings.FloatLeft && SharedRuntimeSettings.FloatRight) ? 1 : 0); } NativeButton cachedButton4 = GetCachedButton("CategoryBtn4"); if (cachedButton4 != null) { cachedButton4.SetToggleIndex((SharedRuntimeSettings.WallJumpLeft && SharedRuntimeSettings.WallJumpRight) ? 1 : 0); } NativeButton cachedButton5 = GetCachedButton("CategoryBtn5"); if (cachedButton5 != null) { cachedButton5.SetToggleIndex(SharedRuntimeSettings.AllowHeal ? 1 : 0); } NativeButton cachedButton6 = GetCachedButton("CategoryBtn6"); if (cachedButton6 != null) { cachedButton6.SetToggleIndex((SharedRuntimeSettings.AttackUp && SharedRuntimeSettings.AttackLeft && SharedRuntimeSettings.AttackRight) ? 1 : 0); } } } private void UpdateTypeButtonColor(NativeButton btn, bool isEnabled) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (btn != null) { Text componentInChildren = btn.gameObject.GetComponentInChildren<Text>(); if ((Object)(object)componentInChildren != (Object)null) { ((Graphic)componentInChildren).color = (isEnabled ? Color.white : DisabledTextColor); ((Graphic)componentInChildren).SetVerticesDirty(); } } } private void UpdateSlidersVisibility() { bool flag = !SharedRuntimeSettings.UseTypeMode; NativeSlider cachedSlider = GetCachedSlider("TotalSkillSlider"); if (cachedSlider != null) { cachedSlider.gameObject.SetActive(flag); } NativeSlider cachedSlider2 = GetCachedSlider("VSlider"); NativeSlider cachedSlider3 = GetCachedSlider("HSlider"); NativeSlider cachedSlider4 = GetCachedSlider("SSlider"); NativeSlider cachedSlider5 = GetCachedSlider("ASlider"); bool active = !flag; if (cachedSlider2 != null) { cachedSlider2.gameObject.SetActive(active); } if (cachedSlider3 != null) { cachedSlider3.gameObject.SetActive(active); } if (cachedSlider4 != null) { cachedSlider4.gameObject.SetActive(active); } if (cachedSlider5 != null) { cachedSlider5.gameObject.SetActive(active); } } public void RefreshAllValues() { SyncButtonState("RoomBtn", SharedRuntimeSettings.SceneRandomEnabled); SyncButtonState("ItemBtn", SharedRuntimeSettings.ItemRandomEnabled); SyncButtonState("TrapBtn", SharedRuntimeSettings.TrapEnabled); SyncButtonState("FullRandomBtn", SharedRuntimeSettings.FullRandomMode); SyncButtonState("RandomModeMainBtn", SharedRuntimeSettings.FullRandomMode); SyncButtonState("TrapMovementBtn", SharedRuntimeSettings.TrapMovementEnabled); SyncButtonState("SkillTriggerBtn", SharedRuntimeSettings.SkillTriggerRandomEnabled); SyncButtonState("ShowRoomNameBtn", SharedRuntimeSettings.ShowSceneLabel); SyncButtonState("ShowRoomSeedBtn", SharedRuntimeSettings.ShowSeedLabel); NativeButton cachedButton = GetCachedButton("RoomModeBtn"); if (cachedButton != null) { cachedButton.SetToggleIndex((SharedRuntimeSettings.RoomRandomizerMode == 1) ? 1 : 0); } SyncButtonState("QuestRewardBtn", GlobalConfig.QuestRewardEnabled == null || GlobalConfig.QuestRewardEnabled.Value); SyncButtonState("BossRewardBtn", GlobalConfig.BossRewardEnabled == null || GlobalConfig.BossRewardEnabled.Value); NativeButton cachedButton2 = GetCachedButton("EnemyScaleRandomBtn"); if (cachedButton2 != null && ScaleRandomEnabledProp != null) { cachedButton2.SetToggleIndex(((bool)ScaleRandomEnabledProp.GetValue(null)) ? 1 : 0); } SyncButtonState("CompletionBtn", SharedRuntimeSettings.ForceCompletionDisplay); SyncButtonState("CrestTypeBtn", SharedRuntimeSettings.CrestRandomEnabled); SyncButtonState("SkillTypeBtn", SharedRuntimeSettings.SkillItemRandomEnabled); SyncButtonState("RelicTypeBtn", SharedRuntimeSettings.RelicRandomEnabled); bool value = GlobalConfig.AttackUp.Value; bool value2 = GlobalConfig.AttackLeft.Value; bool value3 = GlobalConfig.AttackRight.Value; SharedRuntimeSettings.AttackUp = value; SharedRuntimeSettings.AttackLeft = value2; SharedRuntimeSettings.AttackRight = value3; NativeButton cachedButton3 = GetCachedButton("UpBtn"); if (cachedButton3 != null) { cachedButton3.SetToggleIndex((!value) ? 1 : 0); } NativeButton cachedButton4 = GetCachedButton("LeftBtn"); if (cachedButton4 != null) { cachedButton4.SetToggleIndex((!value2) ? 1 : 0); } NativeButton cachedButton5 = GetCachedButton("RightBtn"); if (cachedButton5 != null) { cachedButton5.SetToggleIndex((!value3) ? 1 : 0); } NativeButton cachedButton6 = GetCachedButton("SilkHeartBtn"); if (cachedButton6 != null) { cachedButton6.SetToggleIndex(RoomRandomMode.IsPending ? 1 : 0); } SetSliderValue("ItemCountSlider", SharedRuntimeSettings.ItemCount); SetSliderValue("TotalSkillSlider", SharedRuntimeSettings.SkillTotal); SetSliderValue("VSlider", SharedRuntimeSettings.SkillVertical); SetSliderValue("HSlider", SharedRuntimeSettings.SkillHorizontal); SetSliderValue("SSlider", SharedRuntimeSettings.SkillSpecial); SetSliderValue("ASlider", SharedRuntimeSettings.SkillAttack); if (ScaleMinProp != null) { SetSliderValue("EnemyScaleMinSlider", (float)ScaleMinProp.GetValue(null)); } if (ScaleMaxProp != null) { SetSliderValue("EnemyScaleMaxSlider", (float)ScaleMaxProp.GetValue(null)); } SetOptionValue("SkillModeOption", SharedRuntimeSettings.UseTypeMode ? 1 : 0); SetOptionValue("ResetOption", SharedRuntimeSettings.ResetSeedWorld ? 1 : 0); NativeInput cachedInput = GetCachedInput("CurrencyFirstThresholdInput"); if (cachedInput != null) { cachedInput.SetText(SharedRuntimeSettings.CurrencyFirstThreshold.ToString()); } NativeInput cachedInput2 = GetCachedInput("CurrencySecondThresholdInput"); if (cachedInput2 != null) { cachedInput2.SetText(SharedRuntimeSettings.CurrencySecondThreshold.ToString()); } NativeLabel cachedLabel = GetCachedLabel("CurrentSeedValue"); if (cachedLabel != null) { cachedLabel.SetText(SharedRuntimeSettings.Seed.ToString()); } NativeButton cachedButton7 = GetCachedButton("TrapDifficultyBtn"); if (cachedButton7 != null) { int trapDifficulty = SharedRuntimeSettings.TrapDifficulty; if (trapDifficulty >= 0 && trapDifficulty < TrapDifficultyNames.Length) { cachedButton7.SetTitle(TrapDifficultyNames[trapDifficulty]); } } SharedRuntimeSettings.Difficulty = ((GlobalConfig.Difficulty != null) ? GlobalConfig.Difficulty.Value : 0); UpdateDifficultyUI(); RefreshRepeatLimitInputs(); UpdateFullRandomUI(); UpdateCategoryButtonStates(); UpdateSlidersVisibility(); } private void UpdateDifficultyUI() { int num = SharedRuntimeSettings.Difficulty; if (num < 0) { num = 0; } if (num >= DifficultyNames.Length) { num = DifficultyNames.Length - 1; } NativeButton cachedButton = GetCachedButton("DifficultyBtn"); if (cachedButton != null) { cachedButton.SetTitle(UILocale.Get("难度:") + UILocale.Get(DifficultyNames[num])); } for (int i = 0; i < DifficultyTips.Length; i++) { NativeButton cachedButton2 = GetCachedButton("DifficultyBtn" + i); if (cachedButton2 != null) { cachedButton2.SetTitle(((i == num) ? "▶ " : "") + UILocale.Get(DifficultyTips[i]) + "\n"); } } } private void SetSliderValue(string sliderName, float value) { NativeSlider cachedSlider = GetCachedSlider(sliderName); if (cachedSlider != null) { cachedSlider.SetValueWithoutNotify(value); } } private void SetOptionValue(string optName, int value) { NativeOption cachedOption = GetCachedOption(optName); if (cachedOption != null) { cachedOption.SetValueWithoutNotify(value); } } private void SyncButtonState(string buttonName, bool isEnabled) { NativeButton cachedButton = GetCachedButton(buttonName); if (cachedButton != null) { cachedButton.SetToggleIndex(isEnabled ? 1 : 0); } } private void Confirm() { if (!_liveSeedReady) { if (_seedRolling) { ModLog.Warning("[MenuChanger] 种子尚未确定,禁止开始游戏"); SetCalcStatus("活种计算进行中,等验证完成后再开始游戏"); } else { ModLog.Warning("[MenuChanger] 尚未验证出活种,禁止开始游戏"); SetCalcStatus("请先点「开始随机」验证出活种,再开始游戏"); } return; } Plugin.BlackoutShow(); Plugin instance = Plugin.Instance; if ((Object)(object)instance != (Object)null) { instance.SetPendingOpeningSettings(SharedRuntimeSettings.UseTypeMode, SharedRuntimeSettings.SkillTotal, SharedRuntimeSettings.SkillVertical, SharedRuntimeSettings.SkillHorizontal, SharedRuntimeSettings.SkillSpecial, SharedRuntimeSettings.SkillAttack, SharedRuntimeSettings.ItemCount); } SilksongItemRandomizerAPI.ResetAllData(false); try { if (HKSilksong_RandomizerAPI.IsSceneRandomEnabled()) { int seed = SharedRuntimeSettings.Seed; HKSilksong_RandomizerAPI.RegenerateWithSeed(seed); ModLog.Info("[MenuChanger] 房间随机化已开启,连接已按种子 " + seed + " 生成"); } else { ModLog.Info("[MenuChanger] 房间随机化未开启,场景图走原生流程"); try { HKSilksong_RandomizerAPI.SetShowSeedOnScreen(false); ModLog.Info("[MenuChanger] 房随未开启:已隐藏房随种子悬浮显示(避免误导的旧种子)"); } catch { } } } catch (Exception ex) { ModLog.Warning("[MenuChanger] 房间连接定档生成失败: " + ex.Message); } StartingAbilityPickerAPI.SetEnemyRandomEnabled(SharedRuntimeSettings.EnemyRandomEnabled); SilksongItemRandomizerAPI.PrimeAllTemplates(); StartingAbilityPickerAPI.SaveAllSettingsToConfig(); StartGameViaInitialSave(permaDeath: false); Hide(); if ((Object)(object)MenuChangerMod.Instance != (Object)null) { MenuChangerMod.Instance.StartDelayedFullApply(); } } private void StartGameViaInitialSave(bool permaDeath) { //IL_00cb: Unknown result type (might be due to invalid IL or missing references) GameManager instance = GameManager.instance; if ((Object)(object)instance == (Object)null) { ModLog.Error("[MenuChanger] GameManager 未就绪,回退原生新档流程"); UIManager.instance.StartNewGame(permaDeath, false); return; } int pendingProfile = ProfileManager.PendingProfile; try { string text = Path.Combine(Path.GetDirectoryName(typeof(MenuChangerMod).Assembly.Location), "InitialSave", "user1.dat"); if (!File.Exists(text)) { ModLog.Error("[MenuChanger] 初始存档缺失: " + text + ",回退原生新档流程"); UIManager.instance.StartNewGame(permaDeath, false); return; } byte[] array = File.ReadAllBytes(text); SaveGameData val = SaveDataUtility.DeserializeSaveData<SaveGameData>(instance.GetJsonForSaveBytes(array)); if (val == null || val.playerData == null) { ModLog.Error("[MenuChanger] 初始存档反序列化失败,回退原生新档流程"); UIManager.instance.StartNewGame(permaDeath, false); return; } if (permaDeath) { val.playerData.permadeathMode = (PermadeathModes)1; } ModLog.Info($"[MenuChanger] 初始存档开局:注入 saveSlot={pendingProfile}(user{pendingProfile}.dat,原生 lastProfileIndex),permaDeath={permaDeath}"); if ((Object)(object)MenuChangerMod.Instance != (Object)null) { ((MonoBehaviour)MenuChangerMod.Instance).StartCoroutine(HideBlackoutWhenPlaying()); } instance.LoadGameFromUI(pendingProfile, val); UIManagerEx.ShowPage("Blank"); } catch (Exception arg) { ModLog.Error($"[MenuChanger] 初始存档开局异常: {arg},回退原生新档流程"); UIManager.instance.StartNewGame(permaDeath, false); } } private IEnumerator HideBlackoutWhenPlaying() { for (float timeout = 25f; timeout > 0f; timeout -= Time.unscaledDeltaTime) { GameManager instance = GameManager.instance; if ((Object)(object)instance != (Object)null && ((int)instance.GameState == 2 || (int)instance.GameState == 4)) { break; } yield return null; } ModLog.Info("[MenuChanger] 初始存档开局:Prime 黑幕移除,交给原生淡入"); try { Plugin.BlackoutHide(); } catch (Exception ex) { ModLog.Warning("[MenuChanger] Prime 黑幕移除异常: " + ex.Message); } } private void ApplyVanillaSettings() { SharedRuntimeSettings.ItemRandomEnabled = false; SharedRuntimeSettings.CrestRandomEnabled = false; SharedRuntimeSettings.SkillItemRandomEnabled = false; SharedRuntimeSettings.RelicRandomEnabled = false; SharedRuntimeSettings.TrapEnabled = false; SharedRuntimeSettings.TrapMovementEnabled = false; SharedRuntimeSettings.SceneRandomEnabled = false; SharedRuntimeSettings.SkillTriggerEnabled = false; SharedRuntimeSettings.EnemyRandomEnabled = false; SharedRuntimeSettings.FullRandomMode = false; SharedRuntimeSettings.ResetSeedWorld = false; SilksongItemRandomizerAPI.SetEnabled(false); SilksongItemRandomizerAPI.SetCrestRandomEnabled(false); SilksongItemRandomizerAPI.SetSkillItemRandomEnabled(false); SilksongItemRandomizerAPI.SetRelicRandomEnabled(false); SilksongItemRandomizerAPI.SetTrapEnabled(false); SilksongItemRandomizerAPI.SetTrapMovementEnabled(false); HKSilksong_RandomizerAPI.SetEnabled(false); EnemyEnabledProp?.SetValue(null, false); StartingAbilityPickerAPI.SetFullRandomMode(false); StartingAbilityPickerAPI.SetResetSeedWorld(false); } private void StartGame(bool permaDeath) { if (_seedRolling) { ModLog.Warning("[MenuChanger] 种子尚未确定,禁止开始游戏"); return; } ApplyVanillaSettings(); Plugin instance = Plugin.Instance; if ((Object)(object)instance != (Object)null) { instance.SetPendingOpeningSettings(SharedRuntimeSettings.UseTypeMode, SharedRuntimeSettings.SkillTotal, SharedRuntimeSettings.SkillVertical, SharedRuntimeSettings.SkillHorizontal, SharedRuntimeSettings.SkillSpecial, SharedRuntimeSettings.SkillAttack, SharedRuntimeSettings.ItemCount); } StartingAbilityPickerAPI.SetEnemyRandomEnabled(SharedRuntimeSettings.EnemyRandomEnabled); SilksongItemRandomizerAPI.PrimeAllTemplates(); StartingAbilityPickerAPI.SaveAllSettingsToConfig(); StartGameViaInitialSave(permaDeath); Hide(); if ((Object)(object)MenuChangerMod.Instance != (Object)null) { MenuChangerMod.Instance.StartDelayedFullApply(); } } public void RefreshPageList() { pageOrder = (from p in NativePage.AllInstances select ((Object)p.gameObject).name into n where n != "ModeSelect" && n != "SeedCalcPage" && n != "Blank" select n).ToList(); } public void ShowPage(string pageName) { if (!string.IsNullOrEmpty(pageName)) { UIManagerEx.ShowPage(pageName); UpdatePageIndicator(); } } public void UpdatePageIndicator() { if (pageIndicator == null) { return; } string currentShowingPageName = GetCurrentShowingPageName(); if (!string.IsNullOrEmpty(currentShowingPageName) && pageOrder.Count != 0) { int num = pageOrder.IndexOf(currentShowingPageName); if (num >= 0) { pageIndicator.SetText($"{num + 1}/{pageOrder.Count}"); pageIndicator.gameObject.SetActive(pageOrder.Count > 1); } } } public void SwitchPage(int delta) { if (pageOrder.Count != 0) { string currentShowingPageName = GetCurrentShowingPageName(); if (!string.IsNullOrEmpty(currentShowingPageName)) { int index = (pageOrder.IndexOf(currentShowingPageName) + delta + pageOrder.Count) % pageOrder.Count; ShowPage(pageOrder[index]); } } } private string GetCurrentShowingPageName() { foreach (NativePage allInstance in NativePage.AllInstances) { if (allInstance != null && allInstance.isShowing) { return ((Object)allInstance.gameObject).name; } } return null; } public void Show(NativePage fromPage = null) { parentPage = fromPage; RefreshAllValues(); root.SetActive(true); ((MonoBehaviour)uiManager).StartCoroutine(FadeIn()); if (pageOrder.Contains("Main")) { ShowPage("Main"); } else if (pageOrder.Count > 0) { ShowPage(pageOrder[0]); } } public void Hide() { ((MonoBehaviour)uiManager).StartCoroutine(FadeOut()); } private IEnumerator FadeIn() { canvasGroup.alpha = 0f; canvasGroup.interactable = true; canvasGroup.blocksRaycasts = true; while (canvasGroup.alpha < 1f) { CanvasGroup obj = canvasGroup; obj.alpha += Time.unscaledDeltaTime * 3f; yield return null; } canvasGroup.alpha = 1f; } private IEnumerator FadeOut() { canvasGroup.interactable = false; canvasGroup.blocksRaycasts = false; while (canvasGroup.alpha > 0f) { CanvasGroup obj = canvasGroup; obj.alpha -= Time.unscaledDeltaTime * 3f; yield return null; } canvasGroup.alpha = 0f; if ((Object)(object)root != (Object)null) { root.SetActive(false); } if (parentPage != null) { parentPage.Show(true); } } } [HarmonyPatch] public static class SkipToFirstAct { private static bool _shouldSkip = false; private static bool _skipTriggered = false; private static bool _tutorialRestorePending = false; private static bool _tutorialSkipped = false; private static readonly WaitForSeconds SkipInterval = new WaitForSeconds(0.2f); private static readonly MethodInfo SendHeroInPositionMethod = typeof(HeroController).GetMethod("SendHeroInPosition", BindingFlags.Instance | BindingFlags.NonPublic); private static Type _csmCachedType; private static readonly FieldInfo[] CsmFields = new FieldInfo[5]; private static void EnsureCsmFieldCache(Type type) { if (!(type == _csmCachedType)) { BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic; CsmFields[0] = type.GetField("musicCue", bindingAttr); CsmFields[1] = type.GetField("musicSnapshot", bindingAttr); CsmFields[2] = type.GetField("musicDelayTime", bindingAttr); CsmFields[3] = type.GetField("musicTransitionTime", bindingAttr); CsmFields[4] = type.GetField("atmosCue", bindingAttr); _csmCachedType = type; } } public static void EnableSkip() { _tutorialSkipped = false; if (!_shouldSkip) { _shouldSkip = true; _skipTriggered = false; SceneManager.sceneLoaded += OnSceneLoaded; ModLog.Info("[SkipToFirstAct] 已启用跳过开场模式"); } } public static void DisableSkip() { if (_shouldSkip) { _shouldSkip = false; SceneManager.sceneLoaded -= OnSceneLoaded; } } private static void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (!_shouldSkip) { return; } if (((Scene)(ref scene)).name != "Opening_Sequence" && ((Scene)(ref scene)).name != "Main_Menu") { if (((Scene)(ref scene)).name == "Tut_01" || ((Scene)(ref scene)).name == "tut_01") { _tutorialRestorePending = true; } else { GameManager instance = GameManager.instance; if ((Object)(object)instance != (Object)null) { ((MonoBehaviour)instance).StartCoroutine(RestoreSceneMusic()); } } } if (((Scene)(ref scene)).name == "Opening_Sequence") { if (!_skipTriggered) { _skipTriggered = true; ModLog.Info("[SkipToFirstAct] 检测到开场动画,开始跳过..."); GameManager instance2 = GameManager.instance; if ((Object)(object)instance2 == (Object)null) { _skipTriggered = false; } else { ((MonoBehaviour)instance2).StartCoroutine(SkipCutscenes()); } } } else { if ((!(((Scene)(ref scene)).name == "Tut_01") && !(((Scene)(ref scene)).name == "tut_01")) || _tutorialSkipped) { return; } GameManager instance3 = GameManager.instance; try { if ((Object)(object)instance3 != (Object)null && instance3.GetPlayerDataBool("bindCutscenePlayed")) { _tutorialSkipped = true; return; } } catch { } GameManager instance4 = GameManager.instance; if (!((Object)(object)instance4 == (Object)null)) { _tutorialSkipped = true; ((MonoBehaviour)instance4).StartCoroutine(SkipEntireTutorial()); } } } private static IEnumerator SkipCutscenes() { yield return null; GameManager gm = GameManager.instance; if ((Object)(object)gm == (Object)null) { ModLog.Error("[SkipToFirstAct] GameManager 不可用"); yield break; } for (int i = 0; i < 5; i++) { gm.SkipCutscene(); yield return SkipInterval; } _skipTriggered = false; Scene activeScene = SceneManager.GetActiveScene(); string name = ((Scene)(ref activeScene)).name; if (!_tutorialSkipped && (name == "Tut_01" || name == "tut_01")) { _tutorialRestorePending = true; _tutorialSkipped = true; ((MonoBehaviour)gm).StartCoroutine(SkipEntireTutorial()); } } private static IEnumerator RestoreSceneMusic() { GameManager gm = null; for (int wait = 0; wait < 600; wait++) { gm = GameManager.instance; if ((Object)(object)gm != (Object)null && gm.HasFinishedEnteringScene && (Object)(object)gm.AudioManager != (Object)null) { break; } yield return null; } if ((Object)(object)gm == (Object)null || (Object)(object)gm.AudioManager == (Object)null) { ModLog.Warning("[SkipToFirstAct] 场景进入未完成/音频系统不可用,整体音乐恢复中止"); yield break; } yield return null; AudioManager audioManager = gm.AudioManager; bool flag = string.Equals(gm.GetSceneNameString(), "tut_01", StringComparison.OrdinalIgnoreCase); try { HeroController instance = HeroController.instance; if ((Object)(object)instance != (Object)null && !instance.isHeroInPosition) { bool flag2 = false; try { MethodInfo sendHeroInPositionMethod = SendHeroInPositionMethod; if (sendHeroInPositionMethod != null) { sendHeroInPositionMethod.Invoke(instance, new object[1] { true }); flag2 = true; } } catch (Exception ex) { ModLog.Warning("[SkipToFirstAct] SendHeroInPosition 反射调用失败,走字段兜底: " + ex.Message); } if (!flag2) { instance.isHeroInPosition = true; } ModLog.Info("[SkipToFirstAct] HeroController 就位标记已置位(isHeroInPosition=true),解锁音频/相机全链"); } } catch (Exception ex2) { ModLog.Warning("[SkipToFirstAct] HeroController 就位恢复异常: " + ex2.Message); } try { CameraController cameraCtrl = gm.cameraCtrl; if ((Object)(object)cameraCtrl != (Object)null && !cameraCtrl.HasBeenPositionedAtHero && !CameraController.IsPositioningCamera) { cameraCtrl.PositionToHero(true); ModLog.Info("[SkipToFirstAct] 相机未定位,主动触发 PositionToHero 解锁音频/相机链"); } } catch (Exception ex3) { ModLog.Warning("[SkipToFirstAct] 相机定位恢复异常: " + ex3.Message); } try { if (AudioListener.pause) { AudioListener.pause = false; ModLog.Info("[SkipToFirstAct] AudioListener.pause 已复位为 false(Control FSM 静音演出残留)"); } } catch (Exception ex4) { ModLog.Warning("[SkipToFirstAct] AudioListener.pause 复位异常: " + ex4.Message); } try { GameCameras instance2 = GameCameras.instance; if ((Object)(object)instance2 != (Object)null && (Object)(object)instance2.forceCameraAspect != (Object)null) { instance2.forceCameraAspect.SetFovOffset(0f, 0f, (AnimationCurve)null); ModLog.Info("[SkipToFirstAct] 相机 FOV offset 已复位为 0"); } } catch (Exception ex5) { ModLog.Warning("[SkipToFirstAct] 相机 FOV 复位异常: " + ex5.Message); } Plugin.BlackoutHide(); if (flag) { try { PlayMakerFSM[] array = Object.FindObjectsByType<PlayMakerFSM>((FindObjectsInactive)1, (FindObjectsSortMode)0); foreach (PlayMakerFSM val in array) { if ((Object)(object)val == (Object)null || val.FsmStates == null || !HasFsmState(val, "Moss Music Up")) { continue; } FsmState state = val.Fsm.GetState("Moss Music Up"); if (state == null || state.Actions == null) { continue; } for (int j = 0; j < state.Actions.Length; j++) { FsmStateAction obj = state.Actions[j]; ApplyMusicCue val2 = (ApplyMusicCue)(object)((obj is ApplyMusicCue) ? obj : null); if (val2 != null) { Object value = val2.musicCue.Value; MusicCue val3 = (MusicCue)(object)((value is MusicCue) ? value : null); if ((Object)(object)val3 != (Object)null) { val3.Preload(((Component)val).gameObject); audioManager.ApplyMusicCue(val3, 0f, 0f, false); ModLog.Info("[SkipToFirstAct] tut_01 教程 BGM 重放: " + ((Object)val3).name); } continue; } FsmStateAction obj2 = state.Actions[j]; TransitionToAudioSnapshot val4 = (TransitionToAudioSnapshot)(object)((obj2 is TransitionToAudioSnapshot) ? obj2 : null); if (val4 != null) { Object value2 = val4.snapshot.Value; AudioMixerSnapshot val5 = (AudioMixerSnapshot)(object)((value2 is AudioMixerSnapshot) ? value2 : null); if (val5 != null) { audioManager.ApplyMusicSnapshot(val5, 0f, val4.transitionTime.Value); ModLog.Info("[SkipToFirstAct] tut_01 音乐快照恢复: " + ((Object)val5).name); } } } break; } } catch (Exception ex6) { ModLog.Warning("[SkipToFirstAct] tut_01 教程 BGM 重放异常: " + ex6.Message); } } try { CustomSceneManager[] array2 = Object.FindObjectsByType<CustomSceneManager>((FindObjectsInactive)1, (FindObjectsSortMode)0); if (array2 != null && array2.Length != 0) { CustomSceneManager val6 = array2[0]; EnsureCsmFieldCache(((object)val6).GetType()); object? obj3 = CsmFields[0]?.GetValue(val6); MusicCue val7 = (MusicCue)((obj3 is MusicCue) ? obj3 : null); object? obj4 = CsmFields[1]?.GetValue(val6); AudioMixerSnapshot val8 = (AudioMixerSnapshot)((obj4 is AudioMixerSnapshot) ? obj4 : null); float num = ((CsmFields[2]?.GetValue(val6) is float num2) ? num2 : 0f); float num3 = ((CsmFields[3]?.GetValue(val6) is float num4) ? num4 : 0f); if ((Object)(object)val7 != (Object)null && (Object)(object)audioManager.CurrentMusicCue == (Object)null) { val7.Preload(((Component)val6).gameObject); audioManager.ApplyMusicCue(val7, num, num3, false); ModLog.Info("[SkipToFirstAct] 场景音乐配置恢复: cue=" + ((Object)val7).name); } if ((Object)(object)val8 != (Object)null) { audioManager.ApplyMusicSnapshot(val8, num, num3); } object? obj5 = CsmFields[4]?.GetValue(val6); AtmosCue val9 = (AtmosCue)((obj5 is AtmosCue) ? obj5 : null); if ((Object)(object)val9 != (Object)null) { audioManager.ClearAtmosOverrides(); audioManager.ApplyAtmosCue(val9, val6.transitionTime, true); } if ((Object)(object)val6.atmosSnapshot != (Object)null) { AudioManager.TransitionToAtmosOverride(val6.atmosSnapshot, val6.transitionTime); } } } catch (Exception ex7) { ModLog.Warning("[SkipToFirstAct] 场景音乐配置恢复异常: " + ex7.Message); } try { MusicRegion[] array3 = Object.FindObjectsByType<MusicRegion>((FindObjectsInactive)1, (FindObjectsSortMode)0); foreach (MusicRegion val10 in array3) { if (!((Object)(object)val10 == (Object)null)) { if ((Object)(object)val10.enterMusicSnapshot != (Object)null) { audioManager.ApplyMusicSnapshot(val10.enterMusicSnapshot, 0f, val10.enterTransitionTime); } if ((Object)(object)val10.enterMusicCue != (Object)null && (Object)(object)audioManager.CurrentMusicCue == (Object)null) { val10.enterMusicCue.Preload(((Component)val10).gameObject); audioManager.ApplyMusicCue(val10.enterMusicCue, 0f, 0f, false); ModLog.Info("[SkipToFirstAct] 音乐区域恢复: " + ((Object)val10).name); } } } } catch (Exception ex8) { ModLog.Warning("[SkipToFirstAct] 音乐区域恢复异常: " + ex8.Message); } ModLog.Info("[SkipToFirstAct] 整体音乐恢复完成"); } private static IEnumerator SkipEntireTutorial() { yield return null; GameManager instance = GameManager.instance; if ((Object)(object)instance == (Object)null) { ModLog.Error("[SkipToFirstAct] GameManager 不可用,教程跳过中止"); yield break; } try { instance.SetPlayerDataBool("bindCutscenePlayed", true); instance.SetPlayerDataBool("completedTutorial", true); instance.SetPlayerDataBool("enteredTutorialFirstTime", true); instance.SetPlayerDataBool("entered_Tut01b", true); } catch (Exception arg) { ModLog.Error($"[SkipToFirstAct] 写入教程标志失败: {arg}"); } PlayMakerFSM val = null; PlayMakerFSM val2 = null; try { PlayMakerFSM[] array = Object.FindObjectsByType<PlayMakerFSM>((FindObjectsInactive)1, (FindObjectsSortMode)0); for (int i = 0; i < array.Length; i++) { if (!((Object)(object)array[i] == (Object)null) && !(array[i].FsmName != "Control")) { if ((Object)(object)val == (Object)null && HasFsmState(array[i], "Hornet Down")) { val = array[i]; } else if ((Object)(object)val2 == (Object)null && HasFsmState(array[i], "Weak Start")) { val2 = array[i]; } } } if ((Object)(object)val != (Object)null && HasFsmState(val, "End")) { val.SetState("End"); } } catch (Exception ex) { ModLog.Warning("[SkipToFirstAct] FSM 瞬跳异常: " + ex.Message); } try { Color colour = ScreenFaderUtils.GetColour(); Color val3 = default(Color); ((Color)(ref val3))..ctor(0f, 0f, 0f, 0f); ScreenFaderUtils.Fade(colour, val3, 0.5f); Plugin.BlackoutHide(); } catch (Exception ex2) { ModLog.Warning("[SkipToFirstAct] 清除黑幕异常: " + ex2.Message); } if ((Object)(object)instance != (Object)null) { ((MonoBehaviour)instance).StartCoroutine(DelayedGetUp(val2)); } try { if ((Object)(object)HeroController.instance != (Object)null) { HeroController.instance.RefillHealthToMax(); } } catch (Exception ex3) { ModLog.Warning("[SkipToFirstAct] 回满血异常: " + ex3.Message); } try { GameCameras instance2 = GameCameras.instance; if ((Object)(object)instance2 != (Object)null) { EventRegister.SendEvent("SHOW HP", (GameObject)null); EventRegister.SendEvent("SPOOL APPEAR", (GameObject)null); try { SilkSpool silkSpool = instance2.silkSpool; if ((Object)(object)silkSpool != (Object)null) { silkSpool.DrawSpool(); silkSpool.RefreshSilk(); } } catch (Exception ex4) { ModLog.Warning("[SkipToFirstAct] 丝卷初始化异常: " + ex4.Message); } try { BindOrbHudFrame[] array2 = Object.FindObjectsByType<BindOrbHudFrame>((FindObjectsInactive)1, (FindObjectsSortMode)0); for (int j = 0; j < array2.Length; j++) { array2[j].AlreadyAppeared(); } } catch (Exception ex5) { ModLog.Warning("[SkipToFirstAct] 纹章框初始化异常: " + ex5.Message); } EventRegister.SendEvent("HEALTH UPDATE", (GameObject)null); EventRegister.SendEvent("HERO HEALED TO MAX", (GameObject)null); EventRegister.SendEvent("TOOL EQUIPS CHANGED", (GameObject)null); EventRegister.SendEvent("POST TOOL EQUIPS CHANGED", (GameObject)null); instance2.HUDIn(); HudGlobalHide.IsHidden = false; HudScalePositioner.IsReduced = false; if (!instance2.IsHudVisible) { ModLog.Warning("[SkipToFirstAct] HUD 初始化完成但 IsHudVisible 仍为 false"); } } } catch (Exception ex6) { ModLog.Warning("[SkipToFirstAct] HUD 初始化异常: " + ex6.Message); } if (_tutorialRestorePending) { _tutorialRestorePending = false; ((MonoBehaviour)instance).StartCoroutine(RestoreSceneMusic()); } ModLog.Info("[SkipToFirstAct] 教程跳过完成,玩家原地留在 tut_01"); } private static bool HasFsmState(PlayMakerFSM fsm, string stateName) { if ((Object)(object)fsm == (Object)null || fsm.FsmStates == null) { return false; } for (int i = 0; i < fsm.FsmStates.Length; i++) { if (fsm.FsmStates[i] != null && f
BepInEx/plugins/NativeUIMaker.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Logging; using GlobalEnums; using HarmonyLib; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.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.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace NativeUIMaker { public static class NativeUIMakerAPI { private static bool _initialized; private static string _configPath; private static FieldInfo _showWindowField; private static MethodInfo _saveConfigMethod; public static bool IsUIReady => UIManagerEx.IsUIReady; public static event EventHandler<NativeUIEventArgs> OnUIEvent { add { NativeUIEventDispatcher.OnNativeUIEvent += value; } remove { NativeUIEventDispatcher.OnNativeUIEvent -= value; } } public static void Initialize(string configPath) { if (_initialized) { return; } if (string.IsNullOrEmpty(configPath)) { throw new ArgumentException("configPath cannot be null or empty"); } _configPath = configPath; if (UIManagerEx.IsUIReady) { DoInitialize(); return; } UIManagerEx.OnUIReady += delegate { DoInitialize(); }; } private static void DoInitialize() { if (!_initialized) { UIManagerEx.InitializeUI(_configPath); _initialized = true; } } public static void ShowPage(string pageName) { if (!IsUIReady) { throw new InvalidOperationException("UI not ready, call Initialize first"); } UIManagerEx.ShowPage(pageName); } public static void HidePage(string pageName) { if (IsUIReady) { UIManagerEx.HidePage(pageName); } } public static void HideAllPages() { if (!IsUIReady) { return; } foreach (NativePage allInstance in NativePage.AllInstances) { allInstance.Hide(); } } public static NativePage GetCurrentPage() { return UIManagerEx.GetCurrentPage(); } public static NativeButton GetButton(string pageName, string buttonName) { NativePage nativePage = NativePage.AllInstances.FirstOrDefault((NativePage p) => ((Object)p.gameObject).name == pageName); if (nativePage == null) { return null; } GameObject obj = FindChildByName(nativePage.gameObject.transform, buttonName); if (obj == null) { return null; } return obj.GetComponent<NativeButton>(); } public static NativeLabel GetLabel(string pageName, string labelName) { NativePage nativePage = NativePage.AllInstances.FirstOrDefault((NativePage p) => ((Object)p.gameObject).name == pageName); if (nativePage == null) { return null; } GameObject obj = FindChildByName(nativePage.gameObject.transform, labelName); if (obj == null) { return null; } return obj.GetComponent<NativeLabel>(); } public static NativeSlider GetSlider(string pageName, string sliderName) { NativePage nativePage = NativePage.AllInstances.FirstOrDefault((NativePage p) => ((Object)p.gameObject).name == pageName); if (nativePage == null) { return null; } GameObject obj = FindChildByName(nativePage.gameObject.transform, sliderName); if (obj == null) { return null; } return obj.GetComponent<NativeSlider>(); } public static NativeOption GetOption(string pageName, string optionName) { NativePage nativePage = NativePage.AllInstances.FirstOrDefault((NativePage p) => ((Object)p.gameObject).name == pageName); if (nativePage == null) { return null; } GameObject obj = FindChildByName(nativePage.gameObject.transform, optionName); if (obj == null) { return null; } return obj.GetComponent<NativeOption>(); } public static NativeArrow GetArrow(string pageName, string arrowName) { NativePage nativePage = NativePage.AllInstances.FirstOrDefault((NativePage p) => ((Object)p.gameObject).name == pageName); if (nativePage == null) { return null; } GameObject obj = FindChildByName(nativePage.gameObject.transform, arrowName); if (obj == null) { return null; } return obj.GetComponent<NativeArrow>(); } public static NativeInput GetInput(string pageName, string inputName) { NativePage nativePage = NativePage.AllInstances.FirstOrDefault((NativePage p) => ((Object)p.gameObject).name == pageName); if (nativePage == null) { return null; } GameObject obj = FindChildByName(nativePage.gameObject.transform, inputName); if (obj == null) { return null; } return obj.GetComponent<NativeInput>(); } public static void SetButtonTitle(string pageName, string buttonName, string title) { GetButton(pageName, buttonName)?.SetTitle(title); } public static void SetSliderValue(string pageName, string sliderName, float value) { NativeSlider slider = GetSlider(pageName, sliderName); if (slider != null) { slider.Value = value; } } public static void SetOptionIndex(string pageName, string optionName, int index) { GetOption(pageName, optionName)?.SetValueWithoutNotify(index); } public static void SetInputText(string pageName, string inputName, string text) { GetInput(pageName, inputName)?.SetText(text); } public static string GetButtonTitle(string pageName, string buttonName) { return GetButton(pageName, buttonName)?.GetTitle(); } public static float GetSliderValue(string pageName, string sliderName) { return GetSlider(pageName, sliderName)?.Value ?? 0f; } public static int GetOptionIndex(string pageName, string optionName) { return GetOption(pageName, optionName)?.GetCurrentIndex() ?? (-1); } public static string GetOptionValue(string pageName, string optionName) { NativeOption option = GetOption(pageName, optionName); if (option == null) { return ""; } return option.GetCurrentValue(); } public static string GetInputText(string pageName, string inputName) { NativeInput input = GetInput(pageName, inputName); if (input == null) { return ""; } return input.GetText(); } public static void ShowDebugWindow() { SetDebugWindowVisible(visible: true); } public static void HideDebugWindow() { SetDebugWindowVisible(visible: false); } private static void SetDebugWindowVisible(bool visible) { DebugWindow instance = DebugWindow.Instance; if (!((Object)(object)instance == (Object)null)) { if (_showWindowField == null) { _showWindowField = typeof(DebugWindow).GetField("_showWindow", BindingFlags.Instance | BindingFlags.NonPublic); } _showWindowField?.SetValue(instance, visible); } } public static void ReloadUI() { if (!_initialized) { throw new InvalidOperationException("Not initialized"); } UIManagerEx.InitializeUI(_configPath); } public static void SaveCurrentConfig() { DebugWindow instance = DebugWindow.Instance; if (!((Object)(object)instance == (Object)null)) { if (_saveConfigMethod == null) { _saveConfigMethod = typeof(DebugWindow).GetMethod("SaveConfigToFile", BindingFlags.Instance | BindingFlags.NonPublic); } _saveConfigMethod?.Invoke(instance, null); } } private static GameObject FindChildByName(Transform parent, string name) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown if (((Object)parent).name == name) { return ((Component)parent).gameObject; } foreach (Transform item in parent) { GameObject val = FindChildByName(item, name); if ((Object)(object)val != (Object)null) { return val; } } return null; } } [HarmonyPatch] internal static class FontSizeInterceptor { private static bool _installed; private static readonly Dictionary<Text, (NativeButton btn, bool isTitle)> _watched = new Dictionary<Text, (NativeButton, bool)>(); private static readonly HashSet<NativeButton> _traced = new HashSet<NativeButton>(); public static void Install(Harmony harmony) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown if (!_installed) { MethodInfo methodInfo = AccessTools.PropertySetter(typeof(Text), "fontSize"); if (methodInfo == null) { ModLog.Error("[FontSizeTrace] 未找到 Text.fontSize setter,追踪未安装"); return; } harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(FontSizeInterceptor), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _installed = true; ModLog.Info("[FontSizeTrace] Text.fontSize 追踪已安装"); } } public static void Register(NativeButton btn, Text text, bool isTitle, int expected) { if (!((Object)(object)text == (Object)null)) { _watched[text] = (btn, isTitle); } } public static void Unregister(Text text) { if ((Object)(object)text != (Object)null) { _watched.Remove(text); } } private static void Postfix(Text __instance, int value) { if (_watched.Count == 0 || !_watched.TryGetValue(__instance, out (NativeButton, bool) value2)) { return; } var (nativeButton, _) = value2; if (nativeButton != null && !((Object)(object)nativeButton.gameObject == (Object)null)) { int expectedFontSize = nativeButton.ExpectedFontSize; if (expectedFontSize > 0 && value != expectedFontSize && !_traced.Contains(nativeButton)) { _traced.Add(nativeButton); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(string.Format("[FontSizeTrace] ★ 抓到改写者!{0} 的 {1} Text 写入 fontSize={2}(期望 {3})", ((Object)nativeButton.gameObject).name, value2.Item2 ? "title" : "desc", value, expectedFontSize)); stringBuilder.AppendLine("调用栈:"); stringBuilder.Append(Environment.StackTrace); string name = ((Object)((Component)__instance).transform).name; Transform parent = ((Component)__instance).transform.parent; stringBuilder.AppendLine($"\nText 所在: '{name}' 父:'{((parent != null) ? ((Object)parent).name : null)}' active={((Component)__instance).gameObject.activeInHierarchy}"); ModLog.Warning(stringBuilder.ToString()); } } } } public enum NativeUIEventType { Click, ValueChanged, OptionChanged } public class NativeUIEventArgs : EventArgs { public string ControlName { get; set; } public string ControlType { get; set; } public NativeUIEventType EventType { get; set; } public object Value { get; set; } public object Source { get; set; } } public static class NativeUIEventDispatcher { public static event EventHandler<NativeUIEventArgs> OnNativeUIEvent; public static void RegisterControl(NativeButton btn) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown if (btn != null) { btn.OnClick += (UnityAction)delegate { NativeUIEventDispatcher.OnNativeUIEvent?.Invoke(null, new NativeUIEventArgs { ControlName = ((Object)btn.gameObject).name, ControlType = "Button", EventType = NativeUIEventType.Click, Source = btn }); }; } } public static void RegisterControl(NativeSlider slider) { if (slider != null) { slider.OnValueChanged += delegate(float val) { NativeUIEventDispatcher.OnNativeUIEvent?.Invoke(null, new NativeUIEventArgs { ControlName = ((Object)slider.gameObject).name, ControlType = "Slider", EventType = NativeUIEventType.ValueChanged, Value = val, Source = slider }); }; } } public static void RegisterControl(NativeOption opt) { if (opt != null) { opt.OnOptionChanged += delegate(int idx) { NativeUIEventDispatcher.OnNativeUIEvent?.Invoke(null, new NativeUIEventArgs { ControlName = ((Object)opt.gameObject).name, ControlType = "Option", EventType = NativeUIEventType.OptionChanged, Value = idx, Source = opt }); }; } } public static void RegisterControl(NativeInput inp) { if (inp != null) { inp.OnTextChanged += delegate(string text) { NativeUIEventDispatcher.OnNativeUIEvent?.Invoke(null, new NativeUIEventArgs { ControlName = ((Object)inp.gameObject).name, ControlType = "Input", EventType = NativeUIEventType.ValueChanged, Value = text, Source = inp }); }; } } public static void Initialize() { } } public static class PrefabMenuObjects { private static Dictionary<string, GameObject> _prefabs = new Dictionary<string, GameObject>(); private static bool _initialized = false; public static void Initialize() { //IL_03ff: Unknown result type (might be due to invalid IL or missing references) //IL_0406: Expected O, but got Unknown //IL_04aa: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Expected O, but got Unknown //IL_0555: Unknown result type (might be due to invalid IL or missing references) //IL_055c: Expected O, but got Unknown if (_initialized) { return; } _initialized = true; UIManager val = Object.FindObjectOfType<UIManager>(); if ((Object)(object)val == (Object)null) { ModLog.Error("[PrefabMenuObjects] 无法找到 UIManager,使用后备"); CreateFallbackPrefabs(); CreateFallbackSliderPrefab(); CreateFallbackOptionPrefab(); return; } MenuButton val2 = null; if ((Object)(object)val.playModeMenuScreen != (Object)null) { Transform val3 = ((Component)val.playModeMenuScreen).transform.Find("Content"); if ((Object)(object)val3 != (Object)null) { Transform obj = val3.Find("NormalButton"); val2 = ((obj != null) ? ((Component)obj).GetComponent<MenuButton>() : null); if ((Object)(object)val2 == (Object)null) { Transform obj2 = val3.Find("SteelButton"); val2 = ((obj2 != null) ? ((Component)obj2).GetComponent<MenuButton>() : null); } if ((Object)(object)val2 == (Object)null) { Transform obj3 = val3.Find("GGButton"); val2 = ((obj3 != null) ? ((Component)obj3).GetComponent<MenuButton>() : null); } } } if ((Object)(object)val2 != (Object)null) { RegisterPrefab("IconButton", ((Component)val2).gameObject); } else { ModLog.Warning("[PrefabMenuObjects] 未找到 IconButton,使用后备"); } MenuButton val4 = null; if ((Object)(object)val.optionsMenuScreen != (Object)null) { Transform obj4 = ((Component)val.optionsMenuScreen).transform.Find("Content/GameOptions/GameOptionsButton"); val4 = ((obj4 != null) ? ((Component)obj4).GetComponent<MenuButton>() : null); if ((Object)(object)val4 == (Object)null) { Transform obj5 = ((Component)val.optionsMenuScreen).transform.Find("Content/GameOptions/Button"); val4 = ((obj5 != null) ? ((Component)obj5).GetComponent<MenuButton>() : null); } if ((Object)(object)val4 == (Object)null) { val4 = ((Component)val.optionsMenuScreen).GetComponentInChildren<MenuButton>(); } } if ((Object)(object)val4 == (Object)null && (Object)(object)val.mainMenuButtons != (Object)null) { Transform obj6 = ((Component)val.mainMenuButtons).transform.Find("StartGameButton"); val4 = ((obj6 != null) ? ((Component)obj6).GetComponent<MenuButton>() : null); } if ((Object)(object)val4 != (Object)null) { RegisterPrefab("TextButton", ((Component)val4).gameObject); } else { ModLog.Warning("[PrefabMenuObjects] 未找到 TextButton,使用后备"); } MenuButton val5 = null; if ((Object)(object)val.optionsMenuScreen != (Object)null) { Transform obj7 = ((Component)val.optionsMenuScreen).transform.Find("Controls/ApplyButton"); val5 = ((obj7 != null) ? ((Component)obj7).GetComponent<MenuButton>() : null); } if ((Object)(object)val5 != (Object)null) { RegisterPrefab("SmallButton", ((Component)val5).gameObject); } else if ((Object)(object)val4 != (Object)null) { RegisterPrefab("SmallButton", ((Component)val4).gameObject); } else { ModLog.Warning("[PrefabMenuObjects] 未找到 SmallButton,使用后备"); } if (!_prefabs.ContainsKey("IconButton") || !_prefabs.ContainsKey("TextButton") || !_prefabs.ContainsKey("SmallButton")) { CreateFallbackPrefabs(); } Text val6 = null; if ((Object)(object)val.optionsMenuScreen != (Object)null) { Transform val7 = ((Component)val.optionsMenuScreen).transform.Find("Title"); if ((Object)(object)val7 != (Object)null) { val6 = ((Component)val7).GetComponent<Text>(); } } if ((Object)(object)val6 == (Object)null && (Object)(object)val.mainMenuScreen != (Object)null) { Transform val8 = ((Component)val.mainMenuScreen).transform.Find("Title"); if ((Object)(object)val8 != (Object)null) { val6 = ((Component)val8).GetComponent<Text>(); } } if ((Object)(object)val6 != (Object)null) { RegisterPrefab("StandardLabel", ((Component)val6).gameObject); } else { CreateFallbackLabelPrefab(); } GameObject val9 = null; if ((Object)(object)val.audioMenuScreen != (Object)null) { Transform val10 = ((Component)val.audioMenuScreen).transform.Find("Content/MasterVolume/MasterSlider"); if ((Object)(object)val10 != (Object)null) { val9 = ((Component)val10).gameObject; } } if ((Object)(object)val9 != (Object)null) { RegisterPrefab("Slider", val9); } else { CreateFallbackSliderPrefab(); } GameObject val11 = null; if ((Object)(object)val.gamepadMenuScreen != (Object)null) { Transform val12 = ((Component)val.gamepadMenuScreen).transform.Find("Controls/RumbleSetting"); if ((Object)(object)val12 != (Object)null) { Transform val13 = val12.Find("RumblePopupOption"); if ((Object)(object)val13 != (Object)null) { val11 = ((Component)val13).gameObject; } } } if ((Object)(object)val11 == (Object)null && (Object)(object)val.gameOptionsMenuScreen != (Object)null) { Transform val14 = ((Component)val.gameOptionsMenuScreen).transform.Find("Content"); if ((Object)(object)val14 != (Object)null) { foreach (Transform item in val14) { Transform val15 = item; if ((Object)(object)val15.Find("Menu Option Label") != (Object)null && (Object)(object)val15.Find("Menu Option Text") != (Object)null) { val11 = ((Component)val15).gameObject; break; } } } } if ((Object)(object)val11 == (Object)null && (Object)(object)val.videoMenuScreen != (Object)null) { Transform val16 = ((Component)val.videoMenuScreen).transform.Find("Content"); if ((Object)(object)val16 != (Object)null) { foreach (Transform item2 in val16) { Transform val17 = item2; if ((Object)(object)val17.Find("Menu Option Label") != (Object)null && (Object)(object)val17.Find("Menu Option Text") != (Object)null) { val11 = ((Component)val17).gameObject; break; } } } } if ((Object)(object)val11 == (Object)null && (Object)(object)val.audioMenuScreen != (Object)null) { Transform val18 = ((Component)val.audioMenuScreen).transform.Find("Content"); if ((Object)(object)val18 != (Object)null) { foreach (Transform item3 in val18) { Transform val19 = item3; if ((Object)(object)val19.Find("Menu Option Label") != (Object)null && (Object)(object)val19.Find("Menu Option Text") != (Object)null) { val11 = ((Component)val19).gameObject; break; } } } } if ((Object)(object)val11 != (Object)null) { RegisterPrefab("Option", val11); } else { CreateFallbackOptionPrefab(); } } private static void CreateFallbackPrefabs() { CreateFallbackButton("IconButton"); CreateFallbackButton("TextButton"); CreateFallbackButton("SmallButton"); } private static void CreateFallbackButton(string key) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("Fallback" + key); val.SetActive(false); val.AddComponent<MenuButton>(); ((Graphic)val.AddComponent<Image>()).color = Color.gray; val.GetComponent<RectTransform>().sizeDelta = new Vector2(200f, 80f); GameObject val2 = new GameObject("Text"); val2.transform.SetParent(val.transform, false); Text obj = val2.AddComponent<Text>(); obj.text = "Button"; obj.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); obj.fontSize = 30; obj.alignment = (TextAnchor)4; ((Graphic)obj).color = Color.white; ((Component)obj).GetComponent<RectTransform>().sizeDelta = new Vector2(200f, 80f); if (key == "IconButton") { GameObject val3 = new GameObject("Image"); val3.transform.SetParent(val.transform, false); ((Graphic)val3.AddComponent<Image>()).color = Color.white; } RegisterPrefab(key, val); ModLog.Warning("[PrefabMenuObjects] 使用后备按钮预制体: " + key); } private static void CreateFallbackLabelPrefab() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("FallbackLabel"); val.SetActive(false); Text obj = val.AddComponent<Text>(); obj.text = "Label"; obj.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); obj.fontSize = 30; ((Graphic)obj).color = Color.white; obj.alignment = (TextAnchor)4; val.GetComponent<RectTransform>().sizeDelta = new Vector2(400f, 60f); RegisterPrefab("StandardLabel", val); ModLog.Warning("[PrefabMenuObjects] 使用后备标签预制体"); } private static void CreateFallbackSliderPrefab() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("FallbackSlider"); val.SetActive(false); val.AddComponent<Slider>(); GameObject val2 = new GameObject("Menu Option Label"); val2.transform.SetParent(val.transform, false); Text obj = val2.AddComponent<Text>(); obj.text = "Label"; obj.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); obj.fontSize = 30; GameObject val3 = new GameObject("Value"); val3.transform.SetParent(val.transform, false); Text obj2 = val3.AddComponent<Text>(); obj2.text = "0"; obj2.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); obj2.fontSize = 24; RegisterPrefab("Slider", val); ModLog.Warning("[PrefabMenuObjects] 使用后备滑块预制体"); } private static void CreateFallbackOptionPrefab() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("FallbackOption"); val.SetActive(false); val.AddComponent<RectTransform>().sizeDelta = new Vector2(600f, 80f); val.AddComponent<MenuButton>(); GameObject val2 = new GameObject("Menu Option Label"); val2.transform.SetParent(val.transform, false); Text obj = val2.AddComponent<Text>(); obj.text = "标签"; obj.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); obj.fontSize = 30; obj.alignment = (TextAnchor)3; GameObject val3 = new GameObject("Menu Option Text"); val3.transform.SetParent(val.transform, false); Text obj2 = val3.AddComponent<Text>(); obj2.text = "值"; obj2.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); obj2.fontSize = 28; obj2.alignment = (TextAnchor)5; GameObject val4 = new GameObject("Description"); val4.transform.SetParent(val.transform, false); Text obj3 = val4.AddComponent<Text>(); obj3.text = "描述"; obj3.font = Resources.GetBuiltinResource<Font>("Arial.ttf"); obj3.fontSize = 24; ((Graphic)obj3).color = Color.gray; RegisterPrefab("Option", val); ModLog.Warning("[PrefabMenuObjects] 使用后备选项行预制体"); } private static void RegisterPrefab(string key, GameObject source) { if (!((Object)(object)source == (Object)null)) { GameObject val = Object.Instantiate<GameObject>(source); ((Object)val).name = "Prefab_" + key; val.SetActive(false); Object.DontDestroyOnLoad((Object)(object)val); _prefabs[key] = val; } } public static GameObject Get(string key) { if (_prefabs.TryGetValue(key, out var value) && (Object)(object)value != (Object)null) { return value; } ModLog.Error("[PrefabMenuObjects] 预制体 " + key + " 不存在"); return null; } } public static class UILocale { private static bool? _forceChinese; private static bool _cachedIsChinese; private static bool _langCached; private static readonly Dictionary<string, string> EnglishTranslations; private static readonly Dictionary<string, string> ControlTextTranslations; private static readonly Dictionary<string, string> ChineseToEnglish; private static readonly Dictionary<string, string> EnglishToChinese; public static bool IsChinese { get { if (_forceChinese.HasValue) { return _forceChinese.Value; } if (!_langCached) { _cachedIsChinese = DetectChinese(); _langCached = true; } return _cachedIsChinese; } } static UILocale() { _forceChinese = null; _cachedIsChinese = false; _langCached = false; EnglishTranslations = new Dictionary<string, string>(); ControlTextTranslations = new Dictionary<string, string> { { "经典模式", "Classic" }, { "钢魂模式", "Steel" }, { "随机模式", "Random" }, { "房间随机", "Room" }, { "物品随机", "Item" }, { "陷阱随机", "Trap" }, { "怪物随机", "Enemy" }, { "详细设置", "Detail" }, { "返回模式选择", "Back" }, { "确认并开始游戏", "Start" }, { "开始随机", "Start Random" }, { "生成随机种子", "Gen Seed" }, { "随机种子:", "Seed:" }, { "技能随机: 已启用", "Skill: On" }, { "纹章随机: 已启用", "Crest: On" }, { "上劈", "Up" }, { "左劈", "Left" }, { "右劈", "Right" }, { "下劈 (默认)", "Down" }, { "开", "On" }, { "关", "Off" }, { "重置种子世界", "Reset Seed" }, { "技能随机模式", "Skill Mode" }, { "总随机", "Total" }, { "分类随机", "Type" }, { "开局物品数量", "Items" }, { "技能总数量(0-13)", "Total Skills" }, { "垂直技能(0-5)", "Vertical" }, { "水平技能(0-4)", "Horizontal" }, { "特殊技能(0-4)", "Special" }, { "攻击技能(0-5)", "Attack" }, { "游戏模式", "Mode" }, { "彻底疯狂", "Crazy" }, { "纹章诅咒", "Crest" }, { "全随机模式", "FullRand" }, { "丝之心、疾跑和上冲", "SilkDashUp" }, { "显示完成度", "Completion" }, { "应用种子", "Apply Seed" }, { "显示场景名", "Show Scene" }, { "显示种子", "Show Seed" }, { "陷阱难度", "Trap Diff" }, { "初猎", "Easy" }, { "专注", "Normal" }, { "满溢", "Hard" }, { "陷阱生命化", "Trap Life" }, { "重置冰冻黑名单", "Reset Frost" }, { "重置商店记录", "Reset Shop" }, { "重置捡拾记录", "Reset Pickup" }, { "随机缩放开关", "Rand Scale" }, { "缩放最小值", "Min Scale" }, { "缩放最大值", "Max Scale" }, { "分裂选择:", "Split:" }, { "疾风步", "Swift" }, { "飞针", "Harpoon" }, { "流浪者披风", "Cloak" }, { "回血", "Heal" }, { "劈方向", "Slash" }, { "爬墙", "WallClimb" }, { "警告:重置后当前种子世界将重新生成,所有拾取点会重生,技能触发器也会重置。", "Warning: Reset world!" }, { "总体|垂直、水平、特殊、攻击", "Total|Vert,Hor,Spec,Atk" }, { "输入种子", "Enter Seed" }, { "房间种子", "Room Seed" }, { "当前物品种子:", "Curr Item Seed:" }, { "货币首次保底:", "First Pity:" }, { "货币二次保底:", "Second Pity:" }, { "丝矛保底次数:", "SilkSpear Pity:" }, { "开局相关设置", "Startup Settings" }, { "技能分类随机", "Skill Type Random" }, { "辅助设置", "Aux Settings" }, { "物品随机设置", "Item Random Settings" }, { "物品随机池", "Item Pool" }, { "纹章、技能、遗物类型开关", "Toggle Crests, Skills, Relics" }, { "起始地点", "Start Location" }, { "暂未实现", "Not Yet" }, { "诅咒选项", "Curse Options" }, { "纹章诅咒等", "Crest Curses etc." }, { "重复物品", "Repeat Items" }, { "配置各类物品最大获得次数", "Configure Max Dupes" }, { "花费随机化", "Cost Random" }, { "虚拟奖励池: 无限/有限", "Virtual Reward: Infinite/Limited" }, { "商店随机: 已启用", "Shop Random: Enabled" }, { "捡拾随机: 已启用", "Pickup Random: Enabled" }, { "物品随机池类型", "Item Pool Types" }, { "纹章", "Crests" }, { "技能", "Skills" }, { "遗物", "Relics" }, { "重复物品数量配置", "Repeat Limit Config" }, { "起始地点(暂未实现)", "Start Location (WIP)" }, { "全随机模式分裂:上劈、左劈、右劈、冲刺左/右、飞针左/右、漂浮左/右、壁跳左/右、回血", "Full Random splits:Up/Left/Right Slash,Dash L/R,Harpoon L/R,Float L/R,WallJump L/R,Heal" }, { "陷阱池:暗雷、跳跳乐、尖刺类、天花板障碍等", "Trap Pool: Dark Mines, Platforming, Spikes, Ceiling Hazards..." }, { "血量调整:所有怪物血量与原始一致", "HP: All enemies have original HP" }, { "禁用场景列表 (只读):Belltown_04, Bellshrine, Bone_East_Umbrella, Room_Pinstress ...", "Disabled Rooms (Read-only): ..." }, { "纹章随机", "Crest Random" }, { "技能类物品", "Skill Items" }, { "遗物随机", "Relic Random" }, { "疾风步 飞针 流浪者披风 回血 劈方向 爬墙", "SwiftStep Harpoon Wan's Cloak Heal SlashDirect Walljump" }, { "返回主页面", "Back to Main" }, { "应用", "Apply" }, { "返回", "Back" }, { "确认并开始游戏\n", "Start" }, { "开\n", "On\n" }, { "关\n", "Off\n" }, { "房间随机\n", "Room\n" }, { "物品随机\n", "Item\n" }, { "陷阱随机\n", "Trap\n" }, { "怪物随机\n", "Enemy\n" }, { "随机种子:\n", "Seed:\n" }, { "房间种子:", "Room Seed:" }, { "第一次保底次数 (默认30)", "First pity count (default 30)" }, { "第二次保底次数 (默认1000)", "Second pity count (default 1000)" }, { "丝矛保底触发次数 (默认10)", "SilkSpear pity trigger (default 10)" }, { "全房间", "Full" }, { "区域", "Map" }, { "普通", "Normal" }, { "全随机", "Full Random" }, { "返回设置", "Back to Settings" }, { "开始游戏", "Start Game" }, { "输入...", "Enter..." }, { "蓄力斩", "Charge Slash" }, { "冲刺左", "Dash Left" }, { "冲刺右", "Dash Right" }, { "雪绒披风", "Double Jump" }, { "风铃摇", "Eva Heal" }, { "幻兽歌", "Fast Travel" }, { "漂浮左", "Float Left" }, { "漂浮右", "Float Right" }, { "飞针左", "Harpoon Left" }, { "飞针右", "Harpoon Right" }, { "面具碎片", "Heart Piece" }, { "丝线恢复上限+1", "Max Silk Regen +1" }, { "丝之矛", "Needle Throw" }, { "丝忆弦针", "Needolin" }, { "深邃挽歌", "Needolin Memory" }, { "其他物品", "Other Items" }, { "格挡", "Parry" }, { "符文之怒", "Silk Bomb" }, { "苍白之爪", "Silk Boss Needle" }, { "丝刃标", "Silk Charge" }, { "丝轴碎片", "Spool Part" }, { "灵丝升腾", "Super Jump" }, { "灵丝风暴", "Thread Sphere" }, { "纹章槽位解锁器", "Crest Slot Unlocker" }, { "蛛攀术", "Wall Climb" }, { "壁跳左", "Wall Jump Left" }, { "壁跳右", "Wall Jump Right" }, { "丝获得随机", "Silk Random" }, { "随机种子计算", "Seed Calculator" }, { "种子(可手填已验证种子):", "Seed (type verified seed):" }, { "正在计算可行种子,请稍候…", "Calculating viable seed, please wait..." }, { "随机化进度", "Randomizer Progress" }, { "耗时", "Time Elapsed" }, { "尝试", "Attempts" }, { "已试候选", "Candidates tried" }, { "候选", "Candidate" }, { "活种", "live seed" }, { "死种", "dead seed" }, { "可行种子", "Viable Seed" }, { "种子", "Seed" }, { "异常", "Exception" }, { "模拟预筛未过", "failed sim pre-filter" }, { "丝矛保底触发次数 (默认5)", "SilkSpear pity trigger (default 5)" }, { "回到存档页面", "Back to Saves" }, { "披风", "Cape" }, { "能力随机(神龛/触发点):", "Ability Random (shrines/triggers):" }, { "关 = 技能神龛与能力触发点走原生流程(改动后需重开档生效)", "Off = shrines and ability triggers use vanilla flow (restart to apply)" }, { "任务奖励", "Quest Rewards" }, { "首领奖励", "Boss Rewards" }, { "难度", "Difficulty" }, { "难度:简单", "Difficulty: Easy" }, { "难度分级(实验性)", "Difficulty (Experimental)" }, { "难度分级(实验性):影响技巧门容忍度与珍贵物品落点深浅", "Difficulty (experimental): affects technique tolerance and how deep valuable items land" }, { "简单", "Easy" }, { "困难", "Hard" }, { "极限", "Extreme" }, { "难度递增:技巧容忍度降低,珍贵物品更靠后。", "Higher difficulty = tighter technique tolerance, valuable items pushed further back." } }; ChineseToEnglish = new Dictionary<string, string>(); EnglishToChinese = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> item in new Dictionary<string, string> { { "NativeUIMaker 调试窗口", "UI Debug" }, { "=== 创建新按钮 ===", "=== New Button ===" }, { "选择按钮样式:", "Style:" }, { "图标按钮", "Icon" }, { "纯文字按钮", "Text" }, { "小型按钮", "Small" }, { "图标文件路径 (绝对或相对路径,留空则不设置):", "Icon Path:" }, { "切换文字序列(逗号分隔):", "Toggle Texts:" }, { "创建 {0}", "Create {0}" }, { "新按钮", "NewBtn" }, { "可编辑描述", "Desc" }, { "按钮被点击", "Clicked" }, { "=== 已创建的按钮 ===", "=== Buttons ===" }, { "编辑按钮: {0}", "Edit Btn: {0}" }, { "标题:", "Title:" }, { "描述:", "Desc:" }, { "位置 (x, y):", "Pos XY:" }, { "尺寸 (宽, 高):", "Size WH:" }, { "图标偏移 (x, y):", "Icon Offset:" }, { "应用图标偏移", "Apply Icon" }, { "标题文字偏移 (x, y):", "Title Offset:" }, { "应用标题偏移", "Apply Title" }, { "描述文字偏移 (x, y):", "Desc Offset:" }, { "应用描述偏移", "Apply Desc" }, { "允许拖拽 (按住鼠标左键拖动)", "Draggable" }, { "设置切换文字序列(逗号分隔):", "Set Toggle Texts:" }, { "应用切换序列", "Apply Toggle" }, { "应用更改", "Apply" }, { "删除此控件", "Delete" }, { "=== 创建新标签 ===", "=== New Label ===" }, { "创建文本标签 (StandardLabel)", "Create Label" }, { "新标签", "NewLabel" }, { "=== 已创建的标签 ===", "=== Labels ===" }, { "编辑标签: {0}", "Edit Label: {0}" }, { "文本:", "Text:" }, { "字体大小:", "Font Size:" }, { "颜色 (R,G,B):", "Color RGB:" }, { "固定到当前页面", "Pin to Current Page" }, { "=== 创建新滑块 ===", "=== New Slider ===" }, { "创建滑块 (NativeSlider)", "Create Slider" }, { "新滑块", "NewSlider" }, { "滑块 {0}: {1} 当前值={2}", "Slider {0}: {1} val={2}" }, { "未命名", "Unnamed" }, { "编辑滑块: {0}", "Edit Slider: {0}" }, { "当前值: {0}", "Val: {0}" }, { "标签:", "Label:" }, { "滑块 X 偏移:", "Slider X Off:" }, { "滑块宽度 (0=原生):", "Slider Width:" }, { "标签 X 偏移:", "Label X Off:" }, { "数值 X 偏移:", "Value X Off:" }, { "最小值: {0}", "Min: {0}" }, { "最大值: {0}", "Max: {0}" }, { "整数步进:", "Int Step:" }, { "=== 创建新选项行 (无滑块) ===", "=== New Option ===" }, { "创建选项行 (NativeOption)", "Create Option" }, { "新选项", "NewOpt" }, { "这是描述文字", "Desc text" }, { "选项 {0}: {1} 当前值={2}", "Opt {0}: {1} val={2}" }, { "编辑选项行: {0}", "Edit Opt: {0}" }, { "选项列表 (用逗号分隔):", "Options:" }, { "当前选中: {0} (索引 {1})", "Selected: {0} (idx {1})" }, { "上一个", "Prev" }, { "下一个", "Next" }, { "=== 创建新箭头 ===", "=== New Arrow ===" }, { "左箭头", "Left" }, { "右箭头", "Right" }, { "上箭头", "Up" }, { "下箭头", "Down" }, { "=== 已创建的箭头 ===", "=== Arrows ===" }, { "箭头 {0}: {1} 位置={2}", "Arrow {0}: {1} pos={2}" }, { "编辑箭头: {0}", "Edit Arrow: {0}" }, { "方向:", "Dir:" }, { "左", "L" }, { "右", "R" }, { "上", "U" }, { "下", "D" }, { "播放动画 (闪烁)", "Flash" }, { "可点击 (添加按钮)", "Clickable" }, { "=== 创建新输入框 ===", "=== New Input ===" }, { "创建输入框", "Create Input" }, { "=== 已创建的输入框 ===", "=== Inputs ===" }, { "输入框 {0}: {1}", "Input {0}: {1}" }, { "编辑输入框", "Edit Input" }, { "文本内容:", "Text:" }, { "占位符:", "Placeholder:" }, { "输入...", "Enter..." }, { "扫描外部控件", "Scan External" }, { "保存配置", "Save Config" }, { "加载配置", "Load Config" }, { "点击“扫描外部控件”以发现其他模组创建的UI元素。", "Click Scan to find UI from other mods." }, { "外部按钮", "Ext Btns" }, { "外部标签", "Ext Labels" }, { "外部滑块", "Ext Sliders" }, { "外部选项行", "Ext Options" }, { "外部箭头", "Ext Arrows" }, { "外部输入框", "Ext Inputs" }, { "页面管理", "Page Mgmt" }, { "可用页面:", "Pages:" }, { "页面 {0}: {1}", "Page {0}: {1}" }, { "当前页面: {0} 包含控件: {1}", "Curr: {0} ({1} ctls)" }, { "保存页面配置", "Save Page" }, { "加载页面配置", "Load Page" }, { "刷新", "Refresh" }, { "页面内控件列表:", "Page Controls:" }, { "位置", "Pos" }, { "隐藏窗口", "Hide" }, { "本地控件", "Local" }, { "外部控件", "External" }, { "CN", "CN" }, { "EN", "EN" }, { "Auto", "Auto" }, { "创建目标:", "Target:" }, { "全局画布 (独立于页面)", "Global Canvas" }, { "全局画布", "Global" }, { "当前:", "Curr:" }, { "未选中任何控件", "No sel" }, { "控件已被销毁", "Destroyed" }, { "选项1", "Opt1" }, { "选项2", "Opt2" }, { "按钮 {0}: {1}", "Btn {0}: {1}" }, { "标签 {0}: {1}", "Label {0}: {1}" }, { "箭头被点击", "Arrow clicked" }, { "应用", "Apply" }, { "关闭", "Close" }, { "技能类物品", "Skill Items" }, { "遗物", "Relic" }, { "其他物品", "Other Items" }, { "上劈", "Up Slash" }, { "左劈", "Left Slash" }, { "右劈", "Right Slash" }, { "冲刺左", "Dash Left" }, { "冲刺右", "Dash Right" }, { "飞针左", "Harpoon Left" }, { "飞针右", "Harpoon Right" }, { "漂浮左", "Float Left" }, { "漂浮右", "Float Right" }, { "壁跳左", "Wall Jump Left" }, { "壁跳右", "Wall Jump Right" }, { "丝之矛", "Needle Throw" }, { "灵丝风暴", "Thread Sphere" }, { "丝刃标", "Silk Charge" }, { "符文之怒", "Silk Bomb" }, { "苍白之爪", "Silk Boss Needle" }, { "丝忆弦针", "Needolin" }, { "格挡", "Parry" }, { "深邃挽歌", "Needolin Memory" }, { "幻兽歌", "Fast Travel" }, { "风铃摇", "Eva Heal" }, { "雪绒披风", "Double Jump" }, { "灵丝升腾", "Super Jump" }, { "蛛攀术", "Wall Climb" }, { "蓄力斩", "Charge Slash" }, { "面具碎片", "Heart Piece" }, { "丝轴碎片", "Spool Part" }, { "丝线恢复上限+1", "Max Silk Regen +1" }, { "纹章槽位解锁器", "Crest Slot Unlocker" }, { "正在计算可行种子,请稍候…", "Calculating viable seed, please wait..." }, { "正在预筛候选种子(第 ", "Pre-filtering candidate seeds (round " }, { "预筛中… 候选: ", "Pre-filtering... Candidate: " }, { "已找到预筛候选: ", "Candidate found: " }, { "正在用游戏真实分配做最终确认(较慢,请耐心等待)…", "Final confirm with real game allocation (slow, please wait)..." }, { "活种确认完成,可以开始游戏", "Seed confirmed, ready to start" }, { "可行种子: ", "Viable seed: " }, { "已采用手填种子", "Using manually entered seed" }, { "种子: ", "Seed: " }, { "计算已取消,返回设置页", "Canceled, back to settings" }, { "计算已取消,保留当前种子", "Canceled, keeping current seed" }, { "计算失败,保留当前种子", "Calculation failed, keeping current seed" }, { "未找到完全活种,已采用最优解种子", "No full live seed, using best seed" }, { "最优解种子: ", "Best seed: " }, { "用户手填", "Manually entered" }, { "开始游戏", "Start Game" }, { "返回设置", "Back to Settings" }, { "SeedInput 控件未就绪,跳过随机种子", "SeedInput not ready yet, skipping auto seed" }, { "尝试", "Attempts" }, { "已试候选", "Candidates tried" }, { "候选", "Candidate" }, { "随机化进度", "Randomizer Progress" }, { "耗时", "Time Elapsed" }, { "活种", "live seed" }, { "死种", "dead seed" }, { "可行种子", "Viable Seed" }, { "种子", "Seed" }, { "异常", "Exception" }, { "模拟预筛未过", "failed sim pre-filter" }, { "难度:", "Difficulty: " }, { "简单", "Easy" }, { "普通", "Normal" }, { "困难", "Hard" }, { "极限", "Extreme" } }) { if (!EnglishTranslations.ContainsKey(item.Key)) { EnglishTranslations.Add(item.Key, item.Value); } else { ModLog.Warning("[UILocale] Duplicate key ignored: " + item.Key); } } foreach (KeyValuePair<string, string> controlTextTranslation in ControlTextTranslations) { string key = controlTextTranslation.Key; string value = controlTextTranslation.Value; if (!ChineseToEnglish.ContainsKey(key)) { ChineseToEnglish.Add(key, value); } if (!EnglishToChinese.ContainsKey(value)) { EnglishToChinese.Add(value, key); } } } public static void SetForceChinese(bool? forceChinese) { _forceChinese = forceChinese; _langCached = false; } public static string Get(string chineseText) { if (string.IsNullOrEmpty(chineseText)) { return chineseText; } if (IsChinese) { return chineseText; } if (!EnglishTranslations.TryGetValue(chineseText, out var value)) { return chineseText; } return value; } public static void TranslateControlConfig(UIControlConfig cfg) { if (cfg == null) { return; } if (IsChinese) { if (!string.IsNullOrEmpty(cfg.title)) { cfg.title = TranslateFromEnglish(cfg.title); } if (!string.IsNullOrEmpty(cfg.description)) { cfg.description = TranslateFromEnglish(cfg.description); } if (!string.IsNullOrEmpty(cfg.labelText)) { cfg.labelText = TranslateFromEnglish(cfg.labelText); } if (cfg.toggleTexts != null) { for (int i = 0; i < cfg.toggleTexts.Length; i++) { cfg.toggleTexts[i] = TranslateFromEnglish(cfg.toggleTexts[i]); } } if (cfg.options != null) { for (int j = 0; j < cfg.options.Length; j++) { cfg.options[j] = TranslateFromEnglish(cfg.options[j]); } } if (!string.IsNullOrEmpty(cfg.inputText)) { cfg.inputText = TranslateFromEnglish(cfg.inputText); } if (!string.IsNullOrEmpty(cfg.placeholderText)) { cfg.placeholderText = TranslateFromEnglish(cfg.placeholderText); } return; } if (!string.IsNullOrEmpty(cfg.title)) { cfg.title = TranslateFromChinese(cfg.title); } if (!string.IsNullOrEmpty(cfg.description)) { cfg.description = TranslateFromChinese(cfg.description); } if (!string.IsNullOrEmpty(cfg.labelText)) { cfg.labelText = TranslateFromChinese(cfg.labelText); } if (cfg.toggleTexts != null) { for (int k = 0; k < cfg.toggleTexts.Length; k++) { cfg.toggleTexts[k] = TranslateFromChinese(cfg.toggleTexts[k]); } } if (cfg.options != null) { for (int l = 0; l < cfg.options.Length; l++) { cfg.options[l] = TranslateFromChinese(cfg.options[l]); } } if (!string.IsNullOrEmpty(cfg.inputText)) { cfg.inputText = TranslateFromChinese(cfg.inputText); } if (!string.IsNullOrEmpty(cfg.placeholderText)) { cfg.placeholderText = TranslateFromChinese(cfg.placeholderText); } } private static string TranslateFromChinese(string chinese) { if (string.IsNullOrEmpty(chinese)) { return chinese; } if (ChineseToEnglish.TryGetValue(chinese, out var value)) { return value; } string text = chinese.TrimEnd(new char[1] { '\n' }); if (text != chinese && ChineseToEnglish.TryGetValue(text, out value)) { return value + (chinese.EndsWith("\n") ? "\n" : ""); } return chinese; } private static string TranslateFromEnglish(string english) { if (string.IsNullOrEmpty(english)) { return english; } if (EnglishToChinese.TryGetValue(english, out var value)) { return value; } string text = english.TrimEnd(new char[1] { '\n' }); if (text != english && EnglishToChinese.TryGetValue(text, out value)) { return value + (english.EndsWith("\n") ? "\n" : ""); } return english; } private static bool DetectChinese() { try { Type type = Type.GetType("FontManager, Assembly-CSharp"); if (type != null) { FieldInfo field = type.GetField("_currentLanguage", BindingFlags.Static | BindingFlags.NonPublic); if (field != null) { object value = field.GetValue(null); if (value != null) { string text = value.ToString().ToUpper(); if (text == "ZH" || text == "ZH_TW") { return true; } } } } } catch { } try { GameSettings val = GameManager.instance?.gameSettings; if (val != null) { FieldInfo field2 = ((object)val).GetType().GetField("language", BindingFlags.Instance | BindingFlags.Public); if (field2 != null) { object value2 = field2.GetValue(val); if (value2 != null) { string text2 = value2.ToString().ToUpper(); if (text2 == "ZH" || text2 == "ZH_TW") { return true; } } } } } catch { } return false; } } public static class UIManagerEx { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Func<UIControlConfig, string> <>9__8_0; public static Func<string, bool> <>9__8_1; public static Func<NativePage, bool> <>9__12_0; public static Predicate<NativePage> <>9__14_0; public static Predicate<NativeButton> <>9__14_1; public static Predicate<NativeLabel> <>9__14_2; public static Predicate<NativeSlider> <>9__14_3; public static Predicate<NativeOption> <>9__14_4; public static Predicate<NativeInput> <>9__14_5; public static Predicate<NativeArrow> <>9__14_6; public static UnityAction <>9__20_0; internal string <InitializeUI>b__8_0(UIControlConfig c) { return c.page; } internal bool <InitializeUI>b__8_1(string p) { return !string.IsNullOrEmpty(p); } internal bool <GetCurrentPage>b__12_0(NativePage p) { return p?.isShowing ?? false; } internal bool <ResetUI>b__14_0(NativePage p) { if (p != null) { return (Object)(object)p.gameObject == (Object)null; } return true; } internal bool <ResetUI>b__14_1(NativeButton b) { if (b != null) { return (Object)(object)b.gameObject == (Object)null; } return true; } internal bool <ResetUI>b__14_2(NativeLabel l) { if (l != null) { return (Object)(object)l.gameObject == (Object)null; } return true; } internal bool <ResetUI>b__14_3(NativeSlider s) { if (s != null) { return (Object)(object)s.gameObject == (Object)null; } return true; } internal bool <ResetUI>b__14_4(NativeOption o) { if (o != null) { return (Object)(object)o.gameObject == (Object)null; } return true; } internal bool <ResetUI>b__14_5(NativeInput i) { if (i != null) { return (Object)(object)i.gameObject == (Object)null; } return true; } internal bool <ResetUI>b__14_6(NativeArrow a) { if (a != null) { return (Object)(object)a.gameObject == (Object)null; } return true; } internal void <ApplyArrowConfig>b__20_0() { ModLog.Info("箭头被点击"); } } private static Dictionary<string, NativePage> _pageCache = new Dictionary<string, NativePage>(); public static bool IsUIReady { get; private set; } = false; public static event Action OnUIReady; public static void InitializeUI(string configPath) { if (IsUIReady) { return; } if (string.IsNullOrEmpty(configPath) || !File.Exists(configPath)) { ModLog.Error("[UIManagerEx] 配置文件不存在: " + configPath); return; } ConfigData configData = JsonConvert.DeserializeObject<ConfigData>(File.ReadAllText(configPath)); if (configData == null || configData.controls == null) { ModLog.Error("[UIManagerEx] 配置文件无效"); return; } foreach (UIControlConfig control in configData.controls) { UILocale.TranslateControlConfig(control); } RectTransform defaultParent = UIParent.GetDefaultParent(); if ((Object)(object)defaultParent == (Object)null) { ModLog.Error("[UIManagerEx] 无法获取父物体"); return; } _pageCache.Clear(); foreach (NativePage allInstance in NativePage.AllInstances) { if (allInstance != null && (Object)(object)allInstance.gameObject != (Object)null) { _pageCache[((Object)allInstance.gameObject).name] = allInstance; } } foreach (string item in (from c in configData.controls select c.page into p where !string.IsNullOrEmpty(p) select p).Distinct().ToList()) { if (!_pageCache.ContainsKey(item)) { ModLog.Info("[UIManagerEx] 创建页面: " + item); NativePage nativePage = new NativePage(item, defaultParent, addBackButton: false); nativePage.Hide(); _pageCache[item] = nativePage; } } foreach (UIControlConfig control2 in configData.controls) { if (!string.IsNullOrEmpty(control2.page)) { if (!_pageCache.TryGetValue(control2.page, out var value)) { ModLog.Error("[UIManagerEx] 页面 " + control2.page + " 不存在,控件 " + control2.name + " 创建失败"); } else { CreateControl(control2, value.gameObject.transform); } } } Canvas.ForceUpdateCanvases(); foreach (NativePage allInstance2 in NativePage.AllInstances) { allInstance2.Hide(); } NativeUIEventDispatcher.Initialize(); IsUIReady = true; UIManagerEx.OnUIReady?.Invoke(); ModLog.Info($"[UIManagerEx] UI 初始化完成,所有页面已隐藏(控件 {configData.controls.Count} 个)"); } public static void ShowPage(string pageName) { if (!_pageCache.TryGetValue(pageName, out var value) || value == null) { value = NativePage.AllInstances.FirstOrDefault((NativePage p) => (Object)(object)p.gameObject != (Object)null && ((Object)p.gameObject).name == pageName); if (value == null) { ModLog.Error("[UIManagerEx] 页面 " + pageName + " 不存在"); return; } _pageCache[pageName] = value; } foreach (NativePage allInstance in NativePage.AllInstances) { if (allInstance != value) { allInstance.Hide(); } } value.Show(); } public static void HideAllPages() { foreach (NativePage allInstance in NativePage.AllInstances) { allInstance?.Hide(); } } public static void HidePage(string pageName) { if (_pageCache.TryGetValue(pageName, out var value) && value != null) { value.Hide(); return; } value = NativePage.AllInstances.FirstOrDefault((NativePage p) => (Object)(object)p.gameObject != (Object)null && ((Object)p.gameObject).name == pageName); if (value != null) { _pageCache[pageName] = value; value.Hide(); } } public static NativePage GetCurrentPage() { return NativePage.AllInstances.FirstOrDefault((NativePage p) => p?.isShowing ?? false); } public static bool IsUIDestroyed() { if (!IsUIReady) { return false; } bool flag = false; foreach (KeyValuePair<string, NativePage> item in _pageCache) { if (item.Value != null && (Object)(object)item.Value.gameObject != (Object)null) { flag = true; break; } } return !flag; } public static void ResetUI() { IsUIReady = false; _pageCache.Clear(); NativePage.AllInstances.RemoveAll((NativePage p) => p == null || (Object)(object)p.gameObject == (Object)null); NativeButton.AllInstances.RemoveAll((NativeButton b) => b == null || (Object)(object)b.gameObject == (Object)null); NativeLabel.AllInstances.RemoveAll((NativeLabel l) => l == null || (Object)(object)l.gameObject == (Object)null); NativeSlider.AllInstances.RemoveAll((NativeSlider s) => s == null || (Object)(object)s.gameObject == (Object)null); NativeOption.AllInstances.RemoveAll((NativeOption o) => o == null || (Object)(object)o.gameObject == (Object)null); NativeInput.AllInstances.RemoveAll((NativeInput i) => i == null || (Object)(object)i.gameObject == (Object)null); NativeArrow.AllInstances.RemoveAll((NativeArrow a) => a == null || (Object)(object)a.gameObject == (Object)null); NativePage.AllInstances.Clear(); NativeButton.AllInstances.Clear(); NativeLabel.AllInstances.Clear(); NativeSlider.AllInstances.Clear(); NativeOption.AllInstances.Clear(); NativeInput.AllInstances.Clear(); NativeArrow.AllInstances.Clear(); UIParent.ResetCache(); ModLog.Info("[UIManagerEx] 已重置 UI 生命周期状态"); } private static void CreateControl(UIControlConfig cfg, Transform parent) { RectTransform component = ((Component)parent).GetComponent<RectTransform>(); if ((Object)(object)component == (Object)null) { return; } switch (cfg.type) { case "Button": { NativeButton nativeButton = NativeButton.Create(component, (ButtonStyle)cfg.style); if (nativeButton != null) { ((Object)nativeButton.gameObject).name = cfg.name; ApplyButtonConfig(nativeButton, cfg); } break; } case "Label": { NativeLabel nativeLabel = NativeLabel.Create(component); if (nativeLabel != null) { ((Object)nativeLabel.gameObject).name = cfg.name; ApplyLabelConfig(nativeLabel, cfg); } break; } case "Slider": { NativeSlider nativeSlider = NativeSlider.Create(component); if (nativeSlider != null) { ((Object)nativeSlider.gameObject).name = cfg.name; ApplySliderConfig(nativeSlider, cfg); } break; } case "Option": { NativeOption nativeOption = NativeOption.Create(component); if (nativeOption != null) { ((Object)nativeOption.gameObject).name = cfg.name; ApplyOptionConfig(nativeOption, cfg); } break; } case "Arrow": { NativeArrow nativeArrow = NativeArrow.Create(component, (NativeArrow.Direction)cfg.direction); if (nativeArrow != null) { ((Object)nativeArrow.gameObject).name = cfg.name; ApplyArrowConfig(nativeArrow, cfg); } break; } case "Input": { NativeInput nativeInput = NativeInput.Create(component); if (nativeInput != null) { ((Object)nativeInput.gameObject).name = cfg.name; ApplyInputConfig(nativeInput, cfg); } break; } } } private static void ApplyButtonConfig(NativeButton btn, UIControlConfig cfg) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) btn.SetPosition(cfg.position); btn.SetSize(cfg.size.x, cfg.size.y); if (!string.IsNullOrEmpty(cfg.title)) { btn.SetTitle(cfg.title.Trim()); } if (!string.IsNullOrEmpty(cfg.description)) { btn.SetDescription(cfg.description.Trim()); } btn.SetDraggable(cfg.draggable); btn.SetIconOffset(cfg.iconOffset); btn.SetTitleOffset(cfg.titleOffset); btn.SetDescOffset(cfg.descOffset); if (cfg.fontSize > 0) { btn.SetFontSize(cfg.fontSize); } if (cfg.toggleTexts != null && cfg.toggleTexts.Length != 0) { btn.SetToggleTexts(cfg.toggleTexts); if (cfg.toggleIndex >= 0 && cfg.toggleIndex < cfg.toggleTexts.Length) { btn.SetToggleIndex(cfg.toggleIndex); } } } private static void ApplyLabelConfig(NativeLabel lbl, UIControlConfig cfg) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) lbl.SetPosition(cfg.position); lbl.SetSize(cfg.size.x, cfg.size.y); if (!string.IsNullOrEmpty(cfg.labelText)) { lbl.SetText(cfg.labelText.Trim()); } if (cfg.fontSize > 0) { lbl.SetFontSize(cfg.fontSize); } lbl.SetColor(cfg.color); lbl.SetDraggable(cfg.draggable); } private static void ApplySliderConfig(NativeSlider sld, UIControlConfig cfg) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) sld.SetPosition(cfg.position); sld.SetSize(cfg.size.x, cfg.size.y); if (!string.IsNullOrEmpty(cfg.labelText)) { sld.SetLabel(cfg.labelText.Trim()); } if (cfg.fontSize > 0) { sld.SetFontSize(cfg.fontSize); } sld.SetMinMax(cfg.minValue, cfg.maxValue, cfg.wholeNumbers); sld.SetValueWithoutNotify(cfg.value); sld.SetDraggable(cfg.draggable); sld.SetSliderXOffset(cfg.sliderXOffset); sld.SetSliderWidth(cfg.sliderWidth); if (cfg.sliderGap > 0f) { sld.SetBarGap(cfg.sliderGap); } sld.SetLabelXOffset(cfg.labelXOffset); sld.SetValueXOffset(cfg.valueXOffset); } private static void ApplyOptionConfig(NativeOption opt, UIControlConfig cfg) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) opt.SetPosition(cfg.position); opt.SetSize(cfg.size.x, cfg.size.y); if (!string.IsNullOrEmpty(cfg.labelText)) { opt.SetLabel(cfg.labelText.Trim()); } if (!string.IsNullOrEmpty(cfg.description)) { opt.SetDescription(cfg.description.Trim()); } if (cfg.fontSize > 0) { opt.SetFontSize(cfg.fontSize); } if (cfg.options != null && cfg.options.Length != 0) { opt.SetOptions(cfg.options, cfg.optionIndex); } opt.SetDraggable(cfg.draggable); } private static void ApplyArrowConfig(NativeArrow arr, UIControlConfig cfg) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown arr.SetPosition(cfg.position); arr.SetSize(cfg.size.x, cfg.size.y); bool clickable = cfg.clickable; object obj = <>c.<>9__20_0; if (obj == null) { UnityAction val = delegate { ModLog.Info("箭头被点击"); }; <>c.<>9__20_0 = val; obj = (object)val; } arr.SetClickable(clickable, (UnityAction)obj); arr.SetDraggable(cfg.draggable); } private static void ApplyInputConfig(NativeInput inp, UIControlConfig cfg) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) inp.SetPosition(cfg.position); inp.SetSize(cfg.size.x, cfg.size.y); inp.SetTextSilent(cfg.inputText); if (cfg.fontSize > 0) { inp.SetFontSize(cfg.fontSize); } Graphic placeholder = inp.inputField.placeholder; Text val = (Text)(object)((placeholder is Text) ? placeholder : null); if ((Object)(object)val != (Object)null) { val.text = cfg.placeholderText; } } } public static class UIParent { private class CoroutineRunner : MonoBehaviour { public void Run(IEnumerator routine) { ((MonoBehaviour)this).StartCoroutine(routine); } } private static RectTransform _defaultParent; private static bool _isSearching; public static RectTransform GetDefaultParent() { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown if ((Object)(object)_defaultParent != (Object)null && (Object)(object)((Component)_defaultParent).gameObject != (Object)null) { return _defaultParent; } RectTransform val = TryGetDefaultParent(); if ((Object)(object)val != (Object)null) { _defaultParent = val; return val; } if (!_isSearching) { _isSearching = true; if ((Object)(object)NativeUIMakerMod.Instance != (Object)null) { ((MonoBehaviour)NativeUIMakerMod.Instance).StartCoroutine(DelayedSearch()); } else { GameObject val2 = new GameObject("UIParentTemp"); Object.DontDestroyOnLoad((Object)(object)val2); val2.AddComponent<CoroutineRunner>().Run(DelayedSearch(val2)); } } Canvas val3 = Object.FindObjectOfType<Canvas>(); if ((Object)(object)val3 != (Object)null) { Transform transform = ((Component)val3).transform; return (RectTransform)(object)((transform is RectTransform) ? transform : null); } ModLog.Error("[UIParent] 无法获取有效的 UI 父物体,控件将不可见!"); return null; } private static RectTransform TryGetDefaultParent() { if ((Object)(object)UIManager.instance != (Object)null && (Object)(object)UIManager.instance.UICanvas != (Object)null) { Transform transform = ((Component)UIManager.instance.UICanvas).transform; return (RectTransform)(object)((transform is RectTransform) ? transform : null); } Canvas val = Object.FindObjectOfType<Canvas>(); if ((Object)(object)val != (Object)null) { Transform transform2 = ((Component)val).transform; return (RectTransform)(object)((transform2 is RectTransform) ? transform2 : null); } return null; } private static IEnumerator DelayedSearch(GameObject tempGo = null) { for (float timeout = 3f; timeout > 0f; timeout -= Time.deltaTime) { yield return null; RectTransform val = TryGetDefaultParent(); if ((Object)(object)val != (Object)null) { _defaultParent = val; break; } } _isSearching = false; if ((Object)(object)tempGo != (Object)null) { Object.Destroy((Object)(object)tempGo); } } public static void ResetCache() { _defaultParent = null; _isSearching = false; } public static void EnsureVisible(RectTransform rt, Vector2? anchoredPosition = null, Vector2? sizeDelta = null) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)rt == (Object)null)) { rt.anchorMin = new Vector2(0.5f, 0.5f); rt.anchorMax = new Vector2(0.5f, 0.5f); rt.pivot = new Vector2(0.5f, 0.5f); rt.anchoredPosition = (Vector2)(((??)anchoredPosition) ?? Vector2.zero); rt.sizeDelta = (Vector2)(((??)sizeDelta) ?? new Vector2(600f, 80f)); } } public static void AttachAndEnsureVisible(GameObject obj, Vector2? position = null, Vector2? size = null) { if ((Object)(object)obj == (Object)null) { return; } RectTransform component = obj.GetComponent<RectTransform>(); if (!((Object)(object)component == (Object)null)) { RectTransform defaultParent = GetDefaultParent(); if ((Object)(object)defaultParent != (Object)null) { ((Transform)component).SetParent((Transform)(object)defaultParent, false); } EnsureVisible(component, position, size); } } } public class UIScanner { private List<GameObject> _targets; private int _currentIndex; private bool _initialized; private Transform _customRoot; private static readonly BindingFlags _allFlags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; public event Action<GameObject, string> OnScanCompleted; public UIScanner() { _targets = new List<GameObject>(); } public void SetCustomRoot(Transform root) { _customRoot = root; _initialized = false; _targets.Clear(); _currentIndex = 0; } private void EnsureTargets() { if (_initialized) { return; } _initialized = true; if ((Object)(object)_customRoot != (Object)null) { CollectAllGameObjects(_customRoot, _targets); ModLog.Info($"[UIScanner] 共收集到 {_targets.Count} 个 UI 元素(自定义根: {((Object)_customRoot).name})"); return; } Canvas val = UIManager.instance?.UICanvas; if ((Object)(object)val == (Object)null) { ModLog.Error("[UIScanner] 无法获取 UICanvas"); return; } CollectAllGameObjects(((Component)val).transform, _targets); ModLog.Info($"[UIScanner] 共收集到 {_targets.Count} 个 UI 元素"); } private void CollectAllGameObjects(Transform parent, List<GameObject> list) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown list.Add(((Component)parent).gameObject); foreach (Transform item in parent) { Transform parent2 = item; CollectAllGameObjects(parent2, list); } } public bool ScanNext() { EnsureTargets(); if (_currentIndex >= _targets.Count) { return false; } GameObject val = _targets[_currentIndex]; string arg = ScanGameObjectDeep(val); this.OnScanCompleted?.Invoke(val, arg); _currentIndex++; return true; } private string ScanGameObjectDeep(GameObject go) { //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Expected O, but got Unknown StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"\n========== [{_currentIndex + 1}/{_targets.Count}] {GetFullPath(go.transform)} =========="); stringBuilder.AppendLine($"Active: {go.activeSelf} | Layer: {go.layer} | Tag: {go.tag}"); Component[] components = go.GetComponents<Component>(); stringBuilder.AppendLine($"Components ({components.Length}):"); Component[] array = components; foreach (Component val in array) { if ((Object)(object)val == (Object)null) { stringBuilder.AppendLine(" - (null component)"); continue; } stringBuilder.AppendLine(" - " + ((object)val).GetType().FullName); DumpAllFields(val, stringBuilder, " "); DumpSpecialComponents(val, stringBuilder); } if (go.transform.childCount > 0) { stringBuilder.AppendLine($"Direct children ({go.transform.childCount}):"); foreach (Transform item in go.transform) { Transform val2 = item; stringBuilder.AppendLine(" - " + ((Object)val2).name + " (Path: " + GetFullPath(val2) + ")"); } } stringBuilder.AppendLine(); return stringBuilder.ToString(); } private void DumpAllFields(Component comp, StringBuilder sb, string indent) { FieldInfo[] fields = ((object)comp).GetType().GetFields(_allFlags); if (fields.Length == 0) { sb.AppendLine(indent + "(No fields accessible)"); return; } FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { if (!fieldInfo.IsStatic || !fieldInfo.IsLiteral) { try { object value = fieldInfo.GetValue(comp); string text = FormatFieldValue(value); sb.AppendLine(indent + fieldInfo.Name + " = " + text); } catch (Exception ex) { sb.AppendLine(indent + fieldInfo.Name + " = <error: " + ex.Message + ">"); } } } } private string FormatFieldValue(object value) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Expected O, but got Unknown //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Expected O, but got Unknown //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Expected O, but got Unknown if (value == null) { return "null"; } Type type = value.GetType(); if (type == typeof(Vector2)) { Vector2 val = (Vector2)value; return $"({val.x:F2}, {val.y:F2})"; } if (type == typeof(Vector3)) { Vector3 val2 = (Vector3)value; return $"({val2.x:F2}, {val2.y:F2}, {val2.z:F2})"; } if (type == typeof(Color)) { Color val3 = (Color)value; return $"RGBA({val3.r:F2}, {val3.g:F2}, {val3.b:F2}, {val3.a:F2})"; } if (type == typeof(Rect)) { Rect val4 = (Rect)value; return $"x:{((Rect)(ref val4)).x:F1} y:{((Rect)(ref val4)).y:F1} w:{((Rect)(ref val4)).width:F1} h:{((Rect)(ref val4)).height:F1}"; } if (type == typeof(Sprite)) { Sprite val5 = (Sprite)value; if (!((Object)(object)val5 != (Object)null)) { return "null"; } string name = ((Object)val5).name; Texture2D texture = val5.texture; return name + " (Texture: " + ((texture != null) ? ((Object)texture).name : null) + ")"; } if (type == typeof(Font)) { Font val6 = (Font)value; return (((int)val6 != 0) ? ((Object)val6).name : null) ?? "null"; } if (type == typeof(Transform)) { Transform val7 = (Transform)value; if (!((Object)(object)val7 != (Object)null)) { return "null"; } return GetFullPath(val7); } if (type == typeof(GameObject)) { GameObject val8 = (GameObject)value; if (!((Object)(object)val8 != (Object)null)) { return "null"; } return GetFullPath(val8.transform); } if (value is Delegate obj) { return "Delegate: " + obj.Method?.DeclaringType?.Name + "." + obj.Method?.Name; } if (type.IsArray) { Array array = (Array)value; return $"[{array.Length}] items"; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { return $"List (Count: {(object?)((dynamic)value).Count})"; } string text = value.ToString(); if (text.Length > 200) { text = text.Substring(0, 200) + "..."; } return text; } private void DumpSpecialComponents(Component comp, StringBuilder sb) { //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_0427: Unknown result type (might be due to invalid IL or missing references) //IL_035d: Unknown result type (might be due to invalid IL or missing references) //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_04a0: Unknown result type (might be due to invalid IL or missing references) ((object)comp).GetType(); Text val = (Text)(object)((comp is Text) ? comp : null); if (val != null) { sb.AppendLine(" >>> Text Content: \"" + val.text + "\""); Font font = val.font; sb.AppendLine($" >>> Font: {((font != null) ? ((Object)font).name : null)}, FontSize: {val.fontSize}, Style: {val.fontStyle}"); sb.AppendLine($" >>> Color: {((Graphic)val).color}"); sb.AppendLine($" >>> Alignment: {val.alignment}, LineSpacing: {val.lineSpacing}"); sb.AppendLine($" >>> BestFit: {val.resizeTextForBestFit}, Min/Max: {val.resizeTextMinSize}/{val.resizeTextMaxSize}"); } Image val2 = (Image)(object)((comp is Image) ? comp : null); if (val2 != null) { sb.AppendLine(" >>> Sprite: " + (((Object)(object)val2.sprite != (Object)null) ? ((Object)val2.sprite).name : "null")); sb.AppendLine($" >>> Image Type: {val2.type}, Fill Method: {val2.fillMethod}"); sb.AppendLine($" >>> Color: {((Graphic)val2).color}"); sb.AppendLine($" >>> Raycast Target: {((Graphic)val2).raycastTarget}"); } RectTransform val3 = (RectTransform)(object)((comp is RectTransform) ? comp : null); if (val3 != null) { sb.AppendLine($" >>> anchoredPosition: {val3.anchoredPosition}"); sb.AppendLine($" >>> sizeDelta: {val3.sizeDelta}"); sb.AppendLine($" >>> anchorMin: {val3.anchorMin}, anchorMax: {val3.anchorMax}"); sb.AppendLine($" >>> pivot: {val3.pivot}"); sb.AppendLine($" >>> localScale: {((Transform)val3).localScale}"); } MenuSelectable val4 = (MenuSelectable)(object)((comp is MenuSelectable) ? comp : null); if (val4 != null) { sb.AppendLine($" >>> CancelAction: {val4.cancelAction}"); sb.AppendLine($" >>> Interactable: {((Selectable)val4).interactable}"); if ((Object)(object)val4.selectHighlight != (Object)null) { sb.AppendLine(" >>> Highlight Animator: " + ((Object)val4.selectHighlight).name); } } MenuButton val5 = (MenuButton)(object)((comp is MenuButton) ? comp : null); if (val5 != null) { sb.AppendLine($" >>> ButtonType: {val5.buttonType}"); sb.AppendLine(" >>> FlashEffect: " + (((Object)(object)val5.flashEffect != (Object)null) ? ((Object)val5.flashEffect).name : "null")); if (val5.OnSubmitPressed != null && ((UnityEventBase)val5.OnSubmitPressed).GetPersistentEventCount() > 0) { sb.AppendLine($" >>> OnSubmitPressed listeners: {((UnityEventBase)val5.OnSubmitPressed).GetPersistentEventCount()}"); } } Animator val6 = (Animator)(object)((comp is Animator) ? comp : null); if (val6 != null) { RuntimeAnimatorController runtimeAnimatorController = val6.runtimeAnimatorController; sb.AppendLine(" >>> Runtime Animator Controller: " + ((runtimeAnimatorController != null) ? ((Object)runtimeAnimatorController).name : null)); AnimatorStateInfo currentAnimatorStateInfo = val6.GetCurrentAnimatorStateInfo(0); sb.AppendLine($" >>> Current state: {((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash}"); } Slider val7 = (Slider)(object)((comp is Slider) ? comp : null); if (val7 != null) { sb.AppendLine($" >>> Value: {val7.value}, Min: {val7.minValue}, Max: {val7.maxValue}"); sb.AppendLine($" >>> Whole Numbers: {val7.wholeNumbers}"); sb.AppendLine($" >>> Direction: {val7.direction}"); } Toggle val8 = (Toggle)(object)((comp is Toggle) ? comp : null); if (val8 != null) { sb.AppendLine($" >>> IsOn: {val8.isOn}"); sb.AppendLine($" >>> Toggle Transition: {val8.toggleTransition}"); } InputField val9 = (InputField)(object)((comp is InputField) ? comp : null); if (val9 != null) { sb.AppendLine(" >>> Text: \"" + val9.text + "\""); sb.AppendLine(" >>> Placeholder: " + (((Object)(object)val9.placeholder != (Object)null) ? ((object)val9.placeholder).ToString() : "null")); sb.AppendLine($" >>> ContentType: {val9.contentType}, CharacterLimit: {val9.characterLimit}"); } } private string GetFullPath(Transform t) { if ((Object)(object)t == (Object)null) { return ""; } List<string> list = new List<string>(); while ((Object)(object)t != (Object)null) { list.Insert(0, ((Object)t).name); t = t.parent; } return string.Join("/", list); } } [Serializable] public class UIControlConfig { public string name; public string type; public string page; public Vector2 position; public Vector2 size; public string title; public string description; public string[] toggleTexts; public int toggleIndex; public string labelText; public int fontSize; public Color color; public float minValue; public float maxValue; public float value; public bool wholeNumbers; public int optionIndex; public string[] options; public int direction; public bool playAnim; public bool clickable; public bool draggable; public string inputText; public string placeholderText; public int style; public Vector2 iconOffset; public Vector2 titleOffset; public Vector2 descOffset; public float sliderXOffset; public float sliderWidth; public float labelXOffset; public float valueXOffset; public float sliderGap; } [Serializable] public class ConfigData { public List<UIControlConfig> controls = new List<UIControlConfig>(); } internal static class SlimJson { internal static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { Formatting = (Formatting)1, NullValueHandling = (NullValueHandling)1, DefaultValueHandling = (DefaultValueHandling)1 }; } public class DebugWindow : MonoBehaviour { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Predicate<NativeButton> <>9__189_0; public static Predicate<NativeLabel> <>9__189_1; public static Predicate<NativeSlider> <>9__189_2; public static Predicate<NativeOption> <>9__189_3; public static Predicate<NativeArrow> <>9__189_4; public static Predicate<NativeInput> <>9__189_5; public static Func<NativePage, bool> <>9__208_0; public static Func<string, string> <>9__211_0; public static UnityAction <>9__211_1; public static UnityAction <>9__216_0; public static Func<string, string> <>9__234_0; public static Func<string, string> <>9__237_0; public static UnityAction <>9__248_0; public static Predicate<NativeButton> <>9__250_0; public static Predicate<NativeLabel> <>9__250_1; public static Predicate<NativeSlider> <>9__250_2; public static Predicate<NativeOption> <>9__250_3; public static Predicate<NativeArrow> <>9__250_4; public static Predicate<NativeInput> <>9__250_5; public static Predicate<NativeButton> <>9__253_0; public static UnityAction <>9__256_7; internal bool <CleanAllExternalLists>b__189_0(NativeButton b) { if (b != null) { return (Object)(object)b.gameObject == (Object)null; } return true; } internal bool <CleanAllExternalLists>b__189_1(NativeLabel l) { if (l != null) { return (Object)(object)l.gameObject == (Object)null; } return true; } internal bool <CleanAllExternalLists>b__189_2(NativeSlider s) { if (s != null) { return (Object)(object)s.gameObject == (Object)null; } return true; } internal bool <CleanAllExternalLists>b__189_3(NativeOption o) { if (o != null) { return (Object)(object)o.gameObject == (Object)null; } return true; } internal bool <CleanAllExternalLists>b__189_4(NativeArrow a) { if (a != null) { return (Object)(object)a.gameObject == (Object)null; } return true; } internal bool <CleanAllExternalLists>b__189_5(NativeInput i) { if (i != null) { return (Object)(object)i.gameObject == (Object)null; } return true; } internal bool <RefreshPageDropdownList>b__208_0(NativePage p) { return p != null; } internal string <DrawCreateButtonSection>b__211_0(string s) { return s.Trim(); } internal void <DrawCreateButtonSection>b__211_1() { ModLog.Info(UILocale.Get("按钮被点击")); } internal void <CreateArrow>b__216_0() { ModLog.Info(UILocale.Get("箭头被点击")); } internal string <DrawButtonEditor>b__234_0(string s) { return s.Trim(); } internal string <DrawOptionEditor>b__237_0(string s) { return s.Trim(); } internal void <ApplyConfigToControlInPage>b__248_0() { ModLog.Info(UILocale.Get("箭头被点击")); } internal bool <CleanInvalidControls>b__250_0(NativeButton b) { if (b != null) { return (Object)(object)b.gameObject == (Object)null; } return true; } internal bool <CleanInvalidControls>b__250_1(NativeLabel l) { if (l != null) { return (Object)(object)l.gameObject == (Object)null; } return true; } internal bool <CleanInvalidControls>b__250_2(NativeSlider s) { if (s != null) { return (Object)(object)s.gameObject == (Object)null; } return true; } internal bool <CleanInvalidControls>b__250_3(NativeOption o) { if (o != null) { return (Object)(object)o.gameObject == (Object)null; } return true; } internal bool <CleanInvalidControls>b__250_4(NativeArrow a) { if (a != null) { return (Object)(object)a.gameObject == (Object)null; } return true; } internal bool <CleanInvalidControls>b__250_5(NativeInput i) { if (i != null) { return (Object)(object)i.gameObject == (Object)null; } return true; } internal bool <SaveConfigToFile>b__253_0(NativeButton btn) { <>c__DisplayClass253_0 CS$<>8__locals1 = new <>c__DisplayClass253_0 { btn = btn }; return NativeArrow.AllInstances.Any((NativeArrow arr) => arr != null && (Object)(object)arr.gameObject == (Object)(object)CS$<>8__locals1.btn.gameObject); } internal void <LoadConfigFromFile>b__256_7() { ModLog.Info(UILocale.Get("箭头被点击")); } } [CompilerGenerated] private sealed class <>c__DisplayClass253_0 { public NativeButton btn; internal bool <SaveConfigToFile>b__1(NativeArrow arr) { if (arr != null) { return (Object)(object)arr.gameObject == (Object)(object)btn.gameObject; } return false; } } private static DebugWindow _instance; private Rect _windowRect = new Rect(50f, 50f, 800f, 1500f); private Vector2 _scrollPos; private bool _showWindow = true; private int _selectedTab; private HashSet<GameObject> _arrowGameObjectSet = new HashSet<GameObject>(); private HashSet<NativeButton> _localButtonSet = new HashSet<NativeButton>(); private HashSet<NativeLabel> _localLabelSet = new HashSet<NativeLabel>(); private HashSet<NativeSlider> _localSliderSet = new HashSet<NativeSlider>(); private HashSet<NativeOption> _localOptionSet = new HashSet<NativeOption>(); private HashSet<NativeArrow> _localArrowSet = new HashSet<NativeArrow>(); private HashSet<NativeInput> _localInputSet = new HashSet<NativeInput>(); private object _selectedControl; private string _editTitle = ""; private string _editDesc = ""; private Vector2 _editPos = Vector2.zero; private Vector2 _editSize = Vector2.zero; private string _editLabelText = ""; private int _editFontSize = 30; private Color _editColor = Color.white; private float _editSliderMin; private float _editSliderMax; private float _editSliderValue; private bool _editSliderWhole; private string _editSliderLabel = ""; private float _editSliderXOffset; private float _editSliderWidth; private float _editLabelXOffset; private float _editValueXOffset; private string _editOptionLabel = ""; private string _editOptionDesc = ""; private string[] _editOptionOptions; private int _editOptionIndex; private int _editArrowDirection; private bool _editArrowPlayAnim; private bool _editArrowClickable; private bool _editArrowDraggable; private string _editInputText = ""; private string _editInputPlaceholder = ""; private string _editToggleTextsInput = ""; private Vector2 _editIconOffset = Vector2.zero; private Vector2 _editTitleOffset = Vector2.zero; private Vector2 _editDescOffset = Vector2.zero; private string _strPosX = "0"; private string _strPosY = "0"; private string _strSizeW = "0"; private string _strSizeH = "0"; private string _strIconOffX = "0"; private string _strIconOffY = "0"; private string _strTitleOffX = "0"; private string _strTitleOffY = "0"; private string _strDescOffX = "0"; private string _strDescOffY = "0"; private string _strFontSize = "30"; private string _strColor = "1.00,1.00,1.00"; private string _lastParsedColor = ""; private string _strSliderMin = "0"; private string _strSliderMax = "100"; private string _strSliderValue = "0"; private string _strSliderXOff = "0"; private string _strSliderWidth = "0"; private string _strLabelXOff = "0"; private string _strValueXOff = "0"; private List<NativeButton> _allButtons = new List<NativeButton>(); private List<NativeLabel> _allLabels = new List<NativeLabel>(); private List<NativeSlider> _allSliders = new List<NativeSlider>(); private List<NativeOption> _allOptions = new List<NativeOption>(); private List<NativeArrow> _allArrows = new List<NativeArrow>(); private List<NativeInput> _allInputs = new List<NativeInput>(); private ButtonStyle _selectedCreateStyle; private string[] _styleNames = new string[3] { "图标按钮", "纯文字按钮", "小型按钮" }; private string _toggleTextsInput = "选项1,选项2,选项3"; private string _iconPathInput = ""; private NativePage _selectedCreateTargetPage; private string[] _pageNamesForDropdown = new string[0]; private int _selectedPageDropdownIndex; private int _pageDropdownVersion = -1; private List<NativeButton> _externalButtons = new List<NativeButton>(); private List<NativeLabel> _externalLabels = new List<NativeLabel>(); private List<NativeSlider> _externalSliders = new List<NativeSlider>(); private List<NativeOption> _externalOptions = new List<NativeOption>(); private List<NativeArrow> _externalArrows = new List<NativeArrow>(); private List<NativeInput> _externalInputs = new List<NativeInput>(); private bool _externalScanned; private NativePage _selectedPage; private List<UIControlConfig> _pageControlsCache = new List<UIControlConfig>(); private bool _cachedIsChinese; private bool _localeCacheValid; private string _locApplyChanges; private string _locDeleteControl; private string _locDestroyed; private string _locNoSelection; private string _locDraggable; private string _locHideWindow; private string _locLocal; private string _locExternal; private string _locPageMgmt; private string _locTitle; private string _locDesc; private string _locPosXY; private string _locSizeWH; private string _locApplyIcon; private string _locApplyTitle; private string _locApplyDesc; private string _locText; private string _locFontSize; private string _locColorRGB; private string _locLabel; private string _locSliderXOff; private string _locSliderWidth; private string _locLabelXOff; private string _locValueXOff; private string _locMin; private string _locMax; private string _locIntStep; private string _locOptions; private string _locSelected; private string _locPrev; private string _locNext; private string _locDir; private string _locLeft; private string _locRight; private string _locUp; private string _locDown; private string _locFlash; private string _locClickable; private string _locPlaceholder; private string _locEnter; private string _locScanExternal; private string _locSaveConfig; private string _locLoadConfig; private string _locClickScanHint; private string _locExtBtns; private string _locExtLabels; private string _locExtSliders; private string _locExtOptions; private string _locExtArrows; private string _locExtInputs; private string _locPages; private string _locSavePage; private string _locLoadPage; private string _locRefresh; private string _locPageControls; private string _locPos; private string _locTarget; private string _locGlobalCanvas; private string _locGlobal; private string _locCurr; private string _locCreateBtn; private string _locCreateLabel; private string _locCreateSlider; private string _locCreateOption; private string _locCreateArrow; private string _locCreateInput; private string _locStyle; private string _locIcon; private string _locTextBtn; private string _locSmall; private string _locIconPath; private string _locToggleTexts; private string _locSetToggleTexts; private string _locApplyToggle; private string _locNewBtn; private string _locNewLabel; private string _locNewSlider; private string _locNewOpt; private string _locDescText; private string _locDescTextLabel; private string _locArrowClicked; private string _locClicked; private string _locEditButton; private string _locEditLabel; private string _locEditSlider; private string _locEditOption; private string _locEditArrow; private string _locEditInput; private string _locIconOffset; private string _locTitleOffset; private string _locDescOffset; private string _locCurrentValue; private string _locTextContent; private string _locWindowTitle; private string _locAuto; private string _locPinToPage; private const int EXTERNAL_CLEAN_INTERVAL = 30; private int _externalCleanFrameCounter; private static bool _tempDragEnabled; private static GameObject _tempDragTarget; public static DebugWindow Instance => _instance; private string PluginDirectory => NativeUIMakerMod.PluginDirectory; public static GameObject CurrentlySelectedForDrag { get; private set; } public static bool TempDragEnabled => _tempDragEnabled; public static GameObject TempDragTarget => _tempDragTarget; private void RefreshLocaleCache() { _locApplyChanges = UILocale.Get("应用更改"); _locDeleteControl = UILocale.Get("删除此控件"); _locDestroyed = UILocale.Get("控件已被销毁"); _locNoSelection = UILocale.Get("未选中任何控件"); _locDraggable = UILocale.Get("允许拖拽 (按住鼠标左键拖动)"); _locHideWindow = UILocale.Get("隐藏窗口"); _locLocal = UILocale.Get("本地控件"); _locExternal = UILocale.Get("外部控件"); _locPageMgmt = UILocale.Get("页面管理"); _locTitle = UILocale.Get("标题:"); _locDesc = UILocale.Get("描述:"); _locPosXY = UILocale.Get("位置 (x, y):"); _locSizeWH = UILocale.Get("尺寸 (宽, 高):"); _locApplyIcon = UILocale.Get("应用图标偏移"); _locApplyTitle = UILocale.Get("应用标题偏移"); _locApplyDesc = UILocale.Get("应用描述偏移"); _locText = UILocale.Get("文本:"); _locFontSize = UILocale.Get("字体大小:"); _locColorRGB = UILocale.Get("颜色 (R,G,B):"); _locLabel = UILocale.Get("标签:"); _locSliderXOff = UILocale.Get("滑块 X 偏移:"); _locSliderWidth = UILocale.Get("滑块宽度 (0=原生):"); _locLabelXOff = UILocale.Get("标签 X 偏移:"); _locValueXOff = UILocale.Get("数值 X 偏移:"); _locMin = UILocale.Get("最小值: {0}"); _locMax = UILocale.Get("最大值: {0}"); _locIntStep = UILocale.Get("整数步进"); _locOptions = UILocale.Get("选项列表 (用逗号分隔):"); _locSelected = UILocale.Get("当前选中: {0} (索引 {1})"); _locPrev = UILocale.Get("上一个"); _locNext = UILocale.Get("下一个"); _locDir = UILocale.Get("方向:"); _locLeft = UILocale.Get("左"); _locRight = UILocale.Get("右"); _locUp = UILocale.Get("上"); _locDown = UILocale.Get("下"); _locFlash = UILocale.Get("播放动画 (闪烁)"); _locClickable = UILocale.Get("可点击 (添加按钮)"); _locPlaceholder = UILocale.Get("占位符:"); _locEnter = UILocale.Get("输入..."); _locScanExternal = UILocale.Get("扫描外部控件"); _locSaveConfig = UILocale.Get("保存配置"); _locLoadConfig = UILocale.Get("加载配置"); _locClickScanHint = UILocale.Get("点击“扫描外部控件”以发现其他模组创建的UI元素。"); _locExtBtns = UILocale.Get("外部按钮"); _locExtLabels = UILocale.Get("外部标签"); _locExtSliders = UILocale.Get("外部滑块"); _locExtOptions = UILocale.Get("外部选项行"); _locExtArrows = UILocale.Get("外部箭头"); _locExtInputs = UILocale.Get("外部输入框"); _locPages = UILocale.Get("可用页面:"); _locSavePage = UILocale.Get("保存页面配置"); _locLoadPage = UILocale.Get("加载页面配置"); _locRefresh = UILocale.Get("刷新"); _locPageControls = UILocale.Get("页面内控件列表:"); _locPos = UILocale.Get("位置"); _locTarget = UILocale.Get("创建目标:"); _locGlobalCanvas = UILocale.Get("全局画布 (独立于页面)"); _locGlobal = UILocale.Get("全局画布"); _locCurr = UILocale.Get("当前:"); _locCreateBtn = UILocale.Get("=== 创建新按钮 ==="); _locStyle = UILocale.Get("选择按钮样式:"); _locIcon = UILocale.Get("图标按钮"); _locTextBtn = UILocale.Get("纯文字按钮"); _locSmall = UILocale.Get("小型按钮"); _locIconPath = UILocale.Get("图标文件路径 (绝对或相对路径,留空则不设置):"); _locToggleTexts = UILocale.Get("切换文字序列(逗号分隔):"); _locSetToggleTexts = UILocale.Get("设置切换文字序列(逗号分隔):"); _locApplyToggle = UILocale.Get("应用切换序列"); _locNewBtn = UILocale.Get("新按钮"); _locNewLabel = UILocale.Get("新标签"); _locNewSlider = UILocale.Get("新滑块"); _locNewOpt = UILocale.Get("新选项"); _locDescText = UILocale.Get("这是描述文字"); _locDescTextLabel = UILocale.Get("可编辑描述"); _locArrowClicked = UILocale.Get("箭头被点击"); _locClicked = UILocale.Get("按钮被点击"); _locEditButton = UILocale.Get("编辑按钮: {0}"); _locEditLabel = UILocale.Get("编辑标签: {0}"); _locEditSlider = UILocale.Get("编辑滑块: {0}"); _locEditOption = UILocale.Get("编辑选项行: {0}"); _locEditArrow = UILocale.Get("编辑箭头: {0}"); _locEditInput = UILocale.Get("编辑输入框"); _locIconOffset = UILocale.Get("图标偏移 (x, y):"); _locTitleOffset = UILocale.Get("标题文字偏移 (x, y):"); _locDescOffset = UILocale.Get("描述文字偏移 (x, y):"); _locCurrentValue = UILocale.Get("当前值: {0}"); _locTextContent = UILocale.Get("文本内容:"); _locWindowTitle = UILocale.Get("NativeUIMaker 调试窗口"); _locAuto = UILocale.Get("Auto"); _locPinToPage = UILocale.Get("固定到当前页面"); _locCreateLabel = UILocale.Get("创建文本标签 (StandardLabel)"); _locCreateSlider = UILocale.Get("创建滑块 (NativeSlider)"); _locCreateOption = UILocale.Get("创建选项行 (NativeOption)"); _locCreateArrow = UILocale.Get("创建新箭头"); _locCreateInput = UILocale.Get("创建输入框"); _cachedIsChinese = UILocale.IsChinese; _locale
BepInEx/plugins/Newtonsoft.Json.dll
Decompiled a week 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.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETFramework,Version=v4.0", FrameworkDisplayName = ".NET Framework 4")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyFileVersion("13.0.4.30916")] [assembly: AssemblyInformationalVersion("13.0.4+4e13299d4b0ec96bd4df9954ef646bd2d1b5bf2a")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET .NET 4.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("13.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class FeatureGuardAttribute : Attribute { public Type FeatureType { get; } public FeatureGuardAttribute(Type featureType) { FeatureType = featureType; } } [AttributeUsage(AttributeTargets.Property, Inherited = false)] internal sealed class FeatureSwitchDefinitionAttribute : Attribute { public string SwitchName { get; } public FeatureSwitchDefinitionAttribute(string switchName) { SwitchName = switchName; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string? Scope { get; set; } public string? Target { get; set; } public string? MessageId { get; set; } public string? Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } } namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } public class DefaultJsonNameTable : JsonNameTable { private class Entry { internal readonly string Value; internal readonly int HashCode; internal Entry Next; internal Entry(string value, int hashCode, Entry next) { Value = value; HashCode = hashCode; Next = next; } } private static readonly int HashCodeRandomizer; private int _count; private Entry[] _entries; private int _mask = 31; static DefaultJsonNameTable() { HashCodeRandomizer = Environment.TickCount; } public DefaultJsonNameTable() { _entries = new Entry[_mask + 1]; } public override string? Get(char[] key, int start, int length) { if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; num += (num << 7) ^ key[start]; int num2 = start + length; for (int i = start + 1; i < num2; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; int num3 = Thread.VolatileRead(ref _mask); int num4 = num & num3; for (Entry entry = _entries[num4]; entry != null; entry = entry.Next) { if (entry.HashCode == num && TextEquals(entry.Value, key, start, length)) { return entry.Value; } } return null; } public string Add(string key) { if (key == null) { throw new ArgumentNullException("key"); } int length = key.Length; if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } } return AddEntry(key, num); } private string AddEntry(string str, int hashCode) { int num = hashCode & _mask; Entry entry = new Entry(str, hashCode, _entries[num]); _entries[num] = entry; if (_count++ == _mask) { Grow(); } return entry.Value; } private void Grow() { Entry[] entries = _entries; int num = _mask * 2 + 1; Entry[] array = new Entry[num + 1]; for (int i = 0; i < entries.Length; i++) { Entry entry = entries[i]; while (entry != null) { int num2 = entry.HashCode & num; Entry next = entry.Next; entry.Next = array[num2]; array[num2] = entry; entry = next; } } _entries = array; Thread.VolatileWrite(ref _mask, num); } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[]? array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type? _namingStrategyType; private object[]? _namingStrategyParameters; public string? Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[]? NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy? NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference == true; } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference == true; } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings>? DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } private static string ToStringInternal(BigInteger value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (StringUtils.IndexOf(text, '.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri? value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string? value) { return ToString(value, '"'); } public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object? value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter); } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } WriteJson(writer, (T)value, serializer); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get; set; } public object[]? NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference == true; } set { _isReference = value; } } public int Order { get { return _order.GetValueOrDefault(); } set { _order = value; } } public Required Required { get { return _required.GetValueOrDefault(); } set { _required = value; } } public string? PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference == true; } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string? _dateFormatString; private List<JsonPosition>? _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string? DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object? Value => _value; public virtual Type? ValueType => _value?.GetType(); public virtual int Depth { get { int num = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : ((JsonPosition?)null)); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; _maxDepth = 64; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth) { return; } _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is int) { return (int)value; } int num; if (value is BigInteger bigInteger) { num = (int)bigInteger; } else { try { num = Convert.ToInt32(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Integer, num, updateIndex: false); return num; } case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string? ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken)) { object value = Value; if (value != null) { string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture)); SetToken(JsonToken.String, text, updateIndex: false); return text; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[]? ReadAsBytes() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] array2 = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid guid) { byte[] array = guid.ToByteArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); do { if (!Read()) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(list)); byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is double) { return (double)value; } double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger)); SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L)); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is decimal) { return (decimal)value; } decimal num; if (value is BigInteger bigInteger) { num = (decimal)bigInteger; } else { try { num = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset dateTimeOffset) { SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: return ReadDateTimeString((string)Value); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime dateTime) { SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != JsonContainerType.None || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { _currentState = ((!SupportMultipleContent) ? State.Finished : State.Start); } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract? contract, bool hasConverter) { if (hasConverter) { return Read(); } switch (contract?.InternalReadType ?? ReadType.Read) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: { bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; } case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; default: throw new ArgumentOutOfRangeException(); } return TokenType != JsonToken.None; } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, path, lineNumber, linePosition, ex); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonSerializationException(message, path, lineNumber, linePosition, ex); } } [RequiresUnreferencedCode("Newtonsoft.Json relies on reflection over types that may be removed when trimming.")] [RequiresDynamicCode("Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation.")] public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; internal ITraceWriter? _traceWriter; internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string? _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver? ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder is SerializationBinder result) { return result; } if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value); } } public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = value; } } public virtual ITraceWriter? TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer? EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent == true; } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling.HasValue) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } [DebuggerStepThrough] public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } [DebuggerStepThrough] public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } [DebuggerStepThrough] public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } [DebuggerStepThrough] public T? Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader { PropertyNameTable: null } jsonTextReader && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable(); } } private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader { PropertyNameTable: not null } jsonTextReader && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable()) { jsonTextReader.PropertyNameTable = null; } } public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceJsonReader = new TraceJsonReader(reader); if (reader.TokenType != JsonToken.None) { traceJsonReader.WriteCurrentToken(); } return traceJsonReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _date
BepInEx/plugins/PharloomCore.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using System.Text; using Microsoft.CodeAnalysis; using PharloomCore.Data; using PharloomCore.Logic; using PharloomCore.Model; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("PharloomCore")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+c907a5441a34f4759975824f4eedc9f306ab5a89")] [assembly: AssemblyProduct("PharloomCore")] [assembly: AssemblyTitle("PharloomCore")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 PharloomCore { public class PharloomCore { private readonly string[] _nativeConnLines; private RoomGraph _roomGraphTemplate; private readonly Func<RoomGraph, bool, PlacementSimulator> _placementFactory; private RoomGraph _roomGraph; private DoorLogicGraph _doorGraph; private int _techniqueTier = 3; private int _difficulty; private bool _doorExemptComputed; private List<Item> _startingGrants; private string _gapStamp; private static readonly string[] EmptyLines = new string[0]; public Region[] Regions { get; } public PlacementSimulator Placement { get; private set; } public DeadSeedDetector Detector { get; private set; } public SceneGraphBuilder SceneGraph { get; } public PrefixResolver Resolver { get; } public RoomGraph RoomGraph => _roomGraph; public RoomGapSet RoomGaps { get; private set; } public bool RoomPrecision => _roomGraph != null; public bool StrictRoomGating { get; private set; } public IReadOnlyDictionary<string, string> PointScenes { get; } public DoorLogicGraph DoorGraph => _doorGraph; public string DoorGraphStatus { get; private set; } = "未加载"; public int Difficulty { get { return _difficulty; } set { int num = (_difficulty = ((value >= 0) ? ((value > 3) ? 3 : value) : 0)); if (Placement != null) { Placement.Difficulty = num; } TechniqueTier = Math.Min(1 + num, 3); } } public int TechniqueTier { get { return _techniqueTier; } set { if (value < 0) { value = 0; } if (value > 3) { value = 3; } _techniqueTier = value; if (Placement != null) { Placement.TechniqueTier = value; } if (Detector != null) { Detector.TechniqueTier = value; } } } public HashSet<string> DoorStructurallyUnreachable { get; private set; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public PharloomCore(string sceneConnectionPath, string checkpointsPath = null, string pointConditionsPath = null, bool roomPrecision = true) { PharloomCore pharloomCore = this; _nativeConnLines = File.ReadAllLines(sceneConnectionPath); Regions = RegionsData.All; SceneGraph = new SceneGraphBuilder(Regions); SceneGraph.Build(_nativeConnLines); Resolver = new PrefixResolver(Regions); _roomGraphTemplate = RoomGraphBuilder.Build(_nativeConnLines, Resolver, Regions); Dictionary<string, Gate> conditions = PointConditionLoader.LoadFile(pointConditionsPath); PointScenes = PointConditionLoader.LoadSceneMapFile(pointConditionsPath); string path = checkpointsPath; _placementFactory = (RoomGraph rg, bool strict) => new PlacementSimulator(pharloomCore.Regions, path, 0, conditions, rg, strict); _roomGraph = (roomPrecision ? _roomGraphTemplate : null); Attach(); } public PharloomCore(bool roomPrecision = true) { PharloomCore pharloomCore = this; _nativeConnLines = ReadEmbeddedLines("PharloomCore.Data.场景连接.txt").ToArray(); Regions = RegionsData.All; SceneGraph = new SceneGraphBuilder(Regions); SceneGraph.Build(_nativeConnLines); Resolver = new PrefixResolver(Regions); _roomGraphTemplate = RoomGraphBuilder.Build(_nativeConnLines, Resolver, Regions); Dictionary<string, Gate> conditions = PointConditionLoader.LoadLines(ReadEmbeddedLines("PharloomCore.Data.point_conditions.json")); PointScenes = PointConditionLoader.LoadSceneMapLines(ReadEmbeddedLines("PharloomCore.Data.point_conditions.json")); IEnumerable<string> lines = ReadEmbeddedLines("PharloomCore.Data.check_points.txt"); _placementFactory = (RoomGraph rg, bool strict) => new PlacementSimulator(pharloomCore.Regions, lines, 0, conditions, rg, strict); _roomGraph = (roomPrecision ? _roomGraphTemplate : null); try { List<string> list = ReadEmbeddedLines("PharloomCore.Data.door_logic.tsv").ToList(); list.AddRange(ReadEmbeddedLines("PharloomCore.Data.my_points_supplement.tsv")); List<string> policyLines = ReadEmbeddedLines("PharloomCore.Data.term_policy.tsv").ToList(); _doorGraph = DoorLogicGraph.LoadLines(list, null, policyLines); DoorGraphStatus = ((_doorGraph == null || _doorGraph.IsEmpty) ? "门级图加载为空" : $"门级图 {_doorGraph.Nodes.Count} 分区 / {_doorGraph.Doors.Count} 门 / {_doorGraph.Events.Count} 事件 / {_doorGraph.Checks.Count} 点位"); } catch (Exception ex) { _doorGraph = null; DoorGraphStatus = "门级图加载失败(退回房间闭包): " + ex.Message; } Attach(); } private void ComputeDoorExemptRooms() { if (_doorExemptComputed || _doorGraph == null || _doorGraph.IsEmpty) { return; } _doorExemptComputed = true; try { List<Item> list = new List<Item>(); foreach (AbilityId value in Enum.GetValues(typeof(AbilityId))) { list.Add(new Item { Kind = ItemKind.Ability, AbilityId = value }); } foreach (Permission value2 in PermissionsData.All.Values) { list.Add(new Item { Kind = ItemKind.Permission, PermissionId = value2.Id, AbilityId = value2.BoundAbility }); } string[] array = new string[5] { "SlabKeyA", "SlabKeyB", "SlabKeyC", "SimpleKey", "CrestSocketUnlocker" }; foreach (string itemName in array) { list.Add(new Item { Kind = ItemKind.NamedItem, ItemName = itemName }); } ReachabilityResult reachabilityResult = DoorReachability.Compute(null, null, _doorGraph, Regions, fullRandomMode: false, list); HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string key in _doorGraph.RoomNodes.Keys) { if (!reachabilityResult.State.ReachableRooms.Contains(key)) { hashSet.Add(key); } } DoorStructurallyUnreachable = hashSet; } catch { } } public void SetStartingGrants(IEnumerable<Item> grants) { _startingGrants = ((grants != null) ? new List<Item>(grants) : null); if (Placement != null) { Placement.StartingGrants.Clear(); if (_startingGrants != null) { Placement.StartingGrants.AddRange(_startingGrants); } } Detector?.SetStartingGrants(_startingGrants); } private void Attach() { ComputeDoorExemptRooms(); Placement = _placementFactory(_roomGraph, StrictRoomGating); if (Placement != null) { Placement.DoorGraph = _doorGraph; Placement.Difficulty = _difficulty; Placement.TechniqueTier = _techniqueTier; if (_startingGrants != null) { Placement.StartingGrants.Clear(); Placement.StartingGrants.AddRange(_startingGrants); } } Detector = new DeadSeedDetector(Regions, _roomGraph, Placement.BuildAllSlots(), StrictRoomGating); if (Detector != null) { Detector.DoorGraph = _doorGraph; Detector.TechniqueTier = _techniqueTier; Detector.DoorExemptRooms = DoorStructurallyUnreachable; if (_startingGrants != null) { Detector.SetStartingGrants(_startingGrants); } } RoomGaps = ((_roomGraph != null) ? RoomGapSet.Compute(_roomGraph, Regions, Placement.BuildAllSlots()) : null); ReportGapsIfChanged(); } private void ReportGapsIfChanged() { RoomGapSet roomGaps = RoomGaps; string text = ((roomGaps == null) ? "none" : GapStamp(roomGaps)); if (!string.Equals(text, _gapStamp, StringComparison.Ordinal)) { _gapStamp = text; RoomGapReport.Reset(); RoomGapReport.WarnOnce(roomGaps); } } private static string GapStamp(RoomGapSet gaps) { ulong num = 14695981039346656037uL; foreach (string gapRoomId in gaps.GapRoomIds) { foreach (char c in gapRoomId) { num ^= c; num *= 1099511628211L; } num ^= 0xA; num *= 1099511628211L; } return gaps.ExemptRoomCount + ":" + gaps.ExemptSlotCount + ":" + num.ToString("x16"); } public void SetRoomPrecision(bool enabled) { RoomGraph roomGraph = (enabled ? _roomGraphTemplate : null); if (roomGraph != _roomGraph) { _roomGraph = roomGraph; Attach(); } } internal static IEnumerable<string> ReadEmbeddedLines(string resourceName) { using Stream stream = typeof(PharloomCore).Assembly.GetManifestResourceStream(resourceName); if (stream == null) { throw new InvalidOperationException("缺少嵌入资源: " + resourceName); } using StreamReader streamReader = new StreamReader(stream); return streamReader.ReadToEnd().Split(new string[2] { "\r\n", "\n" }, StringSplitOptions.None); } public Gate FindPointGate(string key) { return Placement.FindPointGate(key); } public Dictionary<string, List<string>> GetSceneExits() { return VanillaExitMap.GetAllSceneExits(); } public SeedVerdict TryGenerate(Random rng, int maxTries = 1000, bool fullRandomMode = false) { List<ItemSlot> slots = Placement.BuildAllSlots(); List<Item> pool = Placement.BuildItemPool(fullRandomMode); for (int i = 0; i < maxTries; i++) { if (Placement.TryPlaceActive(rng, slots, pool, out var assignment, fullRandomMode)) { SeedVerdict seedVerdict = Detector.Evaluate(assignment, fullRandomMode); if (!seedVerdict.IsDead) { return seedVerdict; } } } return new SeedVerdict { IsDead = true, Reason = "重试 " + maxTries + " 次仍未找到活种子" }; } public bool IsSeedLive(int seed, bool fullRandomMode = false) { List<ItemSlot> slots = Placement.BuildAllSlots(); List<Item> pool = Placement.BuildItemPool(fullRandomMode); if (!Placement.TryPlaceActive(new Random(seed), slots, pool, out var assignment, fullRandomMode)) { return false; } return !Detector.Evaluate(assignment, fullRandomMode).IsDead; } public int ScoreSeed(int seed, bool fullRandomMode = false) { List<ItemSlot> slots = Placement.BuildAllSlots(); List<Item> pool = Placement.BuildItemPool(fullRandomMode); Dictionary<ItemSlot, Item> assignment; bool flag = Placement.TryPlaceActive(new Random(seed), slots, pool, out assignment, fullRandomMode); SeedVerdict seedVerdict = Detector.Evaluate(assignment, fullRandomMode); if (!seedVerdict.IsDead && flag) { return 0; } int num = ((!flag) ? 1000000 : 0); if (seedVerdict.Reason != null && seedVerdict.Reason.StartsWith("固定点缺失")) { num += 1000000; } num += (seedVerdict.RoomMode ? seedVerdict.UnreachedRoomCount : seedVerdict.UnreachedRegions.Count) * 10000; return num + seedVerdict.BlockedSlotIds.Count * 100; } public int FindLiveSeed(Random rng, int maxTries = 1000, bool fullRandomMode = false) { for (int i = 0; i < maxTries; i++) { int num = rng.Next(1, int.MaxValue); if (IsSeedLive(num, fullRandomMode)) { return num; } } return -1; } public void ReplaceSceneConnections(IEnumerable<string> sceneConnectionLines) { StrictRoomGating = true; RebuildGraphs(sceneConnectionLines); } public void RestoreNativeSceneConnections() { StrictRoomGating = false; RebuildGraphs(_nativeConnLines); } public void MergeSceneConnections(IEnumerable<string> randomLines) { StrictRoomGating = true; RebuildGraphs(MergeConnectionLines(_nativeConnLines, randomLines)); } private void RebuildGraphs(IEnumerable<string> lines) { IList<string> lines2 = (lines as IList<string>) ?? new List<string>(lines ?? EmptyLines); SceneGraph.Build(lines2); _roomGraphTemplate = RoomGraphBuilder.Build(lines2, Resolver, Regions); if (RoomPrecision) { _roomGraph = _roomGraphTemplate; } Attach(); } private static IEnumerable<string> MergeConnectionLines(IEnumerable<string> nativeLines, IEnumerable<string> randomLines) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); AddLines(dictionary, nativeLines); AddSymmetricLines(dictionary, nativeLines); AddLines(dictionary, randomLines); return dictionary.Values; } private static void AddSymmetricLines(Dictionary<string, string> map, IEnumerable<string> lines) { foreach (string line in lines) { string text = line?.Trim(); if (string.IsNullOrEmpty(text) || text.StartsWith("#")) { continue; } string[] array = text.Split(new char[1] { '|' }); if (array.Length < 4) { continue; } string text2 = array[0].Trim(); string text3 = array[1].Trim(); string text4 = array[2].Trim(); string text5 = array[3].Trim(); if (text2.Length != 0 && text4.Length != 0 && text3.Length != 0 && text5.Length != 0 && !string.Equals(text2, text4, StringComparison.OrdinalIgnoreCase)) { string key = text4 + "|" + text5; if (!map.ContainsKey(key)) { map[key] = text4 + "|" + text5 + "|" + text2 + "|" + text3; } } } } private static void AddLines(Dictionary<string, string> map, IEnumerable<string> lines) { foreach (string line in lines) { string text = line.Trim(); if (text.Length != 0 && !text.StartsWith("#")) { string[] array = text.Split(new char[1] { '|' }); if (array.Length >= 4) { map[array[0].Trim() + "|" + array[1].Trim()] = text; } } } } } } namespace PharloomCore.Model { public enum AbilityCategory { Movement, Combat, Spell, Music } public enum AbilityId { NeedleThrow, Dash, DoubleJump, Brolly, SuperJump, Walljump, HarpoonDash, SilkCharge, ThreadSphere, SilkBomb, SilkBossNeedle, ChargeSlash, Parry, Needolin, EvaHeal, NeedolinMemory, Teleport, SilkDash, AttackUp, AttackLeft, AttackRight, Heal, Swim, ShamanCrest, ArchitectChargeSlash, MelodyConductor, MelodyLibrarian, MelodyArchitect, SilkHeart, Journal, LedgeGrab, CrestBeast, CrestWitch, CrestArchitect, CrestReaper, CrestWanderer, CrestHunter, ActThree } public class Ability { public AbilityId Id { get; set; } public string Key { get; set; } public string DisplayName { get; set; } public AbilityCategory Category { get; set; } public override string ToString() { return DisplayName ?? Key; } } public static class MusicAbilityIds { public static readonly HashSet<AbilityId> All = new HashSet<AbilityId> { AbilityId.Needolin, AbilityId.EvaHeal, AbilityId.NeedolinMemory, AbilityId.Teleport, AbilityId.MelodyConductor, AbilityId.MelodyLibrarian, AbilityId.MelodyArchitect }; } public enum GateKind { Ability, Permission, AnyAbilityExcept, And, Or, Vertical, Horizontal, Cold, Item, Never, Room, Node, Event, Technique } public class Gate { public GateKind Kind { get; set; } public AbilityId Ability { get; set; } public string PermissionId { get; set; } public PermissionSide PermissionSide { get; set; } public HashSet<AbilityId> ExcludedCategoriesOrIds { get; set; } public List<Gate> Children { get; set; } public int Level { get; set; } public string ItemName { get; set; } public string NodeId { get; set; } public int TechniqueLevel { get; set; } public static Gate TechniqueGate(int level) { return new Gate { Kind = GateKind.Technique, TechniqueLevel = level }; } public static Gate AbilityGate(AbilityId id) { return new Gate { Kind = GateKind.Ability, Ability = id }; } public static Gate RoomGate(string roomId) { return new Gate { Kind = GateKind.Room, NodeId = roomId }; } public static Gate NodeGate(string nodeId) { return new Gate { Kind = GateKind.Node, NodeId = nodeId }; } public static Gate EventGate(string nodeId) { return new Gate { Kind = GateKind.Event, NodeId = nodeId }; } public static Gate PermissionGate(string id, PermissionSide side) { return new Gate { Kind = GateKind.Permission, PermissionId = id + "_" + SideMapping.EngineSuffix(side) }; } public static Gate AnyAbilityExcept(params AbilityId[] excluded) { return new Gate { Kind = GateKind.AnyAbilityExcept, ExcludedCategoriesOrIds = new HashSet<AbilityId>(excluded) }; } public static Gate VerticalGate(int level) { return new Gate { Kind = GateKind.Vertical, Level = level }; } public static Gate HorizontalGate(int level, PermissionSide side) { return new Gate { Kind = GateKind.Horizontal, Level = level, PermissionSide = side }; } public static Gate ColdGate() { return new Gate { Kind = GateKind.Cold }; } public static Gate ItemGate(string itemName) { return new Gate { Kind = GateKind.Item, ItemName = itemName }; } public static Gate NeverGate() { return new Gate { Kind = GateKind.Never }; } public static Gate And(params Gate[] children) { return new Gate { Kind = GateKind.And, Children = new List<Gate>(children) }; } public static Gate Or(params Gate[] children) { return new Gate { Kind = GateKind.Or, Children = new List<Gate>(children) }; } } public enum PermissionSide { Left, Right } public static class SideMapping { public const bool InvertVisualToEngine = false; public static string EngineSuffix(PermissionSide visualSide) { if (visualSide != PermissionSide.Right) { return "L"; } return "R"; } public static PermissionSide FromEngineSuffix(string id) { if (!id.EndsWith("_R")) { return PermissionSide.Left; } return PermissionSide.Right; } } public class Permission { public string Id { get; set; } public AbilityId BoundAbility { get; set; } public PermissionSide Side { get; set; } public bool SidesSplit { get; set; } public override string ToString() { return Id; } } public static class PermissionIds { public const string Dash = "Dash"; public const string HarpoonDash = "HarpoonDash"; public const string Brolly = "Brolly"; public const string Walljump = "Walljump"; public const string SuperJump = "SuperJump"; } public class PlayerState { public HashSet<AbilityId> Abilities { get; } = new HashSet<AbilityId>(); public HashSet<string> Permissions { get; } = new HashSet<string>(); public HashSet<string> OwnedItems { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public HashSet<Region> ReachableRegions { get; } = new HashSet<Region>(); public HashSet<string> ReachedNodes { get; } = new HashSet<string>(StringComparer.Ordinal); public HashSet<string> ReachableRooms { get; set; } = new HashSet<string>(); public bool HasColdResistance { get; set; } public int AllowedTechniqueTier { get; set; } = 3; public bool HasAbility(AbilityId id) { return Abilities.Contains(id); } public bool HasPermission(string id) { return Permissions.Contains(id); } public bool OwnsItem(string name) { return OwnedItems.Contains(name); } public static PlayerState WithStartingAbilities(bool fullRandomMode) { PlayerState playerState = new PlayerState(); playerState.Abilities.Add(AbilityId.LedgeGrab); playerState.Abilities.Add(AbilityId.CrestHunter); if (fullRandomMode) { return playerState; } playerState.Abilities.Add(AbilityId.AttackUp); playerState.Abilities.Add(AbilityId.AttackLeft); playerState.Abilities.Add(AbilityId.AttackRight); playerState.Abilities.Add(AbilityId.Heal); return playerState; } } public class Region { public string Id { get; set; } public string DisplayName { get; set; } public List<string> ScenePrefixes { get; set; } public List<string> AdjacentRegionIds { get; set; } public Gate EntryGate { get; set; } public Dictionary<string, Gate> Exits { get; set; } public List<ItemSlot> Slots { get; set; } public bool IsStart { get; set; } public bool IsDream { get; set; } public Region() { ScenePrefixes = new List<string>(); AdjacentRegionIds = new List<string>(); Exits = new Dictionary<string, Gate>(); Slots = new List<ItemSlot>(); } public override string ToString() { return DisplayName ?? Id; } } public enum ItemKind { Ability, Permission, NamedItem, Cold, Virtual } public class ItemSlot { public string Id { get; set; } public string SourceKey { get; set; } public Region Region { get; set; } public string RoomId { get; set; } public int Depth { get; set; } = -1; public bool IsFixed { get; set; } public Gate AccessGate { get; set; } public override bool Equals(object obj) { if (obj is ItemSlot itemSlot) { return string.Equals(Id, itemSlot.Id); } return false; } public override int GetHashCode() { if (Id == null) { return 0; } return Id.GetHashCode(); } public override string ToString() { return Id; } } public class Item { public ItemKind Kind { get; set; } public AbilityId AbilityId { get; set; } public string PermissionId { get; set; } public string ItemName { get; set; } public int Priority { get; set; } = 4; public override string ToString() { return Kind switch { ItemKind.Ability => AbilityId.ToString(), ItemKind.Permission => PermissionId, ItemKind.NamedItem => "Item:" + ItemName, ItemKind.Cold => "ColdResistance", ItemKind.Virtual => "Virt:" + ItemName, _ => "?", }; } } public class RoomComponent { public List<string> Rooms { get; } = new List<string>(); public bool IsMain { get; internal set; } public bool IsDreamSeeded { get; internal set; } public bool IsValid { get { if (!IsMain) { return IsDreamSeeded; } return true; } } public int Count => Rooms.Count; public bool Contains(string roomId) { if (roomId != null) { return Rooms.Contains(roomId); } return false; } } public class RoomGraph { public const string DefaultStartRoomId = "Tut_01"; private readonly HashSet<string> _alwaysReachableRooms = new HashSet<string>(StringComparer.Ordinal); private List<RoomComponent> _components; private Dictionary<string, RoomComponent> _componentOfRoom; private RoomComponent _mainComponent; private List<string> _orphanRooms; private HashSet<string> _orphanRoomSet; private Dictionary<string, int> _depth; public string StartRoomId { get; set; } = "Tut_01"; public Dictionary<string, HashSet<string>> Adjacency { get; } = new Dictionary<string, HashSet<string>>(); public Dictionary<string, string> RoomToRegion { get; } = new Dictionary<string, string>(); public List<string> UnmappedScenes { get; } = new List<string>(); public int RoomCount => Adjacency.Count; public IReadOnlyList<RoomComponent> Components { get { EnsureComponents(); return _components; } } public RoomComponent MainComponent { get { EnsureComponents(); return _mainComponent; } } public IReadOnlyList<string> OrphanRoomIds { get { if (_orphanRooms == null) { BuildOrphans(); } return _orphanRooms; } } public IReadOnlyDictionary<string, int> RegionDepth { get { EnsureDepth(); Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal); if (_depth == null) { return dictionary; } foreach (KeyValuePair<string, int> item in _depth) { if (item.Value >= 0 && RoomToRegion.TryGetValue(item.Key, out var value) && !string.IsNullOrEmpty(value) && (!dictionary.TryGetValue(value, out var value2) || item.Value < value2)) { dictionary[value] = item.Value; } } return dictionary; } } public IEnumerable<string> Neighbors(string roomId) { if (roomId != null && Adjacency.TryGetValue(roomId, out var value)) { return value; } return Array.Empty<string>(); } public void DeclareAlwaysReachableRooms(IEnumerable<string> roomIds) { _alwaysReachableRooms.Clear(); if (roomIds != null) { foreach (string roomId in roomIds) { if (!string.IsNullOrEmpty(roomId)) { _alwaysReachableRooms.Add(roomId); } } } InvalidateQueries(); } public RoomComponent ComponentOf(string roomId) { EnsureComponents(); if (roomId == null) { return null; } if (!_componentOfRoom.TryGetValue(roomId, out var value)) { return null; } return value; } public bool IsOrphanRoom(string roomId) { if (_orphanRoomSet == null) { BuildOrphans(); } if (roomId != null) { return _orphanRoomSet.Contains(roomId); } return false; } public static HashSet<string> DreamRegionRooms(Region[] regions, RoomGraph graph) { HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); if (regions == null || graph == null) { return hashSet; } HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal); foreach (Region region in regions) { if (region != null && region.IsDream) { hashSet2.Add(region.Id); } } if (hashSet2.Count == 0) { return hashSet; } foreach (KeyValuePair<string, string> item in graph.RoomToRegion) { if (hashSet2.Contains(item.Value)) { hashSet.Add(item.Key); } } return hashSet; } private void InvalidateQueries() { _components = null; _componentOfRoom = null; _mainComponent = null; _orphanRooms = null; _orphanRoomSet = null; _depth = null; } public int DepthOf(string roomId) { if (string.IsNullOrEmpty(roomId)) { return int.MaxValue; } EnsureDepth(); if (_depth == null || !_depth.TryGetValue(roomId, out var value)) { return int.MaxValue; } return value; } private void EnsureDepth() { if (_depth != null) { return; } _depth = new Dictionary<string, int>(StringComparer.Ordinal); string text = StartRoomId; if (string.IsNullOrEmpty(text) || !Adjacency.ContainsKey(text)) { using HashSet<string>.Enumerator enumerator = _alwaysReachableRooms.GetEnumerator(); if (enumerator.MoveNext()) { text = enumerator.Current; } } if (string.IsNullOrEmpty(text) || !Adjacency.ContainsKey(text)) { return; } Queue<string> queue = new Queue<string>(); _depth[text] = 0; queue.Enqueue(text); foreach (string alwaysReachableRoom in _alwaysReachableRooms) { if (Adjacency.ContainsKey(alwaysReachableRoom) && !_depth.ContainsKey(alwaysReachableRoom)) { _depth[alwaysReachableRoom] = 0; queue.Enqueue(alwaysReachableRoom); } } while (queue.Count > 0) { string text2 = queue.Dequeue(); int num = _depth[text2]; foreach (string item in Neighbors(text2)) { if (!_depth.ContainsKey(item)) { _depth[item] = num + 1; queue.Enqueue(item); } } } } private void EnsureComponents() { if (_components != null) { return; } List<RoomComponent> list = new List<RoomComponent>(); Dictionary<string, RoomComponent> dictionary = new Dictionary<string, RoomComponent>(StringComparer.Ordinal); HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); List<string> list2 = new List<string>(Adjacency.Keys); list2.Sort(StringComparer.Ordinal); foreach (string item in list2) { if (hashSet.Contains(item)) { continue; } RoomComponent roomComponent = new RoomComponent(); Queue<string> queue = new Queue<string>(); queue.Enqueue(item); hashSet.Add(item); while (queue.Count > 0) { string text = queue.Dequeue(); roomComponent.Rooms.Add(text); if (!Adjacency.TryGetValue(text, out var value)) { continue; } foreach (string item2 in value) { if (item2 != null && Adjacency.ContainsKey(item2) && hashSet.Add(item2)) { queue.Enqueue(item2); } } } roomComponent.Rooms.Sort(StringComparer.Ordinal); list.Add(roomComponent); foreach (string room in roomComponent.Rooms) { dictionary[room] = roomComponent; } } list.Sort((RoomComponent a, RoomComponent b) => (a.Count == b.Count) ? string.CompareOrdinal(a.Rooms[0], b.Rooms[0]) : b.Count.CompareTo(a.Count)); if (!string.IsNullOrEmpty(StartRoomId) && dictionary.TryGetValue(StartRoomId, out var value2)) { _mainComponent = value2; } else { _mainComponent = ((list.Count > 0) ? list[0] : null); } if (_mainComponent != null) { _mainComponent.IsMain = true; } foreach (RoomComponent item3 in list) { if (item3.IsMain) { continue; } foreach (string room2 in item3.Rooms) { if (_alwaysReachableRooms.Contains(room2)) { item3.IsDreamSeeded = true; break; } } } _components = list; _componentOfRoom = dictionary; } private void BuildOrphans() { EnsureComponents(); List<string> list = new List<string>(); HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); foreach (RoomComponent component in _components) { if (component.IsValid) { continue; } foreach (string room in component.Rooms) { if (hashSet.Add(room)) { list.Add(room); } } } list.Sort(StringComparer.Ordinal); _orphanRooms = list; _orphanRoomSet = hashSet; } } } namespace PharloomCore.Logic { public class SeedVerdict { public bool IsDead { get; set; } public int ReachedCount { get; set; } public int TotalCount { get; set; } public List<string> UnreachedRegions { get; } = new List<string>(); public List<string> ReachedRegions { get; } = new List<string>(); public List<string> BlockedSlotIds { get; } = new List<string>(); public string Reason { get; set; } public List<string> UnreachedRooms { get; } = new List<string>(); public List<string> ReachedRooms { get; } = new List<string>(); public List<string> ExemptRooms { get; } = new List<string>(); public IReadOnlyList<string> GapRoomIds { get; set; } public bool HasGapExemption => ExemptRooms.Count > 0; public bool RoomMode { get; set; } public string ScopeLabel { get { if (!RoomMode) { return "区域"; } return "房间"; } } public int UnreachedRoomCount => UnreachedRooms.Count; private string ExemptNote { get { if (ExemptRooms.Count <= 0) { return string.Empty; } return "(另有 " + ExemptRooms.Count + " 个数据缺口房间豁免,不计死种)"; } } public override string ToString() { if (!IsDead) { return "活种子: 全部 " + ReachedCount + " " + ScopeLabel + "可达" + ExemptNote; } return "死种子: " + (string.IsNullOrEmpty(Reason) ? string.Join(", ", UnreachedRegions) : Reason); } } public class DeadSeedDetector { private readonly ReachabilityAnalyzer _analyzer; private readonly RoomGapSet _gaps; public DoorLogicGraph DoorGraph { get { return _analyzer.DoorGraph; } set { _analyzer.DoorGraph = value; } } public int TechniqueTier { get { return _analyzer.AllowedTechniqueTier; } set { _analyzer.AllowedTechniqueTier = value; } } public HashSet<string> DoorExemptRooms { get; set; } public bool RoomPrecision => _analyzer.RoomPrecision; public bool StrictRoomGating => _analyzer.StrictRoomGating; public RoomGateIndex RoomGates => _analyzer.RoomGates; public RoomGapSet Gaps => _gaps; public DeadSeedDetector(Region[] regions, RoomGraph roomGraph = null, IEnumerable<ItemSlot> allSlots = null, bool strictRoomGating = false, IEnumerable<Item> startingGrants = null) { _analyzer = new ReachabilityAnalyzer(regions, roomGraph, strictRoomGating); if (startingGrants != null) { _analyzer.StartingGrants.AddRange(startingGrants); } if (strictRoomGating && roomGraph != null && allSlots != null) { _analyzer.AllSlots = (allSlots as List<ItemSlot>) ?? new List<ItemSlot>(allSlots); _analyzer.RoomGates = RoomGateIndex.Build(roomGraph, _analyzer.AllSlots); } _gaps = RoomGapSet.Compute(roomGraph, regions, null); } public SeedVerdict Evaluate(IReadOnlyDictionary<ItemSlot, Item> assignment, bool fullRandomMode = false) { SeedVerdict seedVerdict = new SeedVerdict { RoomMode = _analyzer.RoomPrecision }; if (assignment == null) { seedVerdict.IsDead = true; seedVerdict.Reason = "分配为空(放置失败)"; return seedVerdict; } ReachabilityResult reachabilityResult = _analyzer.Compute(assignment, fullRandomMode); seedVerdict.ReachedCount = (RoomPrecision ? reachabilityResult.ReachedRoomIds.Count : reachabilityResult.ReachedRegionIds.Count); seedVerdict.TotalCount = ((!RoomPrecision) ? _analyzer.Regions.Length : ((_analyzer.RoomGraph != null) ? _analyzer.RoomGraph.RoomCount : 0)); seedVerdict.ReachedRegions.AddRange(reachabilityResult.ReachedRegionIds); seedVerdict.UnreachedRegions.AddRange(reachabilityResult.UnreachedRegionIds); seedVerdict.ReachedRooms.AddRange(reachabilityResult.ReachedRoomIds); if (DoorExemptRooms != null && DoorExemptRooms.Count > 0) { reachabilityResult.UnreachedRoomIds.RemoveAll((string r) => DoorExemptRooms.Contains(r)); } seedVerdict.BlockedSlotIds.AddRange(reachabilityResult.BlockedSlotIds); if (RoomPrecision) { seedVerdict.GapRoomIds = ((_gaps != null) ? _gaps.GapRoomIds : null); foreach (string unreachedRoomId in reachabilityResult.UnreachedRoomIds) { if (_gaps != null && _gaps.IsGapRoom(unreachedRoomId)) { seedVerdict.ExemptRooms.Add(unreachedRoomId); } else { seedVerdict.UnreachedRooms.Add(unreachedRoomId); } } } else { seedVerdict.UnreachedRooms.AddRange(reachabilityResult.UnreachedRoomIds); } string text = FindFixedViolation(assignment); if (text != null) { seedVerdict.IsDead = true; seedVerdict.Reason = "固定点缺失: " + text; return seedVerdict; } if (RoomPrecision ? (seedVerdict.UnreachedRooms.Count > 0) : (!reachabilityResult.AllReached)) { seedVerdict.IsDead = true; if (RoomPrecision) { seedVerdict.Reason = "房间不可达 (" + seedVerdict.UnreachedRooms.Count + "): " + string.Join(", ", seedVerdict.UnreachedRooms) + ExemptSuffix(seedVerdict); } else { seedVerdict.Reason = "区域不可达: " + string.Join(", ", reachabilityResult.UnreachedRegionIds); } return seedVerdict; } if (!reachabilityResult.AllPointsAccessible) { seedVerdict.IsDead = true; seedVerdict.Reason = "点位条件不可达 (" + reachabilityResult.BlockedSlotIds.Count + "): " + string.Join(", ", reachabilityResult.BlockedSlotIds); return seedVerdict; } seedVerdict.IsDead = false; return seedVerdict; } private static string ExemptSuffix(SeedVerdict verdict) { if (verdict.ExemptRooms.Count <= 0) { return string.Empty; } return ";另有 " + verdict.ExemptRooms.Count + " 个数据缺口房间豁免(不计死种): " + string.Join(", ", verdict.ExemptRooms); } private static string FindFixedViolation(IReadOnlyDictionary<ItemSlot, Item> assignment) { foreach (KeyValuePair<ItemSlot, Item> item in assignment) { if (item.Key.IsFixed && !MatchesFixed(item.Key, item.Value)) { return item.Key.Id + " 固定物品被篡改"; } } return null; } public void SetStartingGrants(IEnumerable<Item> grants) { _analyzer.StartingGrants.Clear(); if (grants != null) { _analyzer.StartingGrants.AddRange(grants); } } private static bool MatchesFixed(ItemSlot slot, Item item) { return true; } } public class CheckpointSource { private readonly PrefixResolver _resolver; private readonly IReadOnlyDictionary<string, Gate> _conditionsByKey; public CheckpointSource(Region[] regions, IReadOnlyDictionary<string, Gate> conditionsByKey = null) { _resolver = new PrefixResolver(regions); _conditionsByKey = conditionsByKey; } public List<ItemSlot> BuildSlots(string checkpointsPath, bool includeLore = true) { return BuildSlots(File.ReadAllLines(checkpointsPath), includeLore); } public List<ItemSlot> BuildSlots(IEnumerable<string> lines, bool includeLore = true) { List<ItemSlot> list = new List<ItemSlot>(); int num = 0; foreach (string line in lines) { string text = line.Trim(); if (text.Length == 0) { continue; } string[] array = text.Split(new char[1] { '|' }); string text2 = array[0]; if (array.Length < 2 || (text2 != "Pickup" && (!includeLore || !(text2 == "Lore")))) { continue; } string text3 = array[1].Trim(); Region region = _resolver.Resolve(text3); if (region != null) { string text4 = ((array.Length > 5) ? array[5].Trim() : null); if (text2 == "Pickup" && array.Length > 7 && float.TryParse(array[6], NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && float.TryParse(array[7], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { text4 = text3 + "_" + result.ToString("F2", CultureInfo.InvariantCulture) + "_" + result2.ToString("F2", CultureInfo.InvariantCulture) + "_0.00"; } Gate accessGate = null; if (text4 != null && _conditionsByKey != null && _conditionsByKey.TryGetValue(text4, out var value)) { accessGate = value; } list.Add(new ItemSlot { Id = text2 + "_" + num + "_" + text3, SourceKey = text4, Region = region, RoomId = text3, AccessGate = accessGate }); num++; } } return list; } } public class DoorLogicEntry { public string Key; public string From; public string ToRoom; public string ToPort; public string LogicText; public Gate Gate; public bool FromAnyPartition; } public class EventLogicEntry { public string Key; public string Node; public string Kind; public string LogicText; public Gate Gate; } public class CheckLogicEntry { public string Key; public string Node; public bool Randomized; public string LogicText; public Gate Gate; } public class DoorLogicGraph { private LogicTermResolver _resolver; public string StartRoom { get; set; } public List<string> StartNodes { get; } = new List<string>(); public Dictionary<string, Gate> Nodes { get; } = new Dictionary<string, Gate>(StringComparer.Ordinal); public Dictionary<string, string> NodeText { get; } = new Dictionary<string, string>(StringComparer.Ordinal); public Dictionary<string, DoorLogicEntry> Doors { get; } = new Dictionary<string, DoorLogicEntry>(StringComparer.Ordinal); public Dictionary<string, EventLogicEntry> Events { get; } = new Dictionary<string, EventLogicEntry>(StringComparer.Ordinal); public Dictionary<string, CheckLogicEntry> Checks { get; } = new Dictionary<string, CheckLogicEntry>(StringComparer.Ordinal); public Dictionary<string, string> NodeRoom { get; } = new Dictionary<string, string>(StringComparer.Ordinal); public Dictionary<string, List<string>> RoomNodes { get; } = new Dictionary<string, List<string>>(StringComparer.Ordinal); public Dictionary<string, List<DoorLogicEntry>> RoomDoors { get; } = new Dictionary<string, List<DoorLogicEntry>>(StringComparer.Ordinal); public int ParseFailures { get; private set; } public IReadOnlyCollection<string> UnknownTerms { get { if (_resolver == null) { return null; } return _resolver.UnknownTerms; } } public LogicTermResolver Resolver => _resolver; public bool IsEmpty { get { if (Nodes.Count == 0) { return Doors.Count == 0; } return false; } } public static DoorLogicGraph LoadLines(IEnumerable<string> lines) { return LoadLines(lines, null); } public static DoorLogicGraph LoadLines(IEnumerable<string> lines, string policyPath) { return LoadLines(lines, policyPath, null); } public static DoorLogicGraph LoadLines(IEnumerable<string> lines, string policyPath, IEnumerable<string> policyLines) { if (lines == null) { return null; } DoorLogicGraph doorLogicGraph = new DoorLogicGraph(); List<string[]> list = new List<string[]>(); HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); HashSet<string> hashSet2 = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string line in lines) { if (string.IsNullOrWhiteSpace(line) || line[0] == '#') { continue; } string[] array = line.Split(new char[1] { '\t' }); if (array.Length < 2) { continue; } switch (array[0]) { case "S": if (array.Length >= 3 && array[1] == "startRoom") { doorLogicGraph.StartRoom = array[2]; } else if (array.Length >= 3 && array[1] == "startNode") { doorLogicGraph.StartNodes.Add(array[2]); } break; case "N": case "D": case "E": case "C": list.Add(array); if (array.Length >= 2) { string text = RoomOfNode(array[1]); if (text != null) { hashSet.Add(text); } if (array[0] == "E") { hashSet2.Add(array[1]); } } break; } } if (!string.IsNullOrEmpty(doorLogicGraph.StartRoom)) { hashSet.Add(doorLogicGraph.StartRoom); } foreach (string startNode in doorLogicGraph.StartNodes) { string text2 = RoomOfNode(startNode); if (text2 != null) { hashSet.Add(text2); } } doorLogicGraph._resolver = new LogicTermResolver(hashSet); doorLogicGraph._resolver.SetKnownEvents(hashSet2); if (!string.IsNullOrEmpty(policyPath)) { doorLogicGraph._resolver.LoadPolicy(policyPath); } else if (policyLines != null) { doorLogicGraph._resolver.LoadPolicyLines(policyLines); } TravelUnlocks.Apply(list); foreach (string[] item in list) { switch (item[0]) { case "N": if (item.Length >= 3) { doorLogicGraph.AddNode(item[1], item[2]); } break; case "D": if (item.Length >= 6) { doorLogicGraph.AddDoor(new DoorLogicEntry { Key = item[1], From = item[2], ToRoom = item[3], ToPort = item[4], LogicText = item[5], Gate = doorLogicGraph.ParseGate(item[5]) }); } break; case "E": if (item.Length >= 5) { doorLogicGraph.Events[item[1]] = new EventLogicEntry { Key = item[1], Node = item[2], Kind = item[3], LogicText = item[4], Gate = doorLogicGraph.ParseGate(item[4]) }; } break; case "C": if (item.Length >= 5) { doorLogicGraph.Checks[item[1]] = new CheckLogicEntry { Key = item[1], Node = item[2], Randomized = (item[3] == "1"), LogicText = item[4], Gate = doorLogicGraph.ParseGate(item[4]) }; } break; } } StartExitOverrides.Apply(doorLogicGraph); return doorLogicGraph; } public static DoorLogicGraph LoadFiles(params string[] paths) { if (paths == null || paths.Length == 0) { return null; } List<string> list = new List<string>(); foreach (string text in paths) { if (!string.IsNullOrEmpty(text) && File.Exists(text)) { list.AddRange(File.ReadAllLines(text)); } } string directoryName = Path.GetDirectoryName(Path.GetFullPath(paths[0])); string policyPath = (string.IsNullOrEmpty(directoryName) ? null : Path.Combine(directoryName, "term_policy.tsv")); return LoadLines(list, policyPath); } private void AddNode(string node, string logic) { Gate value = ParseGate(logic); Nodes[node] = value; NodeText[node] = logic; string text = RoomOfNode(node); if (text != null) { NodeRoom[node] = text; if (!RoomNodes.TryGetValue(text, out var value2)) { value2 = new List<string>(); RoomNodes[text] = value2; } value2.Add(node); } } private void AddDoor(DoorLogicEntry door) { Doors[door.Key] = door; string text = RoomOfNode(door.From); if (text != null) { if (!RoomDoors.TryGetValue(text, out var value)) { value = new List<DoorLogicEntry>(); RoomDoors[text] = value; } value.Add(door); } } private Gate ParseGate(string logic) { if (string.IsNullOrWhiteSpace(logic) || logic == "TRUE") { return Gate.And(); } if (logic == "NEVER") { return Gate.NeverGate(); } string error; Gate gate = DnfExpression.TryParse(logic, _resolver.Resolve, out error); if (gate == null) { ParseFailures++; return Gate.NeverGate(); } return gate; } internal static string RoomOfNode(string node) { if (string.IsNullOrEmpty(node)) { return null; } int num = node.IndexOf('#'); if (num < 0) { num = node.IndexOf('@'); } if (num <= 0) { return null; } return node.Substring(0, num); } public IReadOnlyCollection<string> CollectItemNames() { HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (Gate value in Nodes.Values) { Collect(value); } foreach (DoorLogicEntry value2 in Doors.Values) { Collect(value2.Gate); } foreach (EventLogicEntry value3 in Events.Values) { Collect(value3.Gate); } foreach (CheckLogicEntry value4 in Checks.Values) { Collect(value4.Gate); } return set; void Collect(Gate g) { if (g != null) { if (g.Kind == GateKind.Item && !string.IsNullOrEmpty(g.ItemName)) { set.Add(g.ItemName); } if (g.Children != null) { foreach (Gate child in g.Children) { Collect(child); } } } } } public IReadOnlyCollection<int> CollectTechniqueLevels() { HashSet<int> set = new HashSet<int>(); foreach (Gate value in Nodes.Values) { Collect(value); } foreach (DoorLogicEntry value2 in Doors.Values) { Collect(value2.Gate); } foreach (EventLogicEntry value3 in Events.Values) { Collect(value3.Gate); } foreach (CheckLogicEntry value4 in Checks.Values) { Collect(value4.Gate); } return set; void Collect(Gate g) { if (g != null) { if (g.Kind == GateKind.Technique) { set.Add(g.TechniqueLevel); } if (g.Children != null) { foreach (Gate child in g.Children) { Collect(child); } } } } } } public static class DoorReachability { public const int MaxTechniqueTier = 3; [ThreadStatic] private static DoorSolver _cache; [ThreadStatic] private static DoorLogicGraph _cacheGraph; [ThreadStatic] private static List<ItemSlot> _cacheSlots; [ThreadStatic] private static int _cacheTier; public static int SolverBuilds { get; private set; } public static ReachabilityResult Compute(IReadOnlyDictionary<ItemSlot, Item> assignment, List<ItemSlot> allSlots, DoorLogicGraph graph, Region[] regions, bool fullRandomMode, IReadOnlyList<Item> grants = null, int allowedTechniqueTier = 3) { if (graph == null || graph.IsEmpty) { return new ReachabilityResult { RoomMode = true, State = PlayerState.WithStartingAbilities(fullRandomMode) }; } if (assignment != null && allSlots != null) { bool flag = false; foreach (KeyValuePair<ItemSlot, Item> item in assignment) { if (!ContainsSlot(allSlots, item.Key)) { flag = true; break; } } if (flag) { return ComputeLegacy(assignment, allSlots, graph, regions, fullRandomMode, grants, allowedTechniqueTier); } } if (_cache == null || _cacheTier != allowedTechniqueTier || _cacheGraph != graph || _cacheSlots != allSlots || _cacheTier != allowedTechniqueTier) { _cache = new DoorSolver(graph, allSlots, allowedTechniqueTier); _cacheGraph = graph; _cacheSlots = allSlots; _cacheTier = allowedTechniqueTier; SolverBuilds++; } return _cache.Compute(assignment, fullRandomMode, grants); } public static int ProbeAvailableCount(DoorLogicGraph graph, List<ItemSlot> allSlots, int tier, IReadOnlyList<Item> grants, List<ItemSlot> open, IReadOnlyDictionary<ItemSlot, Item> working, List<ItemSlot> collectInto = null) { if (graph == null || graph.IsEmpty || _cache == null) { return -1; } if (_cacheGraph != graph || _cacheTier != tier) { return -1; } if (!_cache.HasBaseState) { return -1; } return _cache.WithTempGrants(grants, delegate { int num = 0; for (int i = 0; i < open.Count; i++) { ItemSlot itemSlot = open[i]; if (_cache.IsAvailable(itemSlot, working)) { num++; collectInto?.Add(itemSlot); } } return num; }); } private static bool ContainsSlot(List<ItemSlot> slots, ItemSlot slot) { for (int i = 0; i < slots.Count; i++) { if (slots[i] == slot) { return true; } } return false; } private static ReachabilityResult ComputeLegacy(IReadOnlyDictionary<ItemSlot, Item> assignment, List<ItemSlot> allSlots, DoorLogicGraph graph, Region[] regions, bool fullRandomMode, IReadOnlyList<Item> grants = null, int allowedTechniqueTier = 3) { ReachabilityResult reachabilityResult = new ReachabilityResult { RoomMode = true }; PlayerState playerState = PlayerState.WithStartingAbilities(fullRandomMode); playerState.AllowedTechniqueTier = allowedTechniqueTier; reachabilityResult.State = playerState; if (graph == null || graph.IsEmpty) { return reachabilityResult; } TermTable termTable = new TermTable(); foreach (AbilityId value2 in Enum.GetValues(typeof(AbilityId))) { termTable.GetOrAdd(GateTerms.OfAbility(value2)); } foreach (Permission value3 in PermissionsData.All.Values) { termTable.GetOrAdd(GateTerms.OfPermission(value3.Id)); } termTable.GetOrAdd("state:cold"); HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal); HashSet<int> hashSet3 = new HashSet<int>(); foreach (KeyValuePair<string, Gate> node in graph.Nodes) { hashSet.Add(node.Key); GateTerms.Collect(node.Value, termTable, hashSet3); if (!graph.NodeRoom.TryGetValue(node.Key, out var value)) { value = DoorLogicGraph.RoomOfNode(node.Key); } if (!string.IsNullOrEmpty(value)) { hashSet2.Add(value); } } foreach (DoorLogicEntry value4 in graph.Doors.Values) { GateTerms.Collect(value4.Gate, termTable, hashSet3); if (!string.IsNullOrEmpty(value4.From)) { hashSet.Add(value4.From); termTable.GetOrAdd(GateTerms.OfNode(value4.From)); } if (!string.IsNullOrEmpty(value4.ToPort)) { hashSet.Add(value4.ToPort); } if (!string.IsNullOrEmpty(value4.ToRoom)) { hashSet2.Add(value4.ToRoom); } } foreach (EventLogicEntry value5 in graph.Events.Values) { GateTerms.Collect(value5.Gate, termTable, hashSet3); hashSet.Add(value5.Key); if (!string.IsNullOrEmpty(value5.Node)) { termTable.GetOrAdd(GateTerms.OfNode(value5.Node)); } string text = DoorLogicGraph.RoomOfNode(value5.Node); if (!string.IsNullOrEmpty(text)) { hashSet2.Add(text); } } foreach (CheckLogicEntry value6 in graph.Checks.Values) { GateTerms.Collect(value6.Gate, termTable, hashSet3); if (!string.IsNullOrEmpty(value6.Node)) { termTable.GetOrAdd(GateTerms.OfNode(value6.Node)); } string text2 = DoorLogicGraph.RoomOfNode(value6.Node); if (!string.IsNullOrEmpty(text2)) { hashSet2.Add(text2); } } if (!string.IsNullOrEmpty(graph.StartRoom)) { hashSet2.Add(graph.StartRoom); } if (assignment != null) { foreach (KeyValuePair<ItemSlot, Item> item in assignment) { GateTerms.Collect(item.Key.AccessGate, termTable, hashSet3); string text3 = ((item.Key.Region != null) ? item.Key.Region.Id : null); if (!string.IsNullOrEmpty(text3)) { hashSet2.Add(text3); } } } foreach (string item2 in hashSet2) { termTable.GetOrAdd(GateTerms.OfRoom(item2)); } foreach (string item3 in hashSet) { termTable.GetOrAdd(GateTerms.OfNode(item3)); } Progression progression = new Progression(termTable.Count); MainUpdater mainUpdater = new MainUpdater(progression); foreach (string startNode in graph.StartNodes) { GateTerms.MarkNode(progression, termTable, graph, startNode); } if (!string.IsNullOrEmpty(graph.StartRoom)) { GateTerms.MarkRoom(progression, termTable, graph, graph.StartRoom); } foreach (AbilityId ability in playerState.Abilities) { progression.Set(termTable.GetOrAdd(GateTerms.OfAbility(ability)), 1); } if (grants != null) { foreach (Item grant in grants) { GateTerms.ApplyItem(progression, termTable, grant); } } foreach (KeyValuePair<string, Gate> node2 in graph.Nodes) { mainUpdater.AddEntry(new NodeEntry(graph, termTable, node2.Key, node2.Value, allowedTechniqueTier)); } foreach (DoorLogicEntry value7 in graph.Doors.Values) { mainUpdater.AddEntry(new DoorEntry(graph, termTable, value7, allowedTechniqueTier)); } foreach (EventLogicEntry value8 in graph.Events.Values) { mainUpdater.AddEntry(new EventEntry(graph, termTable, value8, allowedTechniqueTier)); } foreach (CheckLogicEntry value9 in graph.Checks.Values) { mainUpdater.AddEntry(new CheckEntry(graph, termTable, value9, allowedTechniqueTier)); } HashSet<ItemSlot> collected = new HashSet<ItemSlot>(); if (assignment != null) { foreach (KeyValuePair<ItemSlot, Item> item4 in assignment) { mainUpdater.AddEntry(new SlotEntry(graph, termTable, item4.Key, item4.Value, collected, allowedTechniqueTier)); } } mainUpdater.Solve(); reachabilityResult.StepCount = mainUpdater.LastStepCount; foreach (string item5 in hashSet) { if (progression.Has(termTable.IdOf(GateTerms.OfNode(item5)))) { playerState.ReachedNodes.Add(item5); } } foreach (LogicTerm item6 in termTable.All) { if (item6 != null && item6.Name != null && item6.Name.StartsWith("node:", StringComparison.Ordinal) && item6.Name.IndexOf("::", StringComparison.Ordinal) < 0 && progression.Has(item6.Id)) { playerState.ReachedNodes.Add(item6.Name.Substring("node:".Length)); } } foreach (string item7 in hashSet2) { if (progression.Has(termTable.IdOf(GateTerms.OfRoom(item7)))) { playerState.ReachableRooms.Add(item7); } } foreach (LogicTerm item8 in termTable.All) { if (item8 != null && item8.Name != null && item8.Name.StartsWith("room:", StringComparison.Ordinal) && progression.Has(item8.Id)) { playerState.ReachableRooms.Add(item8.Name.Substring("room:".Length)); } } foreach (AbilityId value10 in Enum.GetValues(typeof(AbilityId))) { if (progression.Has(termTable.IdOf(GateTerms.OfAbility(value10)))) { playerState.Abilities.Add(value10); } } foreach (Permission value11 in PermissionsData.All.Values) { if (progression.Has(termTable.IdOf(GateTerms.OfPermission(value11.Id)))) { playerState.Permissions.Add(value11.Id); } } if (progression.Has(termTable.IdOf("state:cold"))) { playerState.HasColdResistance = true; } foreach (LogicTerm item9 in termTable.All) { if (item9 != null && item9.Name != null && item9.Name.StartsWith("item:", StringComparison.Ordinal) && progression.Has(item9.Id)) { playerState.OwnedItems.Add(item9.Name.Substring("item:".Length)); } } if (regions != null) { foreach (Region region in regions) { if (playerState.ReachableRooms.Contains(region.Id)) { reachabilityResult.ReachedRegionIds.Add(region.Id); } } } foreach (string reachableRoom in playerState.ReachableRooms) { reachabilityResult.ReachedRoomIds.Add(reachableRoom); } reachabilityResult.ReachedRoomIds.Sort(StringComparer.Ordinal); foreach (string key2 in graph.RoomNodes.Keys) { if (!playerState.ReachableRooms.Contains(key2)) { reachabilityResult.UnreachedRoomIds.Add(key2); } } reachabilityResult.UnreachedRoomIds.Sort(StringComparer.Ordinal); foreach (CheckLogicEntry value12 in graph.Checks.Values) { bool flag = DoorEntries.NodeReached(value12.Node, progression, termTable) && GateTerms.Satisfied(value12.Gate, progression, termTable, allowedTechniqueTier); bool flag2 = (value12.Node == null || playerState.ReachedNodes.Contains(value12.Node) || (value12.Node.EndsWith("#room", StringComparison.Ordinal) && playerState.ReachableRooms.Contains(DoorLogicGraph.RoomOfNode(value12.Node)))) && (value12.Gate == null || GateEvaluator.Satisfied(value12.Gate, playerState)); if (flag) { reachabilityResult.CheckTermTrue++; } if (flag != flag2 && reachabilityResult.CheckMismatch.Count < 8) { reachabilityResult.CheckMismatch.Add("[" + (flag ? "term-only" : "state-only") + "] " + value12.Key + " | node=" + value12.Node + " | gate=" + ((value12.Gate == null) ? "null" : value12.Gate.Kind.ToString())); } } if (assignment != null) { foreach (KeyValuePair<ItemSlot, Item> item10 in assignment) { ItemSlot key = item10.Key; if (key.AccessGate != null) { string text4 = ((key.Region != null) ? key.Region.Id : null); if (text4 != null && playerState.ReachableRooms.Contains(text4) && !GateEvaluator.Satisfied(key.AccessGate, playerState)) { reachabilityResult.BlockedSlotIds.Add(key.Id ?? key.SourceKey ?? "?"); } } } } return reachabilityResult; } private static bool CheckNodeReached(string node, PlayerState state) { if (state.ReachedNodes.Contains(node)) { return true; } if (!node.EndsWith("#room", StringComparison.Ordinal)) { return false; } string text = DoorLogicGraph.RoomOfNode(node); if (text != null) { return state.ReachableRooms.Contains(text); } return false; } private static void MarkNode(string node, PlayerState state, DoorLogicGraph graph) { if (string.IsNullOrEmpty(node)) { return; } state.ReachedNodes.Add(node); string text = DoorLogicGraph.RoomOfNode(node); if (text != null) { state.ReachableRooms.Add(text); string text2 = text + "#room"; if (graph.Nodes.ContainsKey(text2)) { state.ReachedNodes.Add(text2); } } } } public sealed class DoorSolver { private readonly DoorLogicGraph _graph; private readonly int _tier; private readonly TermTable _table = new TermTable(); private readonly Progression _pm; private readonly MainUpdater _updater; private readonly HashSet<string> _nodeKeys = new HashSet<string>(StringComparer.Ordinal); private readonly HashSet<string> _roomKeys = new HashSet<string>(StringComparer.Ordinal); private readonly Dictionary<ItemSlot, SlotEntry> _slotEntries = new Dictionary<ItemSlot, SlotEntry>(); private readonly List<SlotEntry> _slotEntryList = new List<SlotEntry>(); private readonly HashSet<ItemSlot> _collected = new HashSet<ItemSlot>(); internal readonly DoorLogicGraph KeyGraph; internal readonly List<ItemSlot> KeySlots; internal readonly int KeyTier; private bool _baseSolved; public bool HasBaseState => _baseSolved; public DoorSolver(DoorLogicGraph graph, List<ItemSlot> allSlots, int tier) { if (graph == null) { throw new ArgumentNullException("graph"); } _graph = graph; _tier = tier; KeyGraph = graph; KeySlots = allSlots; KeyTier = tier; foreach (AbilityId value2 in Enum.GetValues(typeof(AbilityId))) { _table.GetOrAdd(GateTerms.OfAbility(value2)); } foreach (Permission value3 in PermissionsData.All.Values) { _table.GetOrAdd(GateTerms.OfPermission(value3.Id)); } _table.GetOrAdd("state:cold"); HashSet<int> hashSet = new HashSet<int>(); foreach (KeyValuePair<string, Gate> node in graph.Nodes) { _nodeKeys.Add(node.Key); GateTerms.Collect(node.Value, _table, hashSet); if (!graph.NodeRoom.TryGetValue(node.Key, out var value)) { value = DoorLogicGraph.RoomOfNode(node.Key); } if (!string.IsNullOrEmpty(value)) { _roomKeys.Add(value); } } foreach (DoorLogicEntry value4 in graph.Doors.Values) { GateTerms.Collect(value4.Gate, _table, hashSet); if (!string.IsNullOrEmpty(value4.From)) { _nodeKeys.Add(value4.From); _table.GetOrAdd(GateTerms.OfNode(value4.From)); } if (!string.IsNullOrEmpty(value4.ToPort)) { _nodeKeys.Add(value4.ToPort); } if (!string.IsNullOrEmpty(value4.ToRoom)) { _roomKeys.Add(value4.ToRoom); } } foreach (EventLogicEntry value5 in graph.Events.Values) { GateTerms.Collect(value5.Gate, _table, hashSet); _nodeKeys.Add(value5.Key); if (!string.IsNullOrEmpty(value5.Node)) { _table.GetOrAdd(GateTerms.OfNode(value5.Node)); } string text = DoorLogicGraph.RoomOfNode(value5.Node); if (!string.IsNullOrEmpty(text)) { _roomKeys.Add(text); } } foreach (CheckLogicEntry value6 in graph.Checks.Values) { GateTerms.Collect(value6.Gate, _table, hashSet); if (!string.IsNullOrEmpty(value6.Node)) { _table.GetOrAdd(GateTerms.OfNode(value6.Node)); } string text2 = DoorLogicGraph.RoomOfNode(value6.Node); if (!string.IsNullOrEmpty(text2)) { _roomKeys.Add(text2); } } if (!string.IsNullOrEmpty(graph.StartRoom)) { _roomKeys.Add(graph.StartRoom); } if (allSlots != null) { foreach (ItemSlot allSlot in allSlots) { if (allSlot != null) { GateTerms.Collect(allSlot.AccessGate, _table, hashSet); string text3 = ((allSlot.Region != null) ? allSlot.Region.Id : null); if (!string.IsNullOrEmpty(text3)) { _roomKeys.Add(text3); } } } } foreach (string roomKey in _roomKeys) { _table.GetOrAdd(GateTerms.OfRoom(roomKey)); } foreach (string nodeKey in _nodeKeys) { _table.GetOrAdd(GateTerms.OfNode(nodeKey)); } _pm = new Progression(_table.Count); _updater = new MainUpdater(_pm); foreach (KeyValuePair<string, Gate> node2 in graph.Nodes) { _updater.AddEntry(new NodeEntry(graph, _table, node2.Key, node2.Value, tier)); } foreach (DoorLogicEntry value7 in graph.Doors.Values) { _updater.AddEntry(new DoorEntry(graph, _table, value7, tier)); } foreach (EventLogicEntry value8 in graph.Events.Values) { _updater.AddEntry(new EventEntry(graph, _table, value8, tier)); } foreach (CheckLogicEntry value9 in graph.Checks.Values) { _updater.AddEntry(new CheckEntry(graph, _table, value9, tier)); } if (allSlots == null) { return; } foreach (ItemSlot allSlot2 in allSlots) { if (allSlot2 != null) { SlotEntry slotEntry = new SlotEntry(graph, _table, allSlot2, null, _collected, tier); _updater.AddEntry(slotEntry); _slotEntries[allSlot2] = slotEntry; _slotEntryList.Add(slotEntry); } } } public bool IsAvailable(ItemSlot slot, IReadOnlyDictionary<ItemSlot, Item> working) { if (slot == null) { return false; } if (working != null && working.ContainsKey(slot)) { return false; } string text = ((!string.IsNullOrEmpty(slot.RoomId)) ? slot.RoomId : ((slot.Region != null) ? slot.Region.Id : null)); if (!string.IsNullOrEmpty(text) && !_pm.Has(_table.IdOf(GateTerms.OfRoom(text)))) { return false; } if (slot.AccessGate != null && !GateTerms.Satisfied(slot.AccessGate, _pm, _table, _tier)) { return false; } return true; } public T WithTempGrants<T>(IReadOnlyList<Item> grants, Func<T> body) { _updater.EnterTemp(); try { if (grants != null) { foreach (Item grant in grants) { GateTerms.ApplyItem(_pm, _table, grant); } } _updater.Run(); return body(); } finally { _updater.RevertTemp(); } } public ReachabilityResult Compute(IReadOnlyDictionary<ItemSlot, Item> assignment, bool fullRandomMode, IReadOnlyList<Item> grants) { _updater.ResetAll(); _baseSolved = false; _collected.Clear(); for (int i = 0; i < _slotEntryList.Count; i++) { _slotEntryList[i].SetItem(null); } if (assignment != null) { foreach (KeyValuePair<ItemSlot, Item> item in assignment) { if (item.Key != null) { if (!_slotEntries.TryGetValue(item.Key, out var value)) { value = new SlotEntry(_graph, _table, item.Key, null, _collected, _tier); _updater.AddEntry(value); _slotEntries[item.Key] = value; _slotEntryList.Add(value); } value.SetItem(item.Value); } } } ReachabilityResult reachabilityResult = new ReachabilityResult { RoomMode = true }; PlayerState playerState = PlayerState.WithStartingAbilities(fullRandomMode); playerState.AllowedTechniqueTier = _tier; reachabilityResult.State = playerState; foreach (string startNode in _graph.StartNodes) { GateTerms.MarkNode(_pm, _table, _graph, startNode); } if (!string.IsNullOrEmpty(_graph.StartRoom)) { GateTerms.MarkRoom(_pm, _table, _graph, _graph.StartRoom); } foreach (AbilityId ability in playerState.Abilities) { _pm.Set(_table.GetOrAdd(GateTerms.OfAbility(ability)), 1); } if (grants != null) { foreach (Item grant in grants) { GateTerms.ApplyItem(_pm, _table, grant); } } reachabilityResult.StepCount = _updater.SolveIncremental(); _baseSolved = true; foreach (string nodeKey in _nodeKeys) { if (_pm.Has(_table.IdOf(GateTerms.OfNode(nodeKey)))) { playerState.ReachedNodes.Add(nodeKey); } } foreach (LogicTerm item2 in _table.All) { if (item2 != null && item2.Name != null && item2.Name.StartsWith("node:", StringComparison.Ordinal) && item2.Name.IndexOf("::", StringComparison.Ordinal) < 0 && _pm.Has(item2.Id)) { playerState.ReachedNodes.Add(item2.Name.Substring("node:".Length)); } } foreach (string roomKey in _roomKeys) { if (_pm.Has(_table.IdOf(GateTerms.OfRoom(roomKey)))) { playerState.ReachableRooms.Add(roomKey); } } foreach (LogicTerm item3 in _table.All) { if (item3 != null && item3.Name != null && item3.Name.StartsWith("room:", StringComparison.Ordinal) && _pm.Has(item3.Id)) { playerState.ReachableRooms.Add(item3.Name.Substring("room:".Length)); } } foreach (AbilityId value2 in Enum.GetValues(typeof(AbilityId))) { if (_pm.Has(_table.IdOf(GateTerms.OfAbility(value2)))) { playerState.Abilities.Add(value2); } } foreach (Permission value3 in PermissionsData.All.Values) { if (_pm.Has(_table.IdOf(GateTerms.OfPermission(value3.Id)))) { playerState.Permissions.Add(value3.Id); } } if (_pm.Has(_table.IdOf("state:cold"))) { playerState.HasColdResistance = true; } foreach (LogicTerm item4 in _table.All) { if (item4 != null && item4.Name != null && item4.Name.StartsWith("item:", StringComparison.Ordinal) && _pm.Has(item4.Id)) { playerState.OwnedItems.Add(item4.Name.Substring("item:".Length)); } } foreach (string reachableRoom in playerState.ReachableRooms) { reachabilityResult.ReachedRoomIds.Add(reachableRoom); } reachabilityResult.ReachedRoomIds.Sort(StringComparer.Ordinal); foreach (string key2 in _graph.RoomNodes.Keys) { if (!playerState.ReachableRooms.Contains(key2)) { reachabilityResult.UnreachedRoomIds.Add(key2); } } reachabilityResult.UnreachedRoomIds.Sort(StringComparer.Ordinal); foreach (CheckLogicEntry value4 in _graph.Checks.Values) { bool flag = DoorEntries.NodeReached(value4.Node, _pm, _table) && GateTerms.Satisfied(value4.Gate, _pm, _table, _tier); bool flag2 = (value4.Node == null || playerState.ReachedNodes.Contains(value4.Node) || (value4.Node.EndsWith("#room", StringComparison.Ordinal) && playerState.ReachableRooms.Contains(DoorLogicGraph.RoomOfNode(value4.Node)))) && (value4.Gate == null || GateEvaluator.Satisfied(value4.Gate, playerState)); if (flag) { reachabilityResult.CheckTermTrue++; } if (flag != flag2 && reachabilityResult.CheckMismatch.Count < 8) { reachabilityResult.CheckMismatch.Add("[" + (flag ? "term-only" : "state-only") + "] " + value4.Key + " | node=" + value4.Node + " | gate=" + ((value4.Gate == null) ? "null" : value4.Gate.Kind.ToString())); } } if (assignment != null) { foreach (KeyValuePair<ItemSlot, Item> item5 in assignment) { ItemSlot key = item5.Key; if (key.AccessGate != null) { string text = ((key.Region != null) ? key.Region.Id : null); if (text != null && playerState.ReachableRooms.Contains(text) && !GateEvaluator.Satisfied(key.AccessGate, playerState)) { reachabilityResult.BlockedSlotIds.Add(key.Id ?? key.SourceKey ?? "?"); } } } } return reachabilityResult; } } internal static class DoorEntries { public static int[] Deps(Gate gate, TermTable table) { HashSet<int> hashSet = new HashSet<int>(); GateTerms.Collect(gate, table, hashSet); int[] array = new int[hashSet.Count]; hashSet.CopyTo(array); return array; } public static bool NodeReached(string node, Progression pm, TermTable table) { if (string.IsNullOrEmpty(node)) { return true; } if (pm.Has(table.IdOf(GateTerms.OfNode(node)))) { return true; } if (!node.EndsWith("#room", StringComparison.Ordinal)) { return false; } string text = DoorLogicGraph.RoomOfNode(node); if (text != null) { return pm.Has(table.IdOf(GateTerms.OfRoom(text))); } return false; } } internal sealed class NodeEntry : UpdateEntry { private readonly DoorLogicGraph _g; private readonly TermTable _t; private readonly string _key; private readonly Gate _gate; private readonly int _tier; private readonly int[] _deps; public override IEnumerable<int> Terms => _deps; public NodeEntry(DoorLogicGraph g, TermTable t, string key, Gate gate, int tier) { _g = g; _t = t; _key = key; _gate = gate; _tier = tier; _deps = DoorEntries.Deps(gate, t); } public override bool CanGet(Progression pm) { return GateTerms.Satisfied(_gate, pm, _t, _tier); } public override void OnAdd(Progression pm) { GateTerms.MarkNode(pm, _t, _g, _key); } } internal sealed class DoorEntry : UpdateEntry { private readonly DoorLogicGraph _g; private readonly TermTable _t; private readonly DoorLogicEntry _door; private readonly int _tier; private readonly int[] _deps; public override IEnumerable<int> Terms => _deps; public DoorEntry(DoorLogicGraph g, TermTable t, DoorLogicEntry door, int tier) { _g = g; _t = t; _door = door; _tier = tier; HashSet<int> hashSet = new HashSet<int>(); GateTerms.Collect(door.Gate, t, hashSet); if (door.FromAnyPartition) { string text = DoorLogicGraph.RoomOfNode(door.From); if (text != null) { hashSet.Add(t.GetOrAdd(GateTerms.OfRoom(text))); } } if (!string.IsNullOrEmpty(door.From)) { hashSet.Add(t.GetOrAdd(GateTerms.OfNode(door.From))); } _deps = new int[hashSet.Count]; hashSet.CopyTo(_deps); } public override bool CanGet(Progression pm) { if (string.IsNullOrEmpty(_door.From)) { return false; } bool flag = pm.Has(_t.IdOf(GateTerms.OfNode(_door.From))); if (!flag && _door.FromAnyPartition) { string text = DoorLogicGraph.RoomOfNode(_door.From); flag = text != null && pm.Has(_t.IdOf(GateTerms.OfRoom(text))); } if (!flag) { return false; } return GateTerms.Satisfied(_door.Gate, pm, _t, _tier); } public override void OnAdd(Progression pm) { if (!string.IsNullOrEmpty(_door.ToPort)) { pm.Set(_t.GetOrAdd(GateTerms.OfNode(_door.ToPort)), 1); if (_g.Doors.TryGetValue(_door.ToPort, out var value) && value.From != null) { GateTerms.MarkNode(pm, _t, _g, value.From); } else { string text = _door.ToPort.Replace('@', '#'); if (_g.Nodes.ContainsKey(text)) { pm.Set(_t.GetOrAdd(GateTerms.OfNode(text)), 1); } } string text2 = DoorLogicGraph.RoomOfNode(_door.ToPort); if (text2 != null) { GateTerms.MarkRoom(pm, _t, _g, text2); } } if (!string.IsNullOrEmpty(_door.ToRoom)) { GateTerms.MarkRoom(pm, _t, _g, _door.ToRoom); } } } internal sealed class EventEntry : UpdateEntry { private readonly DoorLogicGraph _g; private readonly TermTable _t; private readonly EventLogicEntry _ev; private readonly int _tier; private readonly int[] _deps; public override IEnumerable<int> Terms => _deps; public EventEntry(DoorLogicGraph g, TermTable t, EventLogicEntry ev, int tier) { _g = g; _t = t; _ev = ev; _tier = tier; HashSet<int> hashSet = new HashSet<int>(); GateTerms.Collect(ev.Gate, t, hashSet); if (!string.IsNullOrEmpty(ev.Node)) { hashSet.Add(t.GetOrAdd(GateTerms.OfNode(ev.Node))); } _deps = new int[hashSet.Count]; hashSet.CopyTo(_deps); } public override bool CanGet(Progression pm) { if (!string.IsNullOrEmpty(_ev.Node) && !pm.Has(_t.IdOf(GateTerms.OfNode(_ev.Node)))) { return false; } return GateTerms.Satisfied(_ev.Gate, pm, _t, _tier); } public override void OnAdd(Progression pm) { pm.Set(_t.GetOrAdd(GateTerms.OfNode(_ev.Key)), 1); } } internal sealed class CheckEntry : UpdateEntry { private readonly DoorLogicGraph _g; private readonly TermTable _t; private readonly CheckLogicEntry _ck; private readonly int _tier; private readonly int[] _deps; public override IEnumerable<int> Terms => _deps; public CheckEntry(DoorLogicGraph g, TermTable t, CheckLogicEntry ck, int tier) { _g = g; _t = t; _ck = ck; _tier = tier; HashSet<int> hashSet = new HashSet<int>(); GateTerms.Collect(ck.Gate, t, hashSet); if (!string.IsNullOrEmpty(ck.Node)) { hashSet.Add(t.GetOrAdd(GateTerms.OfNode(ck.Node))); string text = DoorLogicGraph.RoomOfNode(ck.Node); if (text != null) { hashSet.Add(t.GetOrAdd(GateTerms.OfRoom(text))); } } _deps = new int[hashSet.Count]; hashSet.CopyTo(_deps); } public override bool CanGet(Progression pm) { if (!DoorEntries.NodeReached(_ck.Node, pm, _t)) { return false; } return GateTerms.Satisfied(_ck.Gate, pm, _t, _tier); } public override void OnAdd(Progression pm) { pm.Set(_t.GetOrAdd(GateTerms.OfNode(_ck.Key)), 1); } } internal sealed class SlotEntry : UpdateEntry { private readonly TermTable _t; private readonly ItemSlot _slot; private Item _item; private readonly HashSet<ItemSlot> _collected; private readonly int _tier; private readonly string _room; private readonly int[] _deps; public override IEnumerable<int> Terms => _deps; public SlotEntry(DoorLogicGraph g, TermTable t, ItemSlot slot, Item item, HashSet<ItemSlot> collected, int tier) { _t = t; _slot = slot; _item = item; _collected = collected; _tier = tier; _room = ((slot == null) ? null : ((!string.IsNullOrEmpty(slot.RoomId)) ? slot.RoomId : ((slot.Region != null) ? slot.Region.Id : null))); HashSet<int> hashSet = new HashSet<int>(); GateTerms.Collect(slot?.AccessGate, t, hashSet); if (!string.IsNullOrEmpty(_room)) { hashSet.Add(t.GetOrAdd(GateTerms.OfRoom(_room))); } _deps = new int[hashSet.Count]; hashSet.CopyTo(_deps); } public void SetItem(Item item) { _item = item; } public override bool CanGet(Progression pm) { if (_item == null) { return false; } if (!string.IsNullOrEmpty(_room) && !pm.Has(_t.IdOf(GateTerms.OfRoom(_room)))) { return false; } return GateTerms.Satisfied(_slot.AccessGate, pm, _t, _tier); } public override void OnAdd(Progression pm) { if (_collected != null) { _collected.Add(_slot); } GateTerms.ApplyItem(pm, _t, _item); } } public sealed class MainUpdater { private readonly Dictionary<int, List<UpdateEntry>> _byTerm = new Dictionary<int, List<UpdateEntry>>(); private readonly Queue<int> _pending = new Queue<int>(); private readonly HashSet<int> _queued = new HashSet<int>(); private readonly List<UpdateEntry> _all = new List<UpdateEntry>(); private readonly List<UpdateEntry> _roots = new List<UpdateEntry>(); private readonly Progression _saved; public Progression Pm { get; private set; } public int MaxSteps { get; set; } = 2000000; public int LastStepCount { get; private set; } public int EntryCount => _all.Count; public int RootCount => _roots.Count; public IEnumerable<UpdateEntry> Entries => _all; public MainUpdater(Progression pm) { if (pm == null) { throw new ArgumentNullException("pm"); } Pm = pm; Pm.TermChanged = EnqueueTerm; _saved = new Progression(pm.Capacity); } public void AddEntry(UpdateEntry entry) { if (entry == null) { return; } _all.Add(entry); IEnumerable<int> terms = entry.Terms; if (terms == null) { return; } bool flag = false; foreach (int item in terms) { if (item >= 0) { flag = true; if (!_byTerm.TryGetValue(item, out var value)) { value = new List<UpdateEntry>(2); _byTerm[item] = value; } if (!value.Contains(entry)) { value.Add(entry); } } } if (!flag) { _roots.Add(entry); } } public void AddEntries(IEnumerable<UpdateEntry> entries) { if (entries == null) { return; } foreach (UpdateEntry entry in entries) { AddEntry(entry); } } public void EnqueueTerm(int termId) { if (termId >= 0 && _queued.Add(termId)) { _pending.Enqueue(termId); } } public void GrantTerm(int termId, int value = 1) { Pm.Set(termId, value); } public void GrantTerms(IEnumerable<int> termIds) { if (termIds == null) { return; } foreach (int termId in termIds) { Pm.Set(termId, 1); } } public void UpdateAll() { for (int i = 0; i < _all.Count; i++) { _all[i].Update(Pm); } } public int Run() { int num = 0; while (_pending.Count > 0 && ++num <= MaxSteps) { int num2 = _pending.Dequeue(); _queued.Remove(num2); if (_byTerm.TryGetValue(num2, out var value) && value.Count != 0) { int count = value.Count; for (int i = 0; i < count; i++) { value[i].Update(Pm); } } } LastStepCount = num; return num; } public int SolveIncremental() { for (int i = 0; i < _roots.Count; i++) { _roots[i].Update(Pm); } return Run(); } public int Solve() { UpdateAll(); return Run(); } public void ResetAll() { for (int i = 0; i < _all.Count; i++) { _all[i].Reset(); } Pm.Clear(); _pending.Clear(); _queued.Clear(); LastStepCount = 0; } public void EnterTemp() { _saved.CopyFrom(Pm); Pm.Temp = true; } public void CommitTemp() { for (int i = 0; i < _all.Count; i++) { UpdateEntry updateEntry = _all[i]; if (updateEntry.State == TempState.Temporary) { updateEntry.State = TempState.Permanent; } } Pm.Temp = false; } public void RevertTemp() { for (int i = 0; i < _all.Count; i++) { UpdateEntry updateEntry = _all[i]; if (updateEntry.State == TempState.Temporary) { updateEntry.State = TempState.None; } } Pm.Temp = false; Action<int> termChanged = Pm.TermChanged; Pm.TermChanged = null; try { Pm.CopyFrom(_saved); } finally { Pm.TermChanged = termChanged; } _pending.Clear(); _queued.Clear(); } } public abstract class UpdateEntry { public TempState State; public bool Obtained => State != TempState.None; public virtual bool AlwaysUpdate => false; public abstract IEnumerable<int> Terms { get; } public void Update(Progression pm) { if (!Obtained) { if (CanGet(pm)) { State = (pm.Temp ? TempState.Temporary : TempState.Permanent); OnAdd(pm); } } else if (AlwaysUpdate && CanGet(pm)) { OnAdd(pm); } } public void Update(Progression pm, int updateTerm) { Update(pm); } public abstract bool CanGet(Progression pm); public abstract void OnAdd(Progression pm); public virtual void OnRemove(Progression pm) { } public void Reset() { State = TempState.None; OnReset(); } protected virtual void OnReset() { } public void OnEndTemp(Progression pm, bool saved) { if (State == TempState.Temporary) { if (saved) { State = TempState.Permanent; return; } State = TempState.None; OnRemove(pm); } } } public sealed class Progression { private readonly int[] _value; public Action<int> TermChanged; public bool Temp { get; set; } public int Capacity => _value.Length; public Progression(int termCount) { if (termCount < 0) { termCount = 0; } _value = new int[termCount]; } public int Get(int id) { if (id < 0 || id >= _value.Length) { return 0; } return _value[id]; } public bool Has(int id) { return Get(id) > 0; } public bool Has(int id, int threshold) { return Get(id) >= threshold; } public void Set(int id, int value) { if (id >= 0 && id < _value.Length && _value[id] != value) { _value[id] = value; TermChanged?.Invoke(id); } } public void Incr(int id, int delta) { if (delta != 0) { Set(id, Get(id) + delta); } } public void Clear() { for (int i = 0; i < _value.Length; i++) { _value[i] = 0; } } public void CopyFrom(Progression other) { if (other == null || other._value.Length != _value.Length) { return; } for (int i = 0; i < _value.Length; i++) { if (_value[i] != other._value[i]) { _value[i] = other._value[i]; TermChanged?.Invoke(i); } } Temp = other.Temp; } } public enum TempState { None, Temporary, Permanent } public enum TermPolicy { Node, Mine, MineTech, Tech, Assume, Mode, Region, Never } public sealed class LogicTermResolver { private sealed class PolicyEntry { public TermPolicy Policy; public string Target; public string Reason; } private readonly HashSet<string> _knownRooms; private readonly Dictionary<string, PolicyEntry> _policy = new Dictionary<string, PolicyEntry>(StringComparer.OrdinalIgnoreCase); private readonly HashSet<string> _unknown = new HashSet<string>(StringComparer.Ordinal); private readonly HashSet<string> _unmapped = new HashSet<string>(StringComparer.Ordinal); private readonly Dictionary<string, int> _policyHits = new Dictionary<string, int>(StringComparer.Ordinal); private static readonly Dictionary<string, Func<Gate>> Exact = new Dictionary<string, Func<Gate>>(StringComparer.OrdinalIgnoreCase) { { "WINGS", () => Gate.AbilityGate(AbilityId.DoubleJump) }, { "LEFTCLAW", () => Gate.PermissionGate("Walljump", PermissionSide.Left) }, { "RIGHTCLAW", () => Gate.PermissionGate("Walljump", PermissionSide.Right) }, { "MANTISCLAW", () => Gate.PermissionGate("Walljump", PermissionSide.Left) }, { "CLAW", () => Gate.AbilityGate(AbilityId.Walljump) }, { "DASH", () => Gate.AbilityGate(AbilityId.Dash) }, { "faydown-cloak", () => Gate.AbilityGate(AbilityId.Brolly) }, { "drifters-cloak", () => Gate.AbilityGate(AbilityId.DoubleJump) }, { "drifters-cloak-2", () => Gate.AbilityGate(AbilityId.DoubleJump) }, { "silk-soar", () => Gate.AbilityGate(AbilityId.SuperJump) }, { "cling-grip", () => Gate.AbilityGate(AbilityId.Walljump) }, { "swift-step", () => Gate.AbilityGate(AbilityId.Dash) }, { "silk-spear", () => Gate.AbilityGate(AbilityId.NeedleThrow) }, { "needle-throw", () => Gate.AbilityGate(AbilityId.NeedleThrow) }, { "parry", () => Gate.AbilityGate(AbilityId.Parry) }, { "cross-stitch", () => Gate.AbilityGate(AbilityId.Parry) }, { "pale-nails", () => Gate.AbilityGate(AbilityId.SilkBossNeedle) }, { "sharpdart", () => Gate.AbilityGate(AbilityId.SilkCharge) }, { "rune-rage", () => Gate.AbilityGate(AbilityId.SilkBomb) }, { "thread-storm", () => Gate.AbilityGate(AbilityId.ThreadSphere) }, { "thread-sphere", () => Gate.AbilityGate(AbilityId.ThreadSphere) }, { "silk-charge", () => Gate.AbilityGate(AbilityId.SilkCharge) }, { "elegy", () => Gate.AbilityGate(AbilityId.NeedolinMemory) }, { "beastling-call", () => Gate.AbilityGate(AbilityId.Teleport) }, { "swim", () => Gate.AbilityGate(AbilityId.Swim) }, { "ledge-grab", () => Gate.AbilityGate(AbilityId.LedgeGrab) }, { "progressive-swift-step-first", () => Gate.AbilityGate(AbilityId.Dash) }, { "progressive-swift-step-full", () => Gate.AbilityGate(AbilityId.Dash) }, { "progressive-drifter-cloak", () => Gate.AbilityGate(AbilityId.DoubleJump) }, { "Faydown Cloak", () => Gate.AbilityGate(AbilityId.Brolly) }, { "Drifter's Cloak", () => Gate.AbilityGate(AbilityId.DoubleJump) }, { "Swift Step", () => Gate.AbilityGate(AbilityId.Dash) }, { "Cling Grip", () => Gate.AbilityGate(AbilityId.Walljump) }, { "Clawline", () => Gate.AbilityGate(AbilityId.HarpoonDash) }, { "Silk Soar", () => Gate.AbilityGate(AbilityId.SuperJump) }, { "Needolin", () => Gate.AbilityGate(AbilityId.Needolin) }, { "Needle Strike", () => Gate.AbilityGate(AbilityId.ChargeSlash) }, { "Capability: Swim", () => Gate.AbilityGate(AbilityId.Swim) }, { "Capability: Sprint", () => Gate.AbilityGate(AbilityId.Dash) }, { "Capability: Ledge Grab", () => Gate.AbilityGate(AbilityId.LedgeGrab) }, { "Directional: Cling Grip Left", () => Gate.PermissionGate("Walljump", PermissionSide.Left) }, { "Directional: Cling Grip Right", () => Gate.PermissionGate("Walljump", PermissionSide.Right) }, { "Directional: Ledge Grab Left", () => Gate.AbilityGate(AbilityId.LedgeGrab) }, { "Directional: Ledge Grab Right", () => Gate.AbilityGate(AbilityId.LedgeGrab) }, { "Crest: Beast", () => Gate.AbilityGate(AbilityId.CrestBeast) }, { "Crest: Witch", () => Gate.AbilityGate(AbilityId.CrestWitch) }, { "Crest: Architect", () => Gate.AbilityGate(AbilityId.CrestArchitect) }, { "Crest: Shaman", () => Gate.AbilityGate(AbilityId.ShamanCrest) }, { "Crest: Reaper", () => Gate.AbilityGate(AbilityId.CrestReaper) }, { "Crest: Wanderer", () => Gate.AbilityGate(AbilityId.CrestWanderer) }, { "Crest: Hunter", () => Gate.AbilityGate(AbilityId.CrestHunter) }, { "Melody: Conductor", () => Gate.AbilityGate(AbilityId.MelodyConductor) }, { "Melody: Librarian", () => Gate.AbilityGate(AbilityId.MelodyLibrarian) }, { "Melody: Architect", () => Gate.AbilityGate(AbilityId.MelodyArchitect) } }; private static readonly string[] TechniquePrefixes = new string[29] { "mapper:scuttlebrace", "mapper:flea-brew", "mapper:heal-stall", "mapper:plasmium", "mapper:voltvessels", "mapper:flintslate-stall", "mapper:elite-ball-knowledge", "mapper:beast-crest", "mapper:shaman-crest", "mapper:architect-crest", "mapper:hunter-crest", "mapper:reaper-crest", "mapper:witch-crest", "mapper:wanderer-crest", "mapper:shaman-scuttler", "mapper:enemy-pogo", "mapper:enemy-type-pogo", "mapper:proficient-movement", "mapper:proficient-combat", "mapper:hazard-respawn", "mapper:drill-crystal-pogo", "macro:spike-pogo", "macro:needle-strike", "macro:heal-stall", "Technique:", "Option:", "Path:", "Loadout:", "Usable" }; private readonly HashSet<string> _knownEvents = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public HashSet<string> AssumedAvailable { get; } = new HashSet<string>(StringComparer.Ordinal); public HashSet<string> ModeGated { get; } = new HashSet<string>(StringComparer.Ordinal); public HashSet<string> NativeKeyTerms { get; } = new HashSet<string>(StringComparer.Ordinal); public HashSet<string> EnabledModes { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public HashSet<string> UndefinedEventTerms { get; } = new HashSet<string>(StringComparer.Ordinal); public IReadOnlyCollection<string> UnknownTerms => _unknown; public IReadOnlyCollection<string> UnmappedTerms => _unmapped; public IReadOnlyDictionary<string, int> PolicyHits => _policyHits; public int PolicyCount => _policy.Count; public LogicTermResolver(IEnumerable<string> knownRooms = null) { _knownRooms = new HashSet<string>(StringComparer.OrdinalIgnoreCase); if (knownRooms == null) { return; } foreach (string knownRoom in knownRooms) { if (!string.IsNullOrEmpty(knownRoom)) { _knownRooms.Add(knownRoom); } } } public void SetKnownEvents(IEnumerable<string> events) { if (events == null) { return; } foreach (string @event in events) { if (!string.IsNullOrEmpty(@event)) { _knownEvents.Add(@event); } } } public int LoadPolicy(string path) { if (string.IsNullOrEmpty(path) || !File.Exists(path)) { return 0; } return LoadPolicyLines(File.ReadAllLines(path)); } public int LoadPolicyLines(IEnumerable<string> lines) { if (lines == null) { return 0; } int num = 0; foreach (string line in lines) { if (string.IsNullOrWhiteSpace(line) || line[0] == '#') { continue; } string[] array = line.Split(new char[1] { '\t' }); if (array.Length < 3) { continue; } string text = array[0].Trim(); if (text.Length != 0) { TermPolicy termPolicy = ParsePolicy(array[1]); if (termPolicy != TermPolicy.Node) { _policy[text] = new PolicyEntry { Policy = termPolicy, Target = ((array.Length > 2) ? array[2].Trim() : null), Reason = ((array.Length > 3) ? array[3].Trim() : null) }; num++; } } } return num; } private static TermPolicy ParsePolicy(string text) { if (string.IsNullOrEmpty(text)) { return TermPolicy.Node; } return text.Trim().ToLowerInvariant() switch { "mine" => TermPolicy.Mine, "mine+tech" => TermPolicy.MineTech, "tech" => TermPolicy.Tech, "assume" => TermPolicy.Assume, "mode" => TermPolicy.Mode, "region" => TermPolicy.Region, "never" => TermPolicy.Never, _ => TermPolicy.Node, }; } private Gate ResolveEvent(string key) { if (_knownEvents.Count == 0 || _knownEvents.Contains(key)) { return Gate.EventGate(key); } UndefinedEventTerms.Add(key); string text = ((key.Length > 6) ? key.Substring(6).Trim() : string.Empty); if (text.StartsWith("mapper/owned/", StringComparison.OrdinalIgnoreCase)) { string text2 = text.Substring("mapper/owned/".Length).Trim(); if (text2.Length > 0) { string text3 = "item:" + text2; if (_policy.TryGetValue(text3, out var value)) { return FromPolicy(text3, value); } AssumedAvailable.Add(key); Hit("event:owned"); return Gate.ItemGate(text2); } } if (text.StartsWith("mapper/visit-", StringComparison.OrdinalIgnoreCase)) { string region = text.Substring("mapper/visit-".Length).Trim(); if (region.Length > 0) { List<string> list = _knownRooms.Where((string r) => r.StartsWith(region, StringComparison.OrdinalIgnoreCase)).ToList(); if (list.Count > 0) { Hit("event:visit"); return Gate.Or(list.Select((string r) => Gate.RoomGate(r)).ToArray()); } } } AssumedAvailable.Add(key); Hit("event:assume"); return Gate.And(); } public Gate Resolve(string term) { if (string.IsNullOrWhiteSpace(term)) { return Gate.NeverGate(); } string text = term.Trim(); if (text.StartsWith("mine:", StringComparison.OrdinalIgnoreCase)) { string target = text.Substring(5).Trim(); Gate gate = ResolveTarget(target); if (gate != null) { NativeKeyTerms.Add(text); Hit("mine:"); return gate; } Unknown(text); return Gate.NeverGate(); } if (text.StartsWith("event:", StringComparison.OrdinalIgnoreCase)) { return ResolveEvent(text); } if (text.StartsWith("Event:", StringComparison.Ordinal)) { return ResolveEvent("event:" + text.Substring(6).Trim()); } if (text.StartsWith("Room Node:", StringComparison.OrdinalIgnoreCase)) { string text2 = text.Substring(10).Trim(); if (text2.Length <= 0) { return Gate.NeverGate(); } return Gate.NodeGate(text2); } if (text.IndexOf('#') > 0) { return Gate.NodeGate(text); } int num = text.IndexOf('['); if (num > 0 && text.EndsWith("]", StringComparison.Ordinal)) { string text3 = text.Substring(0, num).Trim(); string text4 = text.Substring(num + 1, text.Length - num - 2).Trim(); if (text3.Length > 0 && text4.Length > 0) { return Gate.NodeGate(text3 + "@" + text4); } } if (_knownRooms.Contains(text)) { return Gate.RoomGate(text); } if (_policy.TryGetValue(text, out var value)) { return FromPolicy(text, value); } if (Exact.TryGetValue(text, out var value2)) { NativeKeyTerms.Add(text); Hit("exact"); return value2() ?? Gate.NeverGate(); } Gate gate2 = ResolvePrefixed(text); if (gate2 != null) { return gate2; } if (IsTechnique(text)) { Hit("tech"); return TechniqueGateFromTerm(text); } if (AbilityAlias.TryResolve(text, out var id)) { NativeKeyTerms.Add(text); Hit("alias"); return Gate.AbilityGate(id); } Unknown(text); return Gate.NeverGate(); } private Gate FromPolicy(string term, PolicyEntry pe) { switch (pe.Policy) { case TermPolicy.Mine: case TermPolicy.MineTech: { Gate gate = ResolveTarget(pe.Target); if (gate != null) { NativeKeyTerms.Add(term); Hit((pe.Policy == TermPolicy.MineTech) ? "mine+tech" : "mine"); return gate; } Unknown(term); return Gate.NeverGate(); } case TermPolicy.Tech: { int result2 = 1; int.TryParse(pe.Target, NumberStyles.Integer, CultureInfo.InvariantCulture, out result2); Hit("tech"); return Gate.TechniqueGate(result2); } case TermPolicy.Assume: AssumedAvailable.Add(term); Hit("assume"); return Gate.And(); case TermPolicy.Mode: { ModeGated.Add(term); Hit("mode"); string text = ModeNameOf(term); bool flag = text != null && EnabledModes.Contains(text); if (string.Equals(pe.Target, "on", StringComparison.OrdinalIgnoreCase) != flag) { return Gate.NeverGate(); } return Gate.And(); } case TermPolicy.Region: { Gate result = RegionGate(pe.Target); Hit("region"); return result; } case TermPolicy.Never: Unknown(term); return Gate.NeverGate(); default: return Gate.NeverGate(); } } private static string ModeNameOf(string term) { string text = term; if (text.StartsWith("state:", StringComparison.OrdinalIgnoreCase)) { text = text.Substring(6); } else if (text.StartsWith("mapper:", StringComparison.OrdinalIgnoreCase)) { text = text.Substring(7); } if (text.EndsWith("-on", StringComparison.OrdinalIgnoreCase) || text.EndsWith("-off", StringComparison.OrdinalIgnoreCase)) { text = text.Substring(0, text.Length - 3); } return text; } private Gate RegionGate(string prefix) { if (string.IsNullOrEmpty(prefix)) { return Gate.And(); } List<Gate> list = new List<Gate>(); foreach (string knownRoom in _knownRooms) { if (knownRoom.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { list.Add(Gate.RoomGate(knownRoom)); } } if (list.Count == 0) { return Gate.And(); } if (list.Count != 1) { return Gate.Or(list.ToArray()); } return list[0]; } public Gate ResolveTarget(string target) { if (string.IsNullOrWhiteSpace(target)) { return null; } string[] array = target.Split(new char[1] { '&' }); List<Gate> list = new List<Gate>(); string[] array2 = array; foreach (string text in array2) { Gate gate = ResolveTargetPart(text.Trim()); if (gate == null) { return null; } list.Add(gate); } if (list.Count == 0) { return null; } if (list.Count != 1) { return Gate.And(list.ToArray()); } return list[0]; } private Gate ResolveTargetPart(string part) { if (part.Length == 0) { return null; } if (part.Equals("true", StringComparison.OrdinalIgnoreCase)) { return Gate.And(); } if (part.Equals("cold", StringComparison.OrdinalIgnoreCase)) { return Gate.ColdGate(); } if (part.StartsWith("v", StringComparison.OrdinalIgnoreCase) && part.Length == 2 && char.IsDigit(part[1])) { return Gate.VerticalGate(part[1] - 48); } if (part.StartsWith("hl", StringComparison.OrdinalIgnoreCase) && part.Length == 3 && char.IsDigit(part[2])) { return Gate.HorizontalGate(part[2] - 48, PermissionSide.Left); } if (part.StartsWith("hr", StringComparison.OrdinalIgnoreCase) && part.Length == 3 && char.IsDigit(part[2])) { return Gate.HorizontalGate(part[2] - 48, PermissionSide.Right); } if (part.StartsWith("ability:", StringComparison.OrdinalIgnoreCase)) { string[] array = part.Substring(8).Split(new char[1] { '|' }); List<Gate> list = new List<Gate>(); string[] array2 = array; for (int i = 0; i < array2.Length; i++) { if (!TryAbility(array2[i].Trim(), out var id)) { return null; } list.Add(Gate.AbilityGate(id)); } if (list.Count == 0) { return null; } if (list.Count != 1) { return Gate.Or(list.ToArray()); } return list[0]; } if (part.StartsWith("perm:", StringComparison.OrdinalIgnoreCase)) { string text = part.Substring(5); int num = text.LastIndexOf(':'); string id2; PermissionSide side; if (num > 0) { id2 = text.Substring(0, num); side = (text.Substring(num + 1).Equals("right", StringComparison.OrdinalIgnoreCase) ? PermissionSide.Right : PermissionSide.Left); } else if (text.EndsWith("_L", StringComparison.OrdinalIgnoreCase)) { id2 = text.Substring(0, text.Length - 2); side = PermissionSide.Left; } else if (text.EndsWith("_R", StringComparison.OrdinalIgnoreCase)) { id2 = text.Substring(0, text.Length - 2); side = PermissionSide.Right; } else { id2 = text; side = PermissionSide.Left; } return Gate.PermissionGate(id2, side); } if (part.StartsWith("crest:", StringComparison.OrdinalIgnoreCase)) { string text2 = part.Substring(6).Trim(); if (text2.Equals("any", StringComparison.OrdinalIgnoreCase)) { return AnyCrestGate(); } if (CrestAbility(text2, out var id3)) { return Gate.AbilityGate(id3); } return null; } if (part.StartsWith("item:", StringComparison.OrdinalIgnoreCase)) { return Gate.ItemGate(part.Substring(5)); } if (part.StartsWith("tech:", StringComparison.OrdinalIgnoreCase)) { int result = 1; int.TryParse(part.Substring(5), NumberStyles.Integer, CultureInfo.InvariantCulture, out result); return Gate.TechniqueGate(result); } return null; } private static bool CrestAbility(string name, out AbilityId id) { switch (name.T
BepInEx/plugins/SilksongItemRandomizer.dll
Decompiled a week 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.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Permissions; using System.Text; using System.Threading; using AssetChainFixer; using Benchwarp.Components; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GlobalEnums; using GlobalSettings; using HarmonyLib; using HutongGames.PlayMaker; using HutongGames.PlayMaker.Actions; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using PharloomCore; using PharloomCore.Data; using PharloomCore.Logic; using PharloomCore.Model; using QuestPlaymakerActions; using SilksongItemRandomizer; using StartingAbilityPicker; using TMProOld; using TeamCherry.Localization; using TeamCherry.SharedUtils; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.AddressableAssets.ResourceLocators; using UnityEngine.Events; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.ResourceManagement.ResourceProviders; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("SilksongItemRandomizer")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("SilksongItemRandomizer")] [assembly: AssemblyTitle("SilksongItemRandomizer")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/YourGitHubUsername/SilksongItemRandomizer")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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; } } } public class HotkeyHandler : MonoBehaviour { private GUIStyle _tipStyle; private GUIStyle _titleBoldStyle; private GUIStyle _nameBoldStyle; private GUIStyle _hintStyle; private GUIStyle _pickBtnStyle; private GUIStyle _skipBtnStyle; private GUIStyle _smallHintStyle; private GUIStyle _noteFieldStyle; private GUIStyle _noteBtnStyle; private static bool _isChineseCache; private List<(string cat, string name)> _currentCandidates = new List<(string, string)>(); private int _f4MsgCycleIndex; private int _f4ComboTier; private static readonly (string kind, string evt)[] F4GlowPopupItems = new(string, string)[9] { ("heart", "CORAL"), ("heart", "FLOWER"), ("heart", "HUNTER"), ("heart", "CLOVER"), ("melody", "CONDUCTOR"), ("melody", "LIBRARIAN"), ("melody", "ARCHITECT"), ("hcombo", "1"), ("hcombo", "2") }; private int _f4PopupIndex; private static bool _f4Toggle; private static int _crestPopupIndex; private static readonly string[] _testSkillFields = new string[17] { "hasDash", "hasWalljump", "hasHarpoonDash", "hasNeedolin", "hasSuperJump", "HasSeenEvaHeal", "hasNeedleThrow", "hasThreadSphere", "hasSilkCharge", "hasSilkBomb", "hasSilkBossNeedle", "hasParry", "hasBrolly", "hasDoubleJump", "hasChargeSlash", "hasNeedolinMemoryPowerup", "hasFastTravelTeleport" }; private static int _extraSlotTestIndex = 0; private static bool _slotDepsLoaded; private static int _splitTestIndex = 0; private static readonly (string label, string skillField, bool right, bool left)[] DirectionCalibList = new(string, string, bool, bool)[8] { ("冲刺左", "hasDash", false, true), ("冲刺右", "hasDash", true, false), ("飞针左", "hasHarpoonDash", false, true), ("飞针右", "hasHarpoonDash", true, false), ("漂浮左", "hasBrolly", false, true), ("漂浮右", "hasBrolly", true, false), ("壁跳左", "hasWalljump", false, true), ("壁跳右", "hasWalljump", true, false) }; private int _dirCalibIndex; private static int _loreTestIndex = -1; private static int _f4SelfGiveIndex = 0; private static readonly (string label, string[] keys)[] SpriteSearchGroups = new(string, string[])[21] { ("prompt", new string[1] { "prompt" }), ("slash", new string[1] { "slash" }), ("needle", new string[1] { "needle" }), ("geo", new string[1] { "geo" }), ("rosary", new string[2] { "rosary", "bead" }), ("toll", new string[1] { "toll" }), ("map", new string[1] { "map" }), ("quest", new string[1] { "quest" }), ("station", new string[1] { "station" }), ("bench", new string[1] { "bench" }), ("bell", new string[1] { "bell" }), ("shrine", new string[2] { "shrine", "chapel" }), ("lock", new string[2] { "lock", "door" }), ("silk", new string[1] { "silk" }), ("shell", new string[2] { "shell", "shard" }), ("spool", new string[1] { "spool" }), ("crest", new string[1] { "crest" }), ("mask", new string[1] { "mask" }), ("heart", new string[1] { "heart" }), ("key", new string[1] { "key" }), ("memory", new string[2] { "memory", "orb" }) }; private static readonly (string cat, string name)[] SpritePickCandidates = new(string, string)[144] { ("prompt", "Cursed_item_prompt"), ("prompt", "Map_prompt"), ("prompt", "Tools_prompt"), ("prompt", "Crest_prompt"), ("prompt", "Journal_Prompt"), ("prompt", "Deep_Memory_Prompt"), ("prompt", "kings_brand_prompt"), ("prompt", "Wall_Jump_Prompt"), ("prompt", "Needolin_Prompt"), ("prompt", "dreamer_mask_prompt"), ("prompt", "Materium_Prompt"), ("prompt", "prompt_silkheart"), ("needle", "T_longneedle"), ("needle", "S_needle_throw"), ("needle", "cradle_needle"), ("needle", "Curse_dark_needle"), ("needle", "prompt_hornet_needle_throw"), ("rosary", "I_rosary_icon_clean"), ("rosary", "I_rosary_icon_big_clean"), ("rosary", "I_rosary_icon_mid_clean"), ("rosary", "I_rosary_icon_etched"), ("rosary", "tiny_icon_rosary"), ("rosary", "rosary_rock_type_base"), ("rosary", "T_rosary_magnet"), ("rosary", "tiny_tool_icon_rosary_cannon"), ("rosary", "rosary_cache_bell"), ("toll", "Toll_machine_silk_ration"), ("toll", "Toll_cap0003"), ("toll", "Toll_cog0006"), ("toll", "bellbench_toll_machine"), ("toll", "bellbench_toll_machine_map"), ("map", "I_map"), ("map", "I_map_type_02"), ("map", "I_quill_and_map"), ("map", "map_arrow"), ("map", "No_Map_symbol"), ("map", "quest_map_icon_round_style"), ("map", "Shop_map_icon__weavehome"), ("map", "gramaphone"), ("quest", "quest_dot_full"), ("quest", "quest_dot_empty"), ("quest", "Kill_quest_icon"), ("quest", "goop_quest_icon"), ("quest", "hunters_nest_quest_icon"), ("quest", "Steel_Servant_Quest_marker"), ("quest", "Mr_Mushroom_quest_notch"), ("quest", "quest_map_icon_round_style"), ("station", "pin_stag_station_shop_icon"), ("station", "pin_tube_station_shop_icon"), ("station", "pin_stag_station"), ("station", "pin_tube_station"), ("bench", "Bench_item_prompt"), ("bench", "pin_bench_shop_icon"), ("bench", "pin_bench"), ("bench", "pin_bench_bell"), ("bench", "town_bench_lit"), ("bell", "Hornet_icon_bell_clapper"), ("bell", "Bell_Hub_Icons0001"), ("bell", "Bell_Hub_Icons0006"), ("bell", "Hornet_bellway_token"), ("bell", "Hornet_bellway_token_duo"), ("bell", "QI_Main_bell_beast"), ("bell", "QI_Main_bellshrines"), ("bell", "bell_shrine_single_silk"), ("bell", "crawbell"), ("bell", "Music_box_bell0000"), ("bell", "bell_sub_sign"), ("shrine", "QI_Main_bellshrines"), ("shrine", "quest_map_icon_songshrines"), ("shrine", "Bellshrine"), ("shrine", "Belltown_Shrine"), ("shrine", "bell_shrine_single_silk"), ("lock", "UI_tool_slot_locked_fill"), ("lock", "Tool_slot_lock_ring"), ("lock", "trap_door_circle"), ("lock", "trapdoor_lever"), ("lock", "music_box_bell_lock0000"), ("silk", "silk_heart_inv_icon"), ("silk", "icon_silk_materium"), ("silk", "silk_heart_scene"), ("silk", "spell_core_slim_silk_heart_ss"), ("silk", "Silk_Grub_large_cocoon0000"), ("silk", "Silk_Grub_small_cocoon"), ("silk", "Toll_machine_silk_ration"), ("silk", "silk_bomb_prompt"), ("silk", "UI_halo_silk0000"), ("shell", "Shell_shard_icon"), ("shell", "I_shell_shard_icon_large"), ("shell", "Icon_Beast_Shard"), ("shell", "T_shell_satchel"), ("shell", "T_sting_shard"), ("shell", "tiny_tool_icon_sting_shard"), ("shell", "HUD_shard_shop"), ("shell", "glass_shards"), ("spool", "Hornet_Spool_Upgrade_Shop_Icon"), ("spool", "Hornet_Spool_Upgrade_Shop_Icon_full"), ("spool", "Hornet_Spool_Upgrade_Shop_Icon_Heart"), ("spool", "Inv_spool_backboard_ss"), ("spool", "T_focus_spool"), ("spool", "T_spool_bar_extender"), ("spool", "spool_upgrade_pickup"), ("spool", "Thread_Spool_spinner0000"), ("crest", "C_crest"), ("crest", "M_crest"), ("crest", "Tools_UI_Crest_Change"), ("crest", "crest_blank"), ("crest", "cursed_crest_animated0001"), ("crest", "Bell_Hub_Crest_Icon_Animated0000"), ("crest", "Crest_prompt"), ("mask", "Hornet_T_fractured_mask"), ("mask", "bestiary_icon_frame_mask"), ("mask", "dreamer_mask_prompt"), ("mask", "soft_masker"), ("mask", "sand_blown_mask"), ("mask", "Goomba_mask_chunk_01"), ("heart", "Heart_Piece_01"), ("heart", "Heart_Piece_02"), ("heart", "Heart_Piece_03"), ("heart", "silk_heart_inv_icon"), ("heart", "bone_heart_egg"), ("heart", "cog_heart_pieces"), ("heart", "heart_prompt_clover"), ("heart", "heart_prompt_flower"), ("heart", "heart_prompt_coral"), ("heart", "coral_king_heart_icon0000"), ("key", "dock_key"), ("key", "I_key_architect"), ("key", "I_key_whiteward"), ("key", "I_chute_key_whiteward"), ("key", "I_slab_key"), ("key", "I_slab_key_brass"), ("key", "I_slab_key_gold"), ("key", "I_slab_key_old"), ("key", "belltown_house_key"), ("key", "rusted_cage_key"), ("memory", "soul_orb"), ("memory", "soul_orb_generic"), ("memory", "black_soul_orb"), ("memory", "new_item_orb"), ("memory", "sc_grey_orb_single"), ("memory", "memory_large_flat"), ("memory", "memory_large_flat_outer"), ("memory", "red_memory_bottle"), ("memory", "UI_halo_orb_beams") }; private bool _pickerActive; private int _pickerIndex; private readonly List<string> _pickedNames = new List<string>(); private bool _annotateActive; private int _annotateIndex; private string _noteText = ""; private readonly List<(string name, string note)> _annotated = new List<(string, string)>(); private List<string> _annotateList = new List<string>(); private bool _isDumpingSprites; private bool _isDumpingTransitions; private static readonly string[] DumpSkipSubstrings = new string[9] { "Travel", "Caravan", "Diving_Bell", "Menu", "Boot", "Preloader", "Intro", "Cutscene", "Credits" }; private static readonly string[] SpecialNameKeywords = new string[8] { "silk spool", "heart piece", "mossberry", "aspid berry", "berry", "spool", "moss", "mask piece" }; private bool _isScanningSpecial; private static readonly string[] AspidBerryBoolNames = new string[3] { "mosstownAspidBerryCollected", "bonegraveAspidBerryCollected", "bonetownAspidBerryCollected" }; public static bool IsScanningChecks { get; private set; } private void Update() { GlobalConfig.TickPersist(); SilksongItemRandomizerAPI.FlushLimitsRegenerate(); PreGeneratedMap.PumpBackgroundBuild(); if (_pickerActive) { if (Input.GetKeyDown((KeyCode)13)) { PickCurrent(pick: true); } else if (Input.GetKeyDown((KeyCode)120)) { PickCurrent(pick: false); } } if (_annotateActive && Input.GetKeyDown((KeyCode)13)) { SaveCurrentNote(); } if (Input.GetKeyDown((KeyCode)287)) { WarpToLastBench(); } if (Input.GetKeyDown((KeyCode)289)) { ToggleRecentItemsUI(); } if (Input.GetKeyDown((KeyCode)27)) { Plugin.Instance?.RefreshBenchwarpUI(); } } private void StartFleaPicker() { if (!_isDumpingSprites) { ((MonoBehaviour)this).StartCoroutine(LoadAtlasesThenStartFleaPicker()); } } private void StartMapSpritePicker() { if (!_isDumpingSprites) { ((MonoBehaviour)this).StartCoroutine(LoadAtlasesThenStartMapPicker()); } } private void TestGrantDirectionPermissions() { try { DirectionPermissionReward directionPermissionReward = new DirectionPermissionReward(Locale.Get("上劈权限"), "upward", allowRight: false, allowLeft: false, isAttack: true); DirectionPermissionReward directionPermissionReward2 = new DirectionPermissionReward(Locale.Get("左劈权限"), "left", allowRight: false, allowLeft: false, isAttack: true); DirectionPermissionReward directionPermissionReward3 = new DirectionPermissionReward(Locale.Get("右劈权限"), "right", allowRight: false, allowLeft: false, isAttack: true); directionPermissionReward.Give(); RecentItemsUI.AddItem(directionPermissionReward); directionPermissionReward2.Give(); RecentItemsUI.AddItem(directionPermissionReward2); directionPermissionReward3.Give(); RecentItemsUI.AddItem(directionPermissionReward3); Plugin.ShowNotification("已发放 上/左/右劈 方向权限(验证持久化+弹窗+图标)", 4f); } catch (Exception arg) { Plugin.Log.LogError($"[F4方向测试] 发放失败: {arg}"); } } private IEnumerator LoadAtlasesThenStartMapPicker() { if (_isDumpingSprites) { yield break; } _isDumpingSprites = true; string[] pendingKeys = new string[1] { "inv_nail" }; List<string> list = new List<string>(); try { foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text && !string.IsNullOrEmpty(text)) { list.Add(text); } } } } catch { } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string item in list) { if (!IsLikelyAtlasKey(item)) { continue; } string[] array = pendingKeys; foreach (string value in array) { if (item.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { hashSet.Add(item); break; } } } int loadedOk = 0; int loadedFail = 0; foreach (string item2 in hashSet) { AsyncOperationHandle<Object> handle; try { handle = Addressables.LoadAssetAsync<Object>((object)item2); } catch { loadedFail++; continue; } float deadline = Time.realtimeSinceStartup + 20f; while (!handle.IsDone && Time.realtimeSinceStartup <= deadline) { yield return null; } if (handle.IsDone && (int)handle.Status == 1) { loadedOk++; continue; } loadedFail++; try { if (handle.IsValid()) { Addressables.Release<Object>(handle); } } catch { } } SpriteCache.Reset(); SpriteCache.EnsureBuilt(); _currentCandidates.Clear(); Sprite[] array2 = Resources.FindObjectsOfTypeAll<Sprite>(); foreach (Sprite val in array2) { if ((Object)(object)val == (Object)null || string.IsNullOrEmpty(((Object)val).name)) { continue; } string[] array = pendingKeys; foreach (string value2 in array) { if (((Object)val).name.IndexOf(value2, StringComparison.OrdinalIgnoreCase) >= 0) { _currentCandidates.Add(("map", ((Object)val).name)); break; } } } if (_currentCandidates.Count == 0) { Plugin.Log.LogInfo("[F4] 未找到剩余地图名的贴图。"); _isDumpingSprites = false; yield break; } _pickerActive = true; _pickerIndex = 0; _pickedNames.Clear(); Plugin.Log.LogInfo($"[F4] 找到 {_currentCandidates.Count} 个剩余地图图标,开始筛选。"); _isDumpingSprites = false; } private void StartSwimIconPicker() { if (!_isDumpingSprites) { ((MonoBehaviour)this).StartCoroutine(LoadAtlasesThenStartSwimIconPicker()); } } private IEnumerator LoadAtlasesThenStartSwimIconPicker() { if (_isDumpingSprites) { yield break; } _isDumpingSprites = true; string[] pendingKeys = new string[5] { "clawline", "harpoon dash", "harpoondash", "harpoon", "dash" }; List<string> list = new List<string>(); try { foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text && !string.IsNullOrEmpty(text)) { list.Add(text); } } } } catch { } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string item in list) { if (!IsLikelyAtlasKey(item)) { continue; } string[] array = pendingKeys; foreach (string value in array) { if (item.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { hashSet.Add(item); break; } } } int loadedOk = 0; int loadedFail = 0; foreach (string item2 in hashSet) { AsyncOperationHandle<Object> handle; try { handle = Addressables.LoadAssetAsync<Object>((object)item2); } catch { loadedFail++; continue; } float deadline = Time.realtimeSinceStartup + 20f; while (!handle.IsDone && Time.realtimeSinceStartup <= deadline) { yield return null; } if (handle.IsDone && (int)handle.Status == 1) { loadedOk++; continue; } loadedFail++; try { if (handle.IsValid()) { Addressables.Release<Object>(handle); } } catch { } } SpriteCache.Reset(); SpriteCache.EnsureBuilt(); _currentCandidates.Clear(); Sprite[] array2 = Resources.FindObjectsOfTypeAll<Sprite>(); foreach (Sprite val in array2) { if ((Object)(object)val == (Object)null || string.IsNullOrEmpty(((Object)val).name)) { continue; } string[] array = pendingKeys; foreach (string value2 in array) { if (((Object)val).name.IndexOf(value2, StringComparison.OrdinalIgnoreCase) >= 0) { _currentCandidates.Add(("swimicon", ((Object)val).name)); break; } } } foreach (var currentCandidate in _currentCandidates) { Plugin.Log.LogInfo("[F4泳图标] " + currentCandidate.name); } if (_currentCandidates.Count == 0) { Plugin.Log.LogInfo("[F4泳图标] 未找到关键词图标。"); _isDumpingSprites = false; yield break; } _pickerActive = true; _pickerIndex = 0; _pickedNames.Clear(); Plugin.Log.LogInfo($"[F4泳图标] 找到 {_currentCandidates.Count} 个图标,开始筛选。"); _isDumpingSprites = false; } private void TestGlowPopupCycle() { try { var (text, text2) = F4GlowPopupItems[_f4PopupIndex++ % F4GlowPopupItems.Length]; Plugin.Log.LogInfo("[F4发光弹窗] " + text + ":" + text2); if (text switch { "heart" => HeartMsgHelper.Show(text2) ? 1 : 0, "melody" => MelodyMsgHelper.Show(text2) ? 1 : 0, "hcombo" => OfficialMsgHelper.ShowHunterCombo(int.Parse(text2), (Action)null) ? 1 : 0, _ => 0, } == 0) { Plugin.Log.LogWarning("[F4发光弹窗] " + text + " " + text2 + " 弹出失败"); } ((MonoBehaviour)this).StartCoroutine(DumpGlowIconDelayed(text, text2)); } catch (Exception arg) { Plugin.Log.LogError($"[F4发光弹窗] 异常: {arg}"); } } private IEnumerator DumpGlowIconDelayed(string kind, string evt) { for (int f = 0; f < 6; f++) { yield return null; } try { List<GameObject> list = (from g in Object.FindObjectsOfType<GameObject>() where Object.op_Implicit((Object)(object)g) && ((Object)g).name.StartsWith("UI Msg Get Item", StringComparison.OrdinalIgnoreCase) select g).ToList(); Plugin.Log.LogInfo($"[F4发光弹窗] {kind}:{evt}: 找到 {list.Count} 个克隆体"); foreach (GameObject item in list) { Transform val = item.transform.Find("Icon"); Transform val2 = item.transform.Find("Icon Glow"); SpriteRenderer val3 = (Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponentInChildren<SpriteRenderer>(true) : null); SpriteRenderer val4 = (Object.op_Implicit((Object)(object)val2) ? ((Component)val2).GetComponentInChildren<SpriteRenderer>(true) : null); Plugin.Log.LogInfo("[F4发光弹窗] " + kind + ":" + evt + ": Icon='" + (((val != null) ? ((Object)val).name : null) ?? "NULL") + "' sprite=" + ((Object.op_Implicit((Object)(object)val3) && Object.op_Implicit((Object)(object)val3.sprite)) ? ((Object)val3.sprite).name : "NULL") + " | Glow='" + (((val2 != null) ? ((Object)val2).name : null) ?? "NULL") + "' sprite=" + ((Object.op_Implicit((Object)(object)val4) && Object.op_Implicit((Object)(object)val4.sprite)) ? ((Object)val4.sprite).name : "NULL")); } } catch (Exception ex) { Plugin.Log.LogError("[F4发光弹窗] 反查图标异常: " + ex.Message); } } private void TestTriggerChapelDoorClose() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) try { Scene activeScene = SceneManager.GetActiveScene(); string name = ((Scene)(ref activeScene)).name; Plugin.Log.LogInfo("[教堂关门测试] 场景: " + name); GameObject val = null; GameObject val2 = null; GameObject val3 = null; List<string> list = new List<string>(); PlayMakerFSM val4 = null; activeScene = SceneManager.GetActiveScene(); GameObject[] rootGameObjects = ((Scene)(ref activeScene)).GetRootGameObjects(); foreach (GameObject val5 in rootGameObjects) { Transform[] componentsInChildren = val5.GetComponentsInChildren<Transform>(true); foreach (Transform val6 in componentsInChildren) { string name2 = ((Object)val6).name; if (name2.IndexOf("Door", StringComparison.OrdinalIgnoreCase) >= 0 || name2.IndexOf("door", StringComparison.OrdinalIgnoreCase) >= 0) { list.Add(name2); } if (name2 == "Door DoClose" && (Object)(object)val == (Object)null) { val = ((Component)val6).gameObject; } else if (name2 == "Door Closed" && (Object)(object)val2 == (Object)null) { val2 = ((Component)val6).gameObject; } else if (name2 == "Door Art" && (Object)(object)val3 == (Object)null) { val3 = ((Component)val6).gameObject; } } PlayMakerFSM[] componentsInChildren2 = val5.GetComponentsInChildren<PlayMakerFSM>(true); foreach (PlayMakerFSM val7 in componentsInChildren2) { if ((Object)(object)val4 == (Object)null && val7.FsmName == "chapel_door_control") { val4 = val7; } } } Plugin.Log.LogInfo("[教堂关门测试] chapel_door_control FSM: " + (((Object)(object)val4 != (Object)null) ? ((Object)((Component)val4).gameObject).name : "未找到")); Plugin.Log.LogInfo("[教堂关门测试] Door DoClose: " + (((Object)(object)val != (Object)null) ? ((Object)val).name : "未找到") + " | Door Closed: " + (((Object)(object)val2 != (Object)null) ? ((Object)val2).name : "未找到") + " | Door Art: " + (((Object)(object)val3 != (Object)null) ? ((Object)val3).name : "未找到")); Plugin.Log.LogInfo("[教堂关门测试] 场景内 door 相关对象: " + string.Join(", ", list.Distinct<string>(StringComparer.OrdinalIgnoreCase))); if ((Object)(object)val4 == (Object)null) { Plugin.Log.LogWarning("[教堂关门测试] 无 chapel_door_control FSM,退出"); return; } Plugin.Log.LogInfo("[教堂关门测试] FSM 当前状态: " + val4.Fsm.ActiveStateName); try { FsmVariables variables = val4.Fsm.Variables; FsmEnum fsmEnum = variables.GetFsmEnum("Crest Type"); FsmObject fsmObject = variables.GetFsmObject("Crest Object"); FsmString fsmString = variables.GetFsmString("Closed PD Bool"); ModLog log = Plugin.Log; Enum arg = ((fsmEnum != null) ? fsmEnum.Value : null); object obj; if (fsmObject == null) { obj = null; } else { Object value = fsmObject.Value; obj = ((value != null) ? value.name : null); } if (obj == null) { obj = "空"; } log.LogInfo(string.Format("[教堂关门测试] Crest Type: {0} | Crest Object: {1} | Closed PD Bool: {2}", arg, obj, ((fsmString != null) ? fsmString.Value : null) ?? "空")); PlayerData instance = PlayerData.instance; if (instance != null) { Plugin.Log.LogInfo($"[教堂关门测试] chapelClosed: reaper={instance.chapelClosed_reaper} wanderer={instance.chapelClosed_wanderer} beast={instance.chapelClosed_beast} witch={instance.chapelClosed_witch} toolmaster={instance.chapelClosed_toolmaster} shaman={instance.chapelClosed_shaman}"); } try { Plugin.Log.LogInfo("[教堂关门测试] 平替标记: " + string.Join(", ", Plugin.SaveData.ChapelRandomizedCrests)); } catch { } } catch (Exception ex) { Plugin.Log.LogWarning("[教堂关门测试] 诊断输出异常: " + ex.Message); } val4.Fsm.SetState("Do Close"); Plugin.Log.LogInfo("[教堂关门测试] 已 SetState(\"Do Close\"),观察关门动画是否播放"); } catch (Exception arg2) { Plugin.Log.LogError($"[教堂关门测试] 异常: {arg2}"); } } private void TestGiveRandomCrest() { try { List<ToolCrest> allCrests = ToolItemManager.GetAllCrests(); if (allCrests == null || allCrests.Count == 0) { Plugin.Log.LogError("[F4纹章] ToolItemManager 无纹章清单"); return; } ToolCrest val = null; foreach (ToolCrest item in allCrests) { if ((Object)(object)item != (Object)null && !item.IsUnlocked) { val = item; break; } } if ((Object)(object)val == (Object)null) { val = allCrests[Random.Range(0, allCrests.Count)]; } if (!((Object)(object)val == (Object)null)) { Plugin.Log.LogInfo("[F4纹章] 随机发放纹章: " + val.name); SavedItemReward savedItemReward = new SavedItemReward((SavedItem)(object)val); savedItemReward.Give(); ItemRandomizer.AddGivenCount(savedItemReward.Id); ItemRandomizer.RecordMapping("test:F4crest", "reward:" + savedItemReward.Id); RecentItemsUI.AddItem(savedItemReward); } } catch (Exception arg) { Plugin.Log.LogError($"[F4纹章] 异常: {arg}"); } } private static void LoadSlotDependencyBundles() { if (_slotDepsLoaded) { return; } _slotDepsLoaded = true; try { string text = Path.Combine(Application.streamingAssetsPath, "aa", "StandaloneWindows64"); if (!Directory.Exists(text)) { Plugin.Log.LogWarning("[F4额外槽] Addressables 目录不存在: " + text); return; } int num = 0; int num2 = 0; int num3 = 0; string[] files = Directory.GetFiles(text, "*.bundle"); foreach (string text2 in files) { try { AssetBundle val = AssetBundle.LoadFromFile(text2); if ((Object)(object)val == (Object)null) { num2++; } else if (val.isStreamedSceneAssetBundle) { val.Unload(false); num3++; } else { num++; } } catch { num2++; } } Plugin.Log.LogInfo($"[F4额外槽] 依赖 bundle 全量加载: 成功{num} 场景跳过{num3} 失败{num2}"); } catch (Exception ex) { Plugin.Log.LogError("[F4额外槽] 依赖 bundle 加载异常: " + ex.Message); } } private void TestGiveExtraSlot() { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) try { PlayerData instance = PlayerData.instance; if (instance == null) { Plugin.Log.LogError("[F4额外槽] PlayerData 不可用"); return; } int num = _extraSlotTestIndex % 2; _extraSlotTestIndex++; string text = ((num == 0) ? "UnlockedExtraYellowSlot" : "UnlockedExtraBlueSlot"); ModLog log = Plugin.Log; object arg = _extraSlotTestIndex - 1; Scene activeScene = SceneManager.GetActiveScene(); log.LogInfo($"[F4额外槽] 触发: slot#{arg} field={text} scene={((Scene)(ref activeScene)).name}"); FieldInfo field = typeof(PlayerData).GetField(text, BindingFlags.Instance | BindingFlags.Public); if (field == null || field.FieldType != typeof(bool)) { Plugin.Log.LogError("[F4额外槽] 字段不存在: " + text); return; } field.SetValue(instance, true); Plugin.Log.LogInfo("[F4额外槽] 物品给予: " + text + " = true"); ToolItemType slotType = (ToolItemType)((num != 0) ? 1 : 2); ((MonoBehaviour)this).StartCoroutine(SpawnFullScreenSlotMsg(slotType)); } catch (Exception arg2) { Plugin.Log.LogError($"[F4额外槽] 异常: {arg2}"); } } private IEnumerator SpawnFullScreenSlotMsg(ToolItemType slotType) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) GameObject val = ChainFixer.LoadPrefabFixed("prompts_assets_all.bundle", "Assets/Prefabs/UI/Messages/UI Msg Crest Evolve.prefab", "F4额外槽evolve"); if ((Object)(object)val == (Object)null) { string text = (((int)slotType == 2) ? "Socket 0" : "Socket 1"); Plugin.ShowNotification("解锁 " + text + "!"); yield break; } GameObject val2 = Object.Instantiate<GameObject>(val); val2.SetActive(false); val2.transform.position = new Vector3(0f, 0f, 0f); PlayMakerFSM val3 = ((IEnumerable<PlayMakerFSM>)val2.GetComponentsInChildren<PlayMakerFSM>(true)).FirstOrDefault((Func<PlayMakerFSM, bool>)((PlayMakerFSM f) => f.FsmName == "Msg Control")); if ((Object)(object)val3 != (Object)null) { FsmString fsmString = val3.FsmVariables.GetFsmString("Item"); if (fsmString != null) { string text2 = (fsmString.Value = (((int)slotType == 2) ? "Socket 0" : "Socket 1")); Plugin.Log.LogInfo("[F4额外槽] FSM '" + val3.FsmName + "' 设 Item='" + text2 + "',激活后 Init→StringSwitch→" + (((int)slotType == 2) ? "SOCKET 1" : "SOCKET 2") + " 分支"); } else { Plugin.Log.LogWarning("[F4额外槽] FSM 无 Item 字符串变量"); } } else { Plugin.Log.LogWarning("[F4额外槽] 未找到 Msg Control FSM"); } Plugin.Log.LogInfo("[F4额外槽] 激活 evolve prefab,Msg Control FSM startState=Init 自动演出"); val2.SetActive(true); ((MonoBehaviour)this).StartCoroutine(DiagnoseBg(val2)); ((MonoBehaviour)this).StartCoroutine(HideEvolveVisualLater(val2, val3)); } private IEnumerator DiagnoseBg(GameObject evo) { yield return (object)new WaitForSeconds(0.5f); if ((Object)(object)evo == (Object)null) { yield break; } Transform val = evo.transform.Find("BG"); if ((Object)(object)val == (Object)null) { Plugin.Log.LogWarning("[F4额外槽] 未找到 BG 子物体"); yield break; } SpriteRenderer component = ((Component)val).GetComponent<SpriteRenderer>(); Animator component2 = ((Component)val).GetComponent<Animator>(); PlayMakerFSM component3 = ((Component)val).GetComponent<PlayMakerFSM>(); ModLog log = Plugin.Log; object[] obj = new object[5] { val.position, ((Component)val).gameObject.activeSelf, null, null, null }; object obj2; if (!((Object)(object)component != (Object)null)) { obj2 = "NULL"; } else { object[] array = new object[5]; Sprite sprite = component.sprite; array[0] = ((sprite != null) ? ((Object)sprite).name : null); array[1] = ((Renderer)component).enabled; array[2] = component.color; array[3] = ((Renderer)component).sortingLayerName; array[4] = ((Renderer)component).sortingOrder; obj2 = string.Format("sprite={0} enabled={1} color={2} sortingL={3} order={4}", array); } obj[2] = obj2; object obj3; if (!((Object)(object)component2 != (Object)null)) { obj3 = "NULL"; } else { RuntimeAnimatorController runtimeAnimatorController = component2.runtimeAnimatorController; obj3 = $"ctrl={((runtimeAnimatorController != null) ? ((Object)runtimeAnimatorController).name : null)} enabled={((Behaviour)component2).enabled}"; } obj[3] = obj3; obj[4] = (((Object)(object)component3 != (Object)null) ? (component3.FsmName + "/" + component3.ActiveStateName) : "NULL"); log.LogInfo(string.Format("[F4额外槽] BG pos={0} active={1} sr={2} anim={3} fsm={4}", obj)); Component[] components = ((Component)val).GetComponents<Component>(); foreach (Component val2 in components) { Plugin.Log.LogInfo("[F4额外槽] BG 组件: " + ((object)val2).GetType().Name); } } private IEnumerator HideEvolveVisualLater(GameObject evo, PlayMakerFSM controlFsm) { yield return (object)new WaitForSeconds(7.5f); if ((Object)(object)evo == (Object)null) { yield break; } Plugin.Log.LogInfo("[F4额外槽] 演出超时,发 PRESS 让 FSM 走完还原流程 (Detect→Down→Done)"); if ((Object)(object)controlFsm != (Object)null) { try { controlFsm.SendEvent("PRESS"); Plugin.Log.LogInfo("[F4额外槽] 已发 PRESS,当前状态: " + controlFsm.Fsm.ActiveStateName); } catch (Exception ex) { Plugin.Log.LogWarning("[F4额外槽] 发 PRESS 异常: " + ex.Message); } } float t = 0f; while (t < 3f && (Object)(object)evo != (Object)null) { t += Time.deltaTime; if ((Object)(object)controlFsm != (Object)null && controlFsm.Fsm.ActiveStateName == "Done") { Plugin.Log.LogInfo("[F4额外槽] FSM 已到 Done(还原完成)"); break; } yield return null; } RestoreMsgInputState(); if ((Object)(object)evo != (Object)null) { evo.SetActive(false); Object.Destroy((Object)(object)evo); Plugin.Log.LogInfo("[F4额外槽] evolve 视觉已回收"); } } private static void RestoreMsgInputState() { try { UIMsgProxy[] array = Object.FindObjectsOfType<UIMsgProxy>(true); UIMsgProxy[] array2 = array; foreach (UIMsgProxy val in array2) { val.SetIsInMsg(false); Plugin.Log.LogInfo("[F4额外槽] 兜底还原 UIMsgProxy '" + ((Object)val).name + "' SetIsInMsg(false)"); } if (array.Length == 0) { Plugin.Log.LogInfo("[F4额外槽] 未找到 UIMsgProxy,跳过兜底还原"); } try { PlayerData instance = PlayerData.instance; bool isInputBlocked = InventoryPaneInput.IsInputBlocked; bool isPickupPaused = CollectableItemPickup.IsPickupPaused; Plugin.Log.LogInfo($"[F4额外槽] 还原后状态: disablePause={instance.disablePause} IsInputBlocked={isInputBlocked} IsPickupPaused={isPickupPaused}"); } catch (Exception ex) { Plugin.Log.LogWarning("[F4额外槽] 还原后状态读取异常: " + ex.Message); } try { if (PlayerData.instance != null && PlayerData.instance.disablePause) { PlayerData.instance.disablePause = false; Plugin.Log.LogInfo("[F4额外槽] 强制还原 disablePause=false(FSM 未走完 SetIsInMsg 还原链)"); } } catch (Exception ex2) { Plugin.Log.LogWarning("[F4额外槽] 强制还原 disablePause 异常: " + ex2.Message); } } catch (Exception ex3) { Plugin.Log.LogWarning("[F4额外槽] 兜底还原异常: " + ex3.Message); } } private IEnumerator TraceSlotFsm(GameObject go, PlayMakerFSM controlFsm) { if ((Object)(object)go == (Object)null) { yield break; } string outputPath = Path.Combine(Paths.PluginPath, $"crest_evolve_trace_{DateTime.Now:HHmmssfff}.txt"); DumpGameObjectStructure(go, outputPath); Transform icon = ((IEnumerable<Transform>)go.GetComponentsInChildren<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform t) => ((Object)t).name == "Icon")); Transform obj = go.transform.Find("Tool_Socket_Evolve_lvl1"); Animator targetAnim = ((obj != null) ? ((Component)obj).GetComponent<Animator>() : null); string lastState = null; for (int frame = 1; frame <= 90; frame++) { yield return null; if ((Object)(object)go == (Object)null) { Plugin.Log.LogInfo("[F4额外槽] 弹窗已销毁"); break; } string text = (((Object)(object)controlFsm != (Object)null) ? (controlFsm.Fsm.ActiveStateName ?? "none") : "noCtrl"); string text2 = (((Object)(object)icon != (Object)null) ? ((Component)icon).gameObject.activeInHierarchy.ToString() : "noIcon"); string text3 = "noLvl1Anim"; if ((Object)(object)targetAnim != (Object)null) { AnimatorStateInfo currentAnimatorStateInfo = targetAnim.GetCurrentAnimatorStateInfo(0); string text4 = "noIcon"; if ((Object)(object)icon != (Object)null) { SpriteRenderer component = ((Component)icon).GetComponent<SpriteRenderer>(); text4 = (((Object)(object)component == (Object)null) ? "noSR" : (((Object)(object)component.sprite != (Object)null) ? ((Object)component.sprite).name : "nullSprite")); } text3 = $"animOn={((Behaviour)targetAnim).isActiveAndEnabled} normTime={((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime:F2} stateHash={((AnimatorStateInfo)(ref currentAnimatorStateInfo)).fullPathHash} clip={targetAnim.GetCurrentAnimatorClipInfo(0).Length} icon={text4}"; } string arg = "state=" + text + " icon=" + text2 + " | " + text3; if (text != lastState || frame <= 3 || frame % 10 == 0) { Plugin.Log.LogInfo($"[F4额外槽] 帧{frame}: {arg}"); lastState = text; } switch (text) { case "Finished": yield break; case "Stop": yield break; } } } private void TestDirectionSplitStep() { (string, bool)[] array = new(string, bool)[8] { ("hasDash", true), ("hasDash", false), ("hasHarpoonDash", true), ("hasHarpoonDash", false), ("hasBrolly", true), ("hasBrolly", false), ("hasWalljump", true), ("hasWalljump", false) }; int splitTestIndex = _splitTestIndex; _splitTestIndex = (_splitTestIndex + 1) % (array.Length + 1); if (splitTestIndex < array.Length) { (string, bool) tuple = array[splitTestIndex]; Plugin.Log.LogInfo("[分裂弹窗测试] 弹出 " + tuple.Item1 + " " + (tuple.Item2 ? "LEFT" : "RIGHT")); DirectionPopupHelper.ShowDirectionSplit(tuple.Item1, tuple.Item2, (Action)null); } else { Plugin.Log.LogInfo("[分裂弹窗测试] 弹出 回血"); Sprite val = SpriteCache.Find("prompt_silkheart"); UiMsgCustomBannerHelper.Show("Brolly", val, "Vincular", "缚丝", "enable heal", false, (Action)null); } } private void DumpGameObjectStructure(GameObject root, string outputPath) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)root == (Object)null) { return; } try { using (StreamWriter streamWriter = new StreamWriter(outputPath, append: false, Encoding.UTF8)) { streamWriter.WriteLine("=== GameObject 结构导出: " + ((Object)root).name + " ==="); streamWriter.WriteLine($"时间: {DateTime.Now:HH:mm:ss.fff}"); streamWriter.WriteLine($"Active Self: {root.activeSelf} Active In Hierarchy: {root.activeInHierarchy}"); Scene scene = root.scene; streamWriter.WriteLine("场景: " + ((Scene)(ref scene)).name); streamWriter.WriteLine("层: " + LayerMask.LayerToName(root.layer)); streamWriter.WriteLine(); DumpTransformRecursive(root.transform, streamWriter, 0); } Plugin.Log.LogInfo("[结构导出] 已保存到: " + outputPath); } catch (Exception arg) { Plugin.Log.LogError($"[结构导出] 失败: {arg}"); } } private void DumpTransformRecursive(Transform t, StreamWriter writer, int depth) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Expected O, but got Unknown string text = new string(' ', depth * 2); writer.WriteLine($"{text}[{depth}] ─ {((Object)t).name}"); writer.WriteLine($"{text} Position: {t.localPosition} Rotation: {t.localEulerAngles} Scale: {t.localScale}"); writer.WriteLine($"{text} Active Self: {((Component)t).gameObject.activeSelf} Active In Hierarchy: {((Component)t).gameObject.activeInHierarchy}"); writer.WriteLine(text + " Tag: " + ((Component)t).tag + " Layer: " + LayerMask.LayerToName(((Component)t).gameObject.layer)); Component[] components = ((Component)t).GetComponents<Component>(); writer.WriteLine($"{text} Components ({components.Length}):"); Component[] array = components; foreach (Component val in array) { if ((Object)(object)val == (Object)null) { writer.WriteLine(text + " - (missing)"); continue; } string fullName = ((object)val).GetType().FullName; writer.WriteLine(text + " - " + fullName); DumpComponentDetail(val, writer, text + " "); } foreach (Transform item in t) { Transform t2 = item; DumpTransformRecursive(t2, writer, depth + 1); } } private void DumpComponentDetail(Component comp, StreamWriter writer, string indent) { //IL_0466: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_05f4: Unknown result type (might be due to invalid IL or missing references) //IL_05f9: Unknown result type (might be due to invalid IL or missing references) //IL_05fd: Unknown result type (might be due to invalid IL or missing references) //IL_0602: Unknown result type (might be due to invalid IL or missing references) //IL_0612: Unknown result type (might be due to invalid IL or missing references) //IL_0617: Unknown result type (might be due to invalid IL or missing references) //IL_061b: Unknown result type (might be due to invalid IL or missing references) //IL_0620: Unknown result type (might be due to invalid IL or missing references) //IL_0641: Unknown result type (might be due to invalid IL or missing references) //IL_0646: Unknown result type (might be due to invalid IL or missing references) //IL_064a: Unknown result type (might be due to invalid IL or missing references) //IL_064f: Unknown result type (might be due to invalid IL or missing references) //IL_065f: Unknown result type (might be due to invalid IL or missing references) //IL_0664: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) try { Animator val = (Animator)(object)((comp is Animator) ? comp : null); if (val != null) { writer.WriteLine(indent + "Animator:"); writer.WriteLine(indent + " Controller: " + (((Object)(object)val.runtimeAnimatorController != (Object)null) ? ((Object)val.runtimeAnimatorController).name : "NULL")); writer.WriteLine(indent + " Avatar: " + (((Object)(object)val.avatar != (Object)null) ? ((Object)val.avatar).name : "NULL")); writer.WriteLine($"{indent} Root Motion: {val.applyRootMotion}"); writer.WriteLine($"{indent} Update Mode: {val.updateMode}"); writer.WriteLine($"{indent} Enabled: {((Behaviour)val).enabled}"); if ((Object)(object)val.runtimeAnimatorController != (Object)null) { int layerCount = val.layerCount; writer.WriteLine($"{indent} Layers: {layerCount}"); for (int i = 0; i < layerCount; i++) { writer.WriteLine($"{indent} Layer[{i}]: {val.GetLayerName(i)} weight={val.GetLayerWeight(i)}"); } AnimatorControllerParameter[] parameters = val.parameters; writer.WriteLine($"{indent} Parameters: {parameters.Length}"); AnimatorControllerParameter[] array = parameters; foreach (AnimatorControllerParameter val2 in array) { writer.WriteLine($"{indent} {val2.name} ({val2.type}) = {GetAnimatorParamValue(val, val2)}"); } } return; } SpriteRenderer val3 = (SpriteRenderer)(object)((comp is SpriteRenderer) ? comp : null); if (val3 != null) { writer.WriteLine(indent + "SpriteRenderer:"); writer.WriteLine(indent + " Sprite: " + (((Object)(object)val3.sprite != (Object)null) ? ((Object)val3.sprite).name : "NULL")); writer.WriteLine($"{indent} Color: {val3.color}"); writer.WriteLine(indent + " Material: " + (((Object)(object)((Renderer)val3).sharedMaterial != (Object)null) ? ((Object)((Renderer)val3).sharedMaterial).name : "NULL")); writer.WriteLine($"{indent} Sorting Layer: {((Renderer)val3).sortingLayerName} Order: {((Renderer)val3).sortingOrder}"); writer.WriteLine($"{indent} Flip X: {val3.flipX} Flip Y: {val3.flipY}"); return; } PlayMakerFSM val4 = (PlayMakerFSM)(object)((comp is PlayMakerFSM) ? comp : null); if (val4 != null) { writer.WriteLine(indent + "PlayMakerFSM:"); writer.WriteLine(indent + " FSM Name: " + val4.FsmName); writer.WriteLine(indent + " Active State: " + val4.ActiveStateName); writer.WriteLine(indent + " Start State: " + ((val4.Fsm != null) ? val4.Fsm.StartState : "NULL")); writer.WriteLine($"{indent} Enabled: {((Behaviour)val4).enabled}"); writer.WriteLine(indent + " Variables:"); if (val4.Fsm == null || val4.Fsm.Variables == null) { return; } FsmVariables variables = val4.Fsm.Variables; FieldInfo[] fields = ((object)variables).GetType().GetFields(BindingFlags.Instance | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.FieldType.Name.StartsWith("Fsm")) { object value = fieldInfo.GetValue(variables); if (value != null) { string fsmVariableValue = GetFsmVariableValue(value); writer.WriteLine(indent + " " + fieldInfo.Name + " (" + fieldInfo.FieldType.Name + ") = " + fsmVariableValue); } } } return; } Canvas val5 = (Canvas)(object)((comp is Canvas) ? comp : null); if (val5 != null) { writer.WriteLine(indent + "Canvas:"); writer.WriteLine($"{indent} Render Mode: {val5.renderMode}"); writer.WriteLine(indent + " World Camera: " + (((Object)(object)val5.worldCamera != (Object)null) ? ((Object)val5.worldCamera).name : "NULL")); writer.WriteLine($"{indent} Pixel Perfect: {val5.pixelPerfect}"); writer.WriteLine($"{indent} Sort Order: {val5.sortingOrder}"); writer.WriteLine($"{indent} Scale Factor: {val5.scaleFactor}"); return; } AudioSource val6 = (AudioSource)(object)((comp is AudioSource) ? comp : null); if (val6 != null) { writer.WriteLine(indent + "AudioSource:"); writer.WriteLine(indent + " Clip: " + (((Object)(object)val6.clip != (Object)null) ? ((Object)val6.clip).name : "NULL")); writer.WriteLine($"{indent} Loop: {val6.loop} Mute: {val6.mute}"); writer.WriteLine($"{indent} Volume: {val6.volume} Pitch: {val6.pitch}"); return; } ParticleSystem val7 = (ParticleSystem)(object)((comp is ParticleSystem) ? comp : null); if (val7 != null) { writer.WriteLine(indent + "ParticleSystem:"); writer.WriteLine($"{indent} Enabled: {val7.isPlaying}"); MainModule main = val7.main; MinMaxCurve val8 = ((MainModule)(ref main)).startLifetime; object arg = ((MinMaxCurve)(ref val8)).constant; main = val7.main; val8 = ((MainModule)(ref main)).startSpeed; writer.WriteLine($"{indent} Main: startLifetime={arg} startSpeed={((MinMaxCurve)(ref val8)).constant}"); EmissionModule emission = val7.emission; val8 = ((EmissionModule)(ref emission)).rateOverTime; object arg2 = ((MinMaxCurve)(ref val8)).constant; emission = val7.emission; writer.WriteLine($"{indent} Emission: rate={arg2} enabled={((EmissionModule)(ref emission)).enabled}"); } } catch (Exception ex) { writer.WriteLine(indent + " [组件详情输出异常: " + ex.Message + "]"); } } private string GetAnimatorParamValue(Animator anim, AnimatorControllerParameter p) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected I4, but got Unknown //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 try { AnimatorControllerParameterType type = p.type; switch (type - 1) { default: if ((int)type != 9) { break; } return "Trigger"; case 0: return anim.GetFloat(p.nameHash).ToString("F3"); case 2: return anim.GetInteger(p.nameHash).ToString(); case 3: return anim.GetBool(p.nameHash).ToString(); case 1: break; } return "?"; } catch { return "获取失败"; } } private string GetFsmVariableValue(object v) { if (v == null) { return "null"; } try { PropertyInfo property = v.GetType().GetProperty("Value"); if (property != null) { object value = property.GetValue(v); return (value != null) ? value.ToString() : "null"; } FieldInfo field = v.GetType().GetField("Value"); if (field != null) { object value2 = field.GetValue(v); return (value2 != null) ? value2.ToString() : "null"; } return v.ToString(); } catch { return "??"; } } private void TestGiveSkillsInOrder() { try { PlayerData instance = PlayerData.instance; if (instance == null) { Plugin.Log.LogError("[F4弹窗测试] PlayerData 为空"); return; } List<string> list = new List<string>(); try { List<ToolCrest> allCrests = ToolItemManager.GetAllCrests(); if (allCrests != null) { foreach (ToolCrest item in allCrests) { if ((Object)(object)item != (Object)null && !string.IsNullOrEmpty(item.name)) { list.Add(item.name); } } } } catch { } int num = _testSkillFields.Length + list.Count; if (num == 0) { Plugin.Log.LogError("[F4弹窗测试] 测试序列为空"); return; } int num2 = _f4SelfGiveIndex % num; _f4SelfGiveIndex++; if (num2 < _testSkillFields.Length) { string text = _testSkillFields[num2]; ResetPdBoolForTest(instance, text); if (text == "HasSeenEvaHeal") { ResetPdBoolForTest(instance, "HasBoundCrestUpgrader"); } Plugin.Log.LogInfo($"[F4弹窗测试] 技能 #{_f4SelfGiveIndex}/{num}: {text}"); StartingAbilityPickerAPI.GiveSkill(text, true); } else { string text2 = list[num2 - _testSkillFields.Length]; Plugin.Log.LogInfo($"[F4弹窗测试] 纹章 #{_f4SelfGiveIndex}/{num}: {text2}"); OfficialMsgHelper.ShowToolCrestByName(text2, (Action)null); } } catch (Exception arg) { Plugin.Log.LogError($"[F4弹窗测试] 异常: {arg}"); } } private static void ResetPdBoolForTest(PlayerData pd, string field) { try { FieldInfo field2 = typeof(PlayerData).GetField(field, BindingFlags.Instance | BindingFlags.Public); if (field2 != null && field2.FieldType == typeof(bool)) { field2.SetValue(pd, false); } } catch { } } private void TestShowCrestPopup() { try { List<ToolCrest> allCrests = ToolItemManager.GetAllCrests(); if (allCrests == null || allCrests.Count == 0) { Plugin.Log.LogError("[纹章弹窗] ToolItemManager 无纹章清单"); return; } ToolCrest obj = allCrests[_crestPopupIndex % allCrests.Count]; _crestPopupIndex++; OfficialMsgHelper.ShowToolCrest(obj, (Action)delegate { Plugin.Log.LogInfo("[纹章弹窗] 弹窗结束"); }); } catch (Exception arg) { Plugin.Log.LogError($"[纹章弹窗] 异常: {arg}"); } } private void TestGrantAllPermissions() { //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Expected O, but got Unknown try { Plugin.Log.LogInfo("[F4全部权限] ===== 授予前 GlobalConfig ====="); Plugin.Log.LogInfo($"[F4全部权限] 攻击: Up={GlobalConfig.AttackUp.Value}, Left={GlobalConfig.AttackLeft.Value}, Right={GlobalConfig.AttackRight.Value}"); Plugin.Log.LogInfo($"[F4全部权限] 冲刺: L={GlobalConfig.DashLeft.Value}, R={GlobalConfig.DashRight.Value} | 飞针: L={GlobalConfig.HarpoonLeft.Value}, R={GlobalConfig.HarpoonRight.Value}"); Plugin.Log.LogInfo($"[F4全部权限] 漂浮: L={GlobalConfig.FloatLeft.Value}, R={GlobalConfig.FloatRight.Value} | 壁跳: L={GlobalConfig.WallJumpLeft.Value}, R={GlobalConfig.WallJumpRight.Value}"); Plugin.Log.LogInfo($"[F4全部权限] 回血: Heal={GlobalConfig.Heal.Value}"); StartingAbilityPickerAPI.SetAttackPermissions(true, true, true); StartingAbilityPickerAPI.SetMovementPermissions(new DirectionPermissions { DashLeft = true, DashRight = true, HarpoonLeft = true, HarpoonRight = true, FloatLeft = true, FloatRight = true, WallJumpLeft = true, WallJumpRight = true, AllowHeal = true }); Plugin.Log.LogInfo("[F4全部权限] ===== 授予后 GlobalConfig ====="); Plugin.Log.LogInfo($"[F4全部权限] 攻击: Up={GlobalConfig.AttackUp.Value}, Left={GlobalConfig.AttackLeft.Value}, Right={GlobalConfig.AttackRight.Value}"); Plugin.Log.LogInfo($"[F4全部权限] 冲刺: L={GlobalConfig.DashLeft.Value}, R={GlobalConfig.DashRight.Value} | 飞针: L={GlobalConfig.HarpoonLeft.Value}, R={GlobalConfig.HarpoonRight.Value}"); Plugin.Log.LogInfo($"[F4全部权限] 漂浮: L={GlobalConfig.FloatLeft.Value}, R={GlobalConfig.FloatRight.Value} | 壁跳: L={GlobalConfig.WallJumpLeft.Value}, R={GlobalConfig.WallJumpRight.Value}"); Plugin.Log.LogInfo($"[F4全部权限] 回血: Heal={GlobalConfig.Heal.Value}"); (bool, bool, bool) attackPermissions = StartingAbilityPickerAPI.GetAttackPermissions(); DirectionPermissions movementPermissions = StartingAbilityPickerAPI.GetMovementPermissions(); Plugin.Log.LogInfo($"[F4全部权限] 运行时攻击: Up={attackPermissions.Item1}, Left={attackPermissions.Item2}, Right={attackPermissions.Item3}"); Plugin.Log.LogInfo($"[F4全部权限] 运行时移动: 冲刺L={movementPermissions.DashLeft},R={movementPermissions.DashRight} 飞针L={movementPermissions.HarpoonLeft},R={movementPermissions.HarpoonRight} " + $"漂浮L={movementPermissions.FloatLeft},R={movementPermissions.FloatRight} 壁跳L={movementPermissions.WallJumpLeft},R={movementPermissions.WallJumpRight} 回血={movementPermissions.AllowHeal}"); Plugin.ShowNotification("已授予全部权限"); } catch (Exception arg) { Plugin.Log.LogError($"[F4全部权限] 异常: {arg}"); } } private void TestNextDirectionPermission() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown try { var (text, text2, flag, flag2) = DirectionCalibList[_dirCalibIndex % DirectionCalibList.Length]; _dirCalibIndex++; DirectionPermissions val = new DirectionPermissions(); switch (text2) { case "hasDash": val.DashLeft = flag2; val.DashRight = flag; break; case "hasHarpoonDash": val.HarpoonLeft = flag2; val.HarpoonRight = flag; break; case "hasBrolly": val.FloatLeft = flag2; val.FloatRight = flag; break; case "hasWalljump": val.WallJumpLeft = flag2; val.WallJumpRight = flag; break; } StartingAbilityPickerAPI.SetMovementPermissions(val); StartingAbilityPickerAPI.GiveSkill(text2, true); Plugin.ShowNotification(Locale.Get(text)); Plugin.Log.LogInfo($"[F10方向校准] 已只开 {text}(skill={text2}, right={flag}, left={flag2}),请实测实际移动方向"); } catch (Exception arg) { Plugin.Log.LogError($"[F10方向校准] 异常: {arg}"); } } private void TestUnlockEvaHeal() { //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) PlayerData instance = PlayerData.instance; if (instance == null) { Plugin.Log.LogError("PlayerData 不可用"); return; } instance.HasSeenEvaHeal = true; instance.HasBoundCrestUpgrader = true; instance.CrestUpgraderOfferedFinal = true; instance.CrestPreUpgradeTalked = true; instance.CrestTalkedPurpose = true; instance.CrestUpgraderTalkedSnare = true; instance.CrestTalkedPurpose = true; instance.CrestUpgraderTalkedSnare = true; instance.chapelClosed_reaper = true; instance.chapelClosed_wanderer = true; instance.chapelClosed_beast = true; instance.chapelClosed_witch = true; instance.chapelClosed_toolmaster = true; instance.chapelClosed_shaman = true; instance.completedMemory_reaper = true; instance.completedMemory_wanderer = true; instance.completedMemory_beast = true; instance.completedMemory_witch = true; instance.completedMemory_toolmaster = true; instance.completedMemory_shaman = true; string[] array = new string[3] { "EvaHeal", "Sylphsong", "Slythsong" }; foreach (string text in array) { try { Data data = ((SerializableNamedList<Data, NamedData>)(object)instance.Tools).GetData(text); data.IsUnlocked = true; data.AmountLeft = 1; ((SerializableNamedList<Data, NamedData>)(object)instance.Tools).SetData(text, data); } catch { } } try { Data data2 = ((SerializableNamedList<Data, NamedData>)(object)instance.Collectables).GetData("EvaHeal"); data2.Amount = 1; ((SerializableNamedList<Data, NamedData>)(object)instance.Collectables).SetData("EvaHeal", data2); } catch { } try { MethodInfo methodInfo = Type.GetType("AutoSaveManager, Assembly-CSharp")?.GetMethod("Save", new Type[1] { typeof(Enum) }); FieldInfo fieldInfo = Type.GetType("AutoSaveName, Assembly-CSharp")?.GetField("GAINED_SLYTHSONG"); if (methodInfo != null && fieldInfo != null) { methodInfo.Invoke(null, new object[1] { fieldInfo.GetValue(null) }); } } catch { } try { Type type = Type.GetType("InventoryCollectableItemSelectionHelper, Assembly-CSharp"); if (type != null) { PropertyInfo property = type.GetProperty("LastSelectionUpdate", BindingFlags.Static | BindingFlags.Public); if (property != null) { Type nestedType = type.GetNestedType("SelectionType"); if (nestedType != null) { object value = Enum.Parse(nestedType, "EvaHeal"); property.SetValue(null, value); } } } } catch { } try { HeroController instance2 = HeroController.instance; if ((Object)(object)instance2 != (Object)null) { instance2.AddSilk(1, true); } } catch { } } private void TestLoreDialogue() { LoreRandomizer.LoreEntry[] loreTable = LoreRandomizer.LoreTable; if (loreTable.Length != 0) { _loreTestIndex = (_loreTestIndex + 1) % loreTable.Length; LoreRandomizer.LoreEntry loreEntry = loreTable[_loreTestIndex]; LoreRandomizer.ShowLoreDialogue(loreEntry.Key, loreEntry.Sheet); } } private void PickCurrent(bool pick) { List<(string, string)> list = ((_currentCandidates.Count > 0) ? _currentCandidates : SpritePickCandidates.ToList()); if (_pickerIndex < list.Count) { if (pick) { _pickedNames.Add(list[_pickerIndex].Item2); } _pickerIndex++; if (_pickerIndex >= list.Count) { FinishPicker(); } } } private IEnumerator LoadAtlasesThenStartFleaPicker() { if (_isDumpingSprites) { yield break; } _isDumpingSprites = true; List<string> list = new List<string>(); try { foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text && !string.IsNullOrEmpty(text)) { list.Add(text); } } } } catch { } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); (string, string[])[] spriteSearchGroups = SpriteSearchGroups; for (int i = 0; i < spriteSearchGroups.Length; i++) { (string, string[]) tuple = spriteSearchGroups[i]; foreach (string item2 in list) { if (!IsLikelyAtlasKey(item2)) { continue; } bool flag = false; string[] item = tuple.Item2; foreach (string value in item) { if (item2.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { flag = true; break; } } if (flag) { hashSet.Add(item2); } } } int loadedOk = 0; int loadedFail = 0; foreach (string item3 in hashSet) { AsyncOperationHandle<Object> handle; try { handle = Addressables.LoadAssetAsync<Object>((object)item3); } catch { loadedFail++; continue; } float deadline = Time.realtimeSinceStartup + 20f; while (!handle.IsDone && Time.realtimeSinceStartup <= deadline) { yield return null; } if (handle.IsDone && (int)handle.Status == 1) { loadedOk++; continue; } loadedFail++; try { if (handle.IsValid()) { Addressables.Release<Object>(handle); } } catch { } } SpriteCache.Reset(); SpriteCache.EnsureBuilt(); _currentCandidates.Clear(); Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>(); foreach (Sprite val in array) { if (!((Object)(object)val == (Object)null)) { string name = ((Object)val).name; if (!string.IsNullOrEmpty(name) && name.IndexOf("flea", StringComparison.OrdinalIgnoreCase) >= 0) { _currentCandidates.Add(("flea", name)); } } } if (_currentCandidates.Count == 0) { Plugin.Log.LogInfo("[F4] 未找到任何包含 'flea' 的贴图。"); _isDumpingSprites = false; yield break; } _pickerActive = true; _pickerIndex = 0; _pickedNames.Clear(); Plugin.Log.LogInfo($"[F4] 找到 {_currentCandidates.Count} 个 flea 图标,开始筛选。"); _isDumpingSprites = false; } private static string NormalizeSpriteName(string s) { if (string.IsNullOrEmpty(s)) { return s ?? ""; } StringBuilder stringBuilder = new StringBuilder(s.Length); foreach (char c in s) { if (c != '-' && c != '_' && c != ' ') { stringBuilder.Append(char.ToLowerInvariant(c)); } } return stringBuilder.ToString(); } private IEnumerator LoadAtlasesThenStartPromptPicker() { if (_isDumpingSprites) { yield break; } _isDumpingSprites = true; List<string> list = new List<string>(); try { foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text && !string.IsNullOrEmpty(text)) { list.Add(text); } } } } catch { } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string item in list) { if (IsLikelyAtlasKey(item)) { hashSet.Add(item); } } int loadedOk = 0; int loadedFail = 0; foreach (string item2 in hashSet) { AsyncOperationHandle<Object> handle; try { handle = Addressables.LoadAssetAsync<Object>((object)item2); } catch { loadedFail++; continue; } float deadline = Time.realtimeSinceStartup + 20f; while (!handle.IsDone && Time.realtimeSinceStartup <= deadline) { yield return null; } if (handle.IsDone && (int)handle.Status == 1) { loadedOk++; continue; } loadedFail++; try { if (handle.IsValid()) { Addressables.Release<Object>(handle); } } catch { } } SpriteCache.Reset(); SpriteCache.EnsureBuilt(); _currentCandidates.Clear(); Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>(); List<string> list2 = new List<string>(); List<string> list3 = new List<string>(); List<string> list4 = new List<string>(); List<string> list5 = new List<string>(); List<string> list6 = new List<string>(); List<string> list7 = new List<string>(); Sprite[] array2 = array; foreach (Sprite val in array2) { if ((Object)(object)val == (Object)null) { continue; } string name = ((Object)val).name; if (string.IsNullOrEmpty(name)) { continue; } string text2 = NormalizeSpriteName(name); if (text2.Contains("flower")) { if (text2.Contains("prompt")) { list2.Add(name); } else { list3.Add(name); } } if (text2.Contains("far") && text2.Contains("sight")) { if (text2.Contains("prompt")) { list4.Add(name); } else { list5.Add(name); } } if (text2.Contains("completion")) { if (text2.Contains("prompt")) { list6.Add(name); } else { list7.Add(name); } } } foreach (string item3 in list2) { _currentCandidates.Add(("花+prompt", item3)); } if (list2.Count == 0) { foreach (string item4 in list3) { _currentCandidates.Add(("花", item4)); } } foreach (string item5 in list4) { _currentCandidates.Add(("遥观仪+prompt", item5)); } if (list4.Count == 0) { foreach (string item6 in list5) { _currentCandidates.Add(("遥观仪", item6)); } } foreach (string item7 in list6) { _currentCandidates.Add(("completion+prompt", item7)); } if (list6.Count == 0) { foreach (string item8 in list7) { _currentCandidates.Add(("completion", item8)); } } Plugin.Log.LogInfo($"[F4] 花: prompt命中{list2.Count} / 回退{list3.Count}," + $"遥观仪(far+sight): prompt命中{list4.Count} / 回退{list5.Count}," + $"completion: prompt命中{list6.Count} / 回退{list7.Count}"); if (_currentCandidates.Count == 0) { Plugin.Log.LogInfo("[F4] 未找到任何含 whiteflower / farsight 的贴图。"); _isDumpingSprites = false; yield break; } _pickerActive = true; _pickerIndex = 0; _pickedNames.Clear(); Plugin.Log.LogInfo($"[F4] 找到 {_currentCandidates.Count} 个目标图标,开始筛选。"); _isDumpingSprites = false; } private void FinishPicker() { _pickerActive = false; using (StreamWriter streamWriter = new StreamWriter(Path.Combine(Paths.PluginPath, "sprite_picked.txt"), append: false)) { foreach (string pickedName in _pickedNames) { streamWriter.WriteLine(pickedName); } } StartAnnotate(_pickedNames); } private void StartAnnotate(List<string> names) { _annotateList = names.Distinct<string>(StringComparer.OrdinalIgnoreCase).ToList(); if (_annotateList.Count != 0) { _annotated.Clear(); _annotateIndex = 0; _noteText = ""; _annotateActive = true; } } private void StartAnnotateFromFile() { string path = Path.Combine(Paths.PluginPath, "sprite_picked.txt"); if (File.Exists(path)) { List<string> names = (from l in File.ReadAllLines(path) select l.Trim() into l where l.Length > 0 select l).ToList(); StartAnnotate(names); } } private void SaveCurrentNote() { if (_annotateIndex < _annotateList.Count) { _annotated.Add((_annotateList[_annotateIndex], _noteText.Trim())); _annotateIndex++; _noteText = ""; if (_annotateIndex >= _annotateList.Count) { FinishAnnotate(); } } } private void FinishAnnotate() { _annotateActive = false; using StreamWriter streamWriter = new StreamWriter(Path.Combine(Paths.PluginPath, "sprite_annotated.txt"), append: false); streamWriter.WriteLine("#sprite_name|用途备注"); foreach (var (text, text2) in _annotated) { streamWriter.WriteLine(text + "|" + text2); } } private IEnumerator DumpSpriteIconsCoroutine() { if (!_isDumpingSprites) { _isDumpingSprites = true; yield return ((MonoBehaviour)this).StartCoroutine(LoadAtlasesThenStartPicker()); _isDumpingSprites = false; } } private IEnumerator LoadAtlasesThenStartPicker() { List<string> list = new List<string>(); try { foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text && !string.IsNullOrEmpty(text)) { list.Add(text); } } } } catch { } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); (string, string[])[] spriteSearchGroups = SpriteSearchGroups; for (int i = 0; i < spriteSearchGroups.Length; i++) { (string, string[]) tuple = spriteSearchGroups[i]; foreach (string item2 in list) { if (!IsLikelyAtlasKey(item2)) { continue; } bool flag = false; string[] item = tuple.Item2; foreach (string value in item) { if (item2.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { flag = true; break; } } if (flag) { hashSet.Add(item2); } } } int loadedOk = 0; int loadedFail = 0; foreach (string item3 in hashSet) { AsyncOperationHandle<Object> handle; try { handle = Addressables.LoadAssetAsync<Object>((object)item3); } catch { loadedFail++; continue; } float deadline = Time.realtimeSinceStartup + 20f; while (!handle.IsDone && Time.realtimeSinceStartup <= deadline) { yield return null; } if (handle.IsDone && (int)handle.Status == 1) { loadedOk++; continue; } loadedFail++; try { if (handle.IsValid()) { Addressables.Release<Object>(handle); } } catch { } } SpriteCache.Reset(); SpriteCache.EnsureBuilt(); if (File.Exists(Path.Combine(Paths.PluginPath, "sprite_picked.txt"))) { StartAnnotateFromFile(); yield break; } _pickerActive = true; _pickerIndex = 0; _pickedNames.Clear(); } private static bool IsLikelyAtlasKey(string key) { if (key.IndexOf(".spriteatlas", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (key.IndexOf(".bundle", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (key.IndexOf("sprites/", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } return false; } private IEnumerator ExportSteelModeIconCoroutine() { _isDumpingSprites = true; try { SpriteCache.EnsureBuilt(); Sprite val = SpriteCache.Find("mode_select_Steel_Soul_HUD"); if ((Object)(object)val == (Object)null) { List<string> list = new List<string>(); try { foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text && !string.IsNullOrEmpty(text) && IsLikelyAtlasKey(text)) { string text2 = text.ToLowerInvariant(); if (text2.Contains("area_art") || text2.Contains("mode_select") || text2.Contains("steel")) { list.Add(text); } } } } } catch { } foreach (string item in list) { AsyncOperationHandle<Object> handle; try { handle = Addressables.LoadAssetAsync<Object>((object)item); } catch { continue; } float deadline = Time.realtimeSinceStartup + 20f; while (!handle.IsDone && Time.realtimeSinceStartup <= deadline) { yield return null; } if (handle.IsDone && (int)handle.Status == 1) { continue; } try { if (handle.IsValid()) { Addressables.Release<Object>(handle); } } catch { } } SpriteCache.Reset(); SpriteCache.EnsureBuilt(); val = SpriteCache.Find("mode_select_Steel_Soul_HUD"); } if (!((Object)(object)val == (Object)null)) { string outPath = Path.Combine(Paths.PluginPath, "steel_mode_icon.png"); ExportSpriteToPng(val, outPath); } } finally { _isDumpingSprites = false; } } private static void ExportSpriteToPng(Sprite s, string outPath) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)s == (Object)null) { return; } Texture2D texture = s.texture; if ((Object)(object)texture == (Object)null) { return; } Rect textureRect = s.textureRect; int num = Mathf.FloorToInt(((Rect)(ref textureRect)).x); int num2 = Mathf.FloorToInt(((Rect)(ref textureRect)).y); int num3 = Mathf.CeilToInt(((Rect)(ref textureRect)).width); int num4 = Mathf.CeilToInt(((Rect)(ref textureRect)).height); Texture2D val = null; RenderTexture val2 = null; RenderTexture val3 = null; try { val2 = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0); Graphics.Blit((Texture)(object)texture, val2); val3 = RenderTexture.active; RenderTexture.active = val2; val = new Texture2D(num3, num4, (TextureFormat)4, false); val.ReadPixels(new Rect((float)num, (float)num2, (float)num3, (float)num4), 0, 0); val.Apply(); RenderTexture.active = val3; val3 = null; RenderTexture.ReleaseTemporary(val2); val2 = null; byte[] bytes = ImageConversion.EncodeToPNG(val); File.WriteAllBytes(outPath, bytes); } catch (Exception ex) { Plugin.Log.LogError("[sprite搜索] 裁剪失败: " + ex.Message); } finally { if ((Object)(object)RenderTexture.active != (Object)(object)val3 && (Object)(object)val3 != (Object)null) { RenderTexture.active = val3; } if ((Object)(object)val2 != (Object)null) { RenderTexture.ReleaseTemporary(val2); } if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } } } private static bool IsDumpSkipped(string sceneName) { string[] dumpSkipSubstrings = DumpSkipSubstrings; foreach (string value in dumpSkipSubstrings) { if (sceneName.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } return false; } private void DumpCheckPoints() { if (!IsScanningChecks && !_isDumpingTransitions) { ((MonoBehaviour)this).StartCoroutine(DumpCheckPointsCoroutine()); } } private IEnumerator DumpCheckPointsCoroutine() { IsScanningChecks = true; ThreadPriority oldLoadPriority = Application.backgroundLoadingPriority; Application.backgroundLoadingPriority = (ThreadPriority)4; FieldInfo suppressField = Type.GetType("HKSilksong_Randomizer.RandomSceneLoader, HKSilksong_SceneRandomizer")?.GetField("SuppressSceneEvents", BindingFlags.Static | BindingFlags.Public); suppressField?.SetValue(null, true); try { List<string> list = new List<string>(); try { int sceneCountInBuildSettings = SceneManager.sceneCountInBuildSettings; for (int i = 0; i < sceneCountInBuildSettings; i++) { string scenePathByBuildIndex = SceneUtility.GetScenePathByBuildIndex(i); if (!string.IsNullOrEmpty(scenePathByBuildIndex)) { list.Add(Path.GetFileNameWithoutExtension(scenePathByBuildIndex)); } } } catch { } if (list.Count < 10) { list.Clear(); try { HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text && text.StartsWith("Scenes/", StringComparison.OrdinalIgnoreCase) && hashSet.Add(text)) { list.Add(text.Substring("Scenes/".Length)); } } } } catch { } } if (list.Count == 0) { Plugin.Log.LogError("[扫描] 无法枚举场景清单(Build Settings 与 Addressables 均为空)"); yield break; } string path = Path.Combine(Paths.PluginPath, "check_points_scan.txt"); int sceneCount = 0; int pointCount = 0; int failed = 0; int excluded = 0; using StreamWriter writer = new StreamWriter(path, append: false); writer.WriteLine("#type|scene|path|name|detail|key|x|y"); writer.Flush(); foreach (string sceneName in list) { if (IsDumpSkipped(sceneName)) { excluded++; continue; } Scene scene = SceneManager.GetSceneByName(sceneName); bool weLoaded = false; bool viaAddr = false; AsyncOperationHandle<SceneInstance> addr = default(AsyncOperationHandle<SceneInstance>); if (!((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded) { AsyncOperation op = null; try { op = SceneManager.LoadSceneAsync(sceneName, (LoadSceneMode)1); } catch { } if (op != null) { float deadline = Time.realtimeSinceStartup + 30f; while (!op.isDone && Time.realtimeSinceStartup <= deadline) { yield return null; } if (op.isDone) { scene = SceneManager.GetSceneByName(sceneName); if (((Scene)(ref scene)).IsValid() && ((Scene)(ref scene)).isLoaded) { weLoaded = true; } } } if (!weLoaded) { bool flag = false; try { addr = Addressables.LoadSceneAsync((object)("Scenes/" + sceneName), (LoadSceneMode)1, true, 100, (SceneReleaseMode)0); flag = true; } catch { } if (flag) { float deadline = Time.realtimeSinceStartup + 30f; while (!addr.IsDone && Time.realtimeSinceStartup <= deadline) { yield return null; } if (addr.IsDone && (int)addr.Status == 1) { SceneInstance result = addr.Result; scene = ((SceneInstance)(ref result)).Scene; weLoaded = true; viaAddr = true; } else { try { if (addr.IsValid()) { Addressables.Release<SceneInstance>(addr); } } catch { } } } } if (!weLoaded) { failed++; yield return null; continue; } } ResetSpawnedShopSingleton(); try { int num = ScanSceneCheckPoints(scene, sceneName, writer); pointCount += num; sceneCount++; } catch { failed++; } if (weLoaded) { try { if (viaAddr) { Addressables.UnloadSceneAsync(addr, true); } else if (((Scene)(ref scene)).IsValid() && ((Scene)(ref scene)).isLoaded) { SceneManager.UnloadSceneAsync(scene); } } catch { } } writer.Flush(); yield return null; } } finally { Application.backgroundLoadingPriority = oldLoadPriority; suppressField?.SetValue(null, false); IsScanningChecks = false; } } private static int ScanSceneCheckPoints(Scene scene, string sceneName, StreamWriter writer) { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Invalid comparison between Unknown and I4 //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_0352: Unknown result type (might be due to invalid IL or missing references) //IL_0357: Unknown result type (might be due to invalid IL or missing references) //IL_0393: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Unknown result type (might be due to invalid IL or missing references) //IL_042a: Unknown result type (might be due to invalid IL or missing references) //IL_042f: Unknown result type (might be due to invalid IL or missing references) //IL_046b: Unknown result type (might be due to invalid IL or missing references) //IL_047a: Unknown result type (might be due to invalid IL or missing references) //IL_0502: Unknown result type (might be due to invalid IL or missing references) //IL_0507: Unknown result type (might be due to invalid IL or missing references) //IL_0543: Unknown result type (might be due to invalid IL or missing references) //IL_0552: Unknown result type (might be due to invalid IL or missing references) //IL_05da: Unknown result type (might be due to invalid IL or missing references) //IL_05df: Unknown result type (might be due to invalid IL or missing references) //IL_061b: Unknown result type (might be due to invalid IL or missing references) //IL_062a: Unknown result type (might be due to invalid IL or missing references) //IL_06b2: Unknown result type (might be due to invalid IL or missing references) //IL_06b7: Unknown result type (might be due to invalid IL or missing references) //IL_06f3: Unknown result type (might be due to invalid IL or missing references) //IL_0702: Unknown result type (might be due to invalid IL or missing references) int num = 0; string boolName; string text = (MapStationUnlockPatch.TryGetStationBoolForScene(sceneName, out boolName) ? ("station:" + boolName) : ""); GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects(); foreach (GameObject val in rootGameObjects) { CollectableItemPickup[] componentsInChildren = val.GetComponentsInChildren<CollectableItemPickup>(true); foreach (CollectableItemPickup val2 in componentsInChildren) { if ((Object)(object)val2 == (Object)null) { continue; } string text2; try { text2 = PickupPatch.GetPickupKey(val2); } catch { text2 = sceneName + "_" + ((Object)((Component)val2).gameObject).name; } string text3 = ""; try { if ((Object)(object)val2.Item != (Object)null) { text3 = ((Object)val2.Item).name; } } catch { } Vector3 position = ((Component)val2).transform.position; writer.WriteLine($"Pickup|{sceneName}|{GetObjectPath(((Component)val2).transform)}|{((Object)((Component)val2).gameObject).name}|{text3}|{text2}|{position.x:F1}|{position.y:F1}"); num++; } NPCControlBase[] componentsInChildren2 = val.GetComponentsInChildren<NPCControlBase>(true); foreach (NPCControlBase val3 in componentsInChildren2) { if ((Object)(object)val3 == (Object)null) { continue; } string name = ((Object)((Component)val3).gameObject).name; Vector3 position2 = ((Component)val3).transform.position; if (LoreTriggerPatch.IsExcludedTollName(name)) { writer.WriteLine($"Toll|{sceneName}|{GetObjectPath(((Component)val3).transform)}|{name}|{text}||{position2.x:F1}|{position2.y:F1}"); num++; continue; } bool flag = false; try { flag = (int)((InteractableBase)val3).InteractLabel == 0; } catch { } if (flag) { string text4 = "loretrig:" + sceneName + ":" + name; writer.WriteLine($"Lore|{sceneName}|{GetObjectPath(((Component)val3).transform)}|{name}||{text4}|{position2.x:F1}|{position2.y:F1}"); num++; } } BellBench[] componentsInChildren3 = val.GetComponentsInChildren<BellBench>(true); foreach (BellBench val4 in componentsInChildren3) { if (!((Object)(object)val4 == (Object)null)) { Vector3 position3 = ((Component)val4).transform.position; writer.WriteLine($"BellBench|{sceneName}|{GetObjectPath(((Component)val4).transform)}|{((Object)((Component)val4).gameObject).name}|{text}||{position3.x:F1}|{position3.y:F1}"); num++; } } ShopOwner[] componentsInChildren4 = val.GetComponentsInChildren<ShopOwner>(true); foreach (ShopOwner val5 in componentsInChildren4) { if (!((Object)(object)val5 == (Object)null)) { for (int k = 0; k < 12; k++) { string text5 = $"shop:{sceneName}_{k}"; Vector3 position4 = ((Component)val5).transform.position; writer.WriteLine($"ShopSlot|{sceneName}|{GetObjectPath(((Component)val5).transform)}|ShopSlot_{k}|Slot {k}|{text5}|{position4.x:F1}|{position4.y:F1}"); num++; } } } SimpleShopMenuOwner[] componentsInChildren5 = val.GetComponentsInChildren<SimpleShopMenuOwner>(true); foreach (SimpleShopMenuOwner val6 in componentsInChildren5) { if (!((Object)(object)val6 == (Object)null)) { for (int l = 0; l < 12; l++) { string text6 = $"shop:{sceneName}_{l}"; Vector3 position5 = ((Component)val6).transform.position; writer.WriteLine($"ShopSlot|{sceneName}|{GetObjectPath(((Component)val6).transform)}|ShopSlot_{l}|Slot {l}|{text6}|{position5.x:F1}|{position5.y:F1}"); num++; } } } CaravanSpider[] componentsInChildren6 = val.GetComponentsInChildren<CaravanSpider>(true); foreach (CaravanSpider val7 in componentsInChildren6) { if (!((Object)(object)val7 == (Object)null)) { for (int m = 0; m < 12; m++) { string text7 = $"shop:{sceneName}_{m}"; Vector3 position6 = ((Component)val7).transform.position; writer.WriteLine($"ShopSlot|{sceneName}|{GetObjectPath(((Component)val7).transform)}|ShopSlot_{m}|Slot {m}|{text7}|{position6.x:F1}|{position6.y:F1}"); num++; } } } CaravanTroupeHunter[] componentsInChildren7 = val.GetComponentsInChildren<CaravanTroupeHunter>(true); foreach (CaravanTroupeHunter val8 in componentsInChildren7) { if (!((Object)(object)val8 == (Object)null)) { for (int n = 0; n < 12; n++) { string text8 = $"shop:{sceneName}_{n}"; Vector3 position7 = ((Component)val8).transform.position; writer.WriteLine($"ShopSlot|{sceneName}|{GetObjectPath(((Component)val8).transform)}|ShopSlot_{n}|Slot {n}|{text8}|{position7.x:F1}|{position7.y:F1}"); num++; } } } SimpleQuestsShopOwner[] componentsInChildren8 = val.GetComponentsInChildren<SimpleQuestsShopOwner>(true); foreach (SimpleQuestsShopOwner val9 in componentsInChildren8) { if (!((Object)(object)val9 == (Object)null)) { for (int num2 = 0; num2 < 12; num2++) { string text9 = $"shop:{sceneName}_{num2}"; Vector3 position8 = ((Component)val9).transform.position; writer.WriteLine($"ShopSlot|{sceneName}|{GetObjectPath(((Component)val9).transform)}|ShopSlot_{num2}|Slot {num2}|{text9}|{position8.x:F1}|{position8.y:F1}"); num++; } } } } return num; } private static void ResetSpawnedShopSingleton() { ShakraMerchantKeeper.ResetSpawnedShopSingleton(); } private static string GetObjectPath(Transform t) { StringBuilder stringBuilder = new StringBuilder(((Object)t).name); while ((Object)(object)t.parent != (Object)null) { t = t.parent; stringBuilder.Insert(0, ((Object)t).name + "/"); } return stringBuilder.ToString(); } private void DumpVanillaTransitions() { if (!_isDumpingTransitions) { ((MonoBehaviour)this).StartCoroutine(DumpVanillaTransitionsCoroutine()); } } private IEnumerator DumpVanillaTransitionsCoroutine() { _isDumpingTransitions = true; ThreadPriority oldLoadPriority = Application.backgroundLoadingPriority; Application.backgroundLoadingPriority = (ThreadPriority)4; FieldInfo suppressField = Type.GetType("HKSilksong_Randomizer.RandomSceneLoader, HKSilksong_SceneRandomizer")?.GetField("SuppressSceneEvents", BindingFlags.Static | BindingFlags.Public); suppressField?.SetValue(null, true); try { List<string> sceneNames = new List<string>(); string text = "Build Settings"; try { int sceneCountInBuildSettings = SceneManager.sceneCountInBuildSettings; for (int i = 0; i < sceneCountInBuildSettings; i++) { string scenePathByBuildIndex = SceneUtility.GetScenePathByBuildIndex(i); if (!string.IsNullOrEmpty(scenePathByBuildIndex)) { sceneNames.Add(Path.GetFileNameWithoutExtension(scenePathByBuildIndex)); } } } catch { } if (sceneNames.Count < 10) { sceneNames.Clear(); text = "Addressables"; try { HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (IResourceLocator resourceLocator in Addressables.ResourceLocators) { foreach (object key in resourceLocator.Keys) { if (key is string text2 && text2.StartsWith("Scenes/", StringComparison.OrdinalIgnoreCase) && hashSet.Add(text2)) { sceneNames.Add(text2.Substring("Scenes/".Length)); } } } } catch { } } if (sceneNames.Count == 0) { Plugin.Log.LogError("[Dump] 无法枚举场景清单(Build Settings 与 Addressables 均为空)"); yield break; } bool viaAddrList = text == "Addressables"; string path = Path.Combine(Paths.PluginPath, "vanilla_transitions.txt"); HashSet<string> seenPairs = new HashSet<string>(StringComparer.OrdinalIgnoreCase); int sceneCount = 0; int pairCount = 0; int skipped = 0; int excluded = 0; using StreamWriter writer = new StreamWriter(path, append: false); writer.WriteLine("#sceneA|gateA|sceneB|gateB"); for (int batchStart = 0; batchStart < sceneNames.Count; batchStart += 10) { int num = Math.Min(10, sceneNames.Count - batchStart); List<(string name, Scene scene, AsyncOperation op, AsyncOperationHandle<SceneInstance> addr, bool weLoaded, bool viaAddr)> items = new List<(string, Scene, AsyncOperation, AsyncOperationHandle<SceneInstance>, bool, bool)>(num); for (int j = batchStart; j < batchStart + num; j++) { string text3 = sceneNames[j]; if (IsDumpSkipped(text3)) { excluded++; continue; } Scene sceneByName = SceneManager.GetSceneByName(text3); if (((Scene)(ref sceneByName)).IsValid() && ((Scene)(ref sceneByName)).isLoaded) { items.Add((text3, sceneByName, null, default(AsyncOperationHandle<SceneInstance>), false, false)); continue; } AsyncOperation val = null; AsyncOperationHandle<SceneInstance> item = default(AsyncOperationHandle<SceneInstance>); bool flag = false; try { if (viaAddrList) { item = Addressables.LoadSceneAsync((object)("Scenes/" + text3), (LoadSceneMode)1, true, 100, (SceneReleaseMode)0); } else { val = SceneManager.LoadSceneAsync(text3, (LoadSceneMode)1); } flag = true; } catch { skipped++; } if (flag && (val != null || viaAddrList)) { items.Add((text3, default(Scene), val, item, true, viaAddrList)); } else if (flag) { skipped++; } } float deadline = Time.realtimeSinceStartup + 60f; bool pending = true; while (pending && Time.realtimeSinceStartup <= deadline) { pending = false; foreach (var item4 in items) { if (item4.weLoaded) { bool isDone; if (!item4.viaAddr) { isDone = item4.op.isDone; } else { AsyncOperationHandle<SceneInstance> item2 = item4.addr; isDone = item2.IsDone; } if (!isDone) { pending = true; break; } } } if (pending) { yield return null; } } foreach (var item5 in items) { Scene val2; if (!item5.weLoaded) { val2 = item5.scene; } else { int num2; if (!item5.viaAddr) { num2 = (item5.op.isDone ? 1 : 0); } else { AsyncOperationHandle<SceneInstance> item2 = item5.addr; if (item2.IsDone) { item2 = item5.addr; num2 = (((int)item2.Status == 1) ? 1 : 0); } else { num2 = 0; } } if (num2 == 0) { skipped++; if (!item5.viaAddr) { continue; } try { AsyncOperationHandle<SceneInstance> item2 = item5.addr; if (item2.IsValid()) { Addressables.Release<SceneInstance>(item5.addr); } } catch { } continue; } Scene val3; if (!item5.viaAddr) { val3 = SceneManager.GetSceneByName(item5.name); } else { AsyncOperationHandle<SceneInstance> item2 = item5.addr; SceneInstance result = item2.Result; val3 = ((SceneInstance)(ref result)).Scene; } val2 = val3; } try { if (((Scene)(ref val2)).IsValid() && ((Scene)(ref val2)).isLoaded) { int num3 = 0; int num4 = 0; GameObject[] rootGameObjects = ((Scene)(ref val2)).GetRootGameObjects(); for (int k = 0; k < rootGameObjects.Length; k++) { TransitionPoint[] componentsInChildren = rootGameObjects[k].GetComponentsInChildren<TransitionPoint>(true); foreach (TransitionPoint val4 in componentsInChildren) { if (!((Object)(object)val4 == (Object)null) && !string.IsNullOrEmpty(val4.targetScene)) { num4++; string text4 = item5.name + "|" + ((Object)((Component)val4).gameObject).name; string text5 = val4.targetScene + "|" + val4.entryPoint; string item3 = ((string.CompareOrdinal(text4, text5) <= 0) ? (text4 + "<->" + text5) : (text5 + "<->" + text4)); if (seenPairs.Add(item3)) { writer.WriteLine(text4 + "|" + val4.targetScene + "|" + val4.entryPoint); pairCount++; num3++; } } } } sceneCount++; } else { skipped++; } } catch { skipped++; } } foreach (var item6 in items) { if (!item6.weLoaded) { continue; } try { if (item6.viaAddr) { AsyncOperationHandle<SceneInstance> item2 = item6.addr; if (!item2.IsValid()) { continue; } item2 = item6.addr; if (item2.IsDone) { item2 = item6.addr; if ((int)item2.Status == 1) { Addressables.UnloadSceneAsync(item6.addr, true); } } continue; } Scene sceneByName2 = SceneManager.GetSceneByName(item6.name); if (((Scene)(ref sceneByName2)).IsValid() && ((Scene)(ref sceneByName2)).isLoaded) { SceneManager.UnloadSceneAsync(sceneByName2); } } catch { } } writer.Flush(); yield return null; } } finally { HotkeyHandler hotkeyHandler = this; Application.backgroundLoadingPriority = oldLoadPriority; suppressField?.SetValue(null, false); hotkeyHandler._isDumpingTransitions = false; } } private void WarpToLastBench() { try { PlayerData instance = PlayerData.instance; if (instance == null) { Plugin.Log.LogError("[HotkeyHandler] PlayerData 不可用"); return; } string respawnScene = instance.respawnScene; if (string.IsNullOrEmpty(respawnScene)) { Plugin.Log.LogWarning("[HotkeyHandler] 重生点场景为空,请先坐一次椅子"); return; } Plugin.Log.LogInfo("[HotkeyHandler] 传送至重生点: " + respawnScene + " / " + instance.respawnMarkerName); GameManager gm = GameManager.instance; gm.SaveGame((Action<bool>)delegate(bool success) { if (!success) { Plugin.Log.LogError("[HotkeyHandler] 保存游戏失败"); } else { gm.LoadGameFromUI(gm.profileID); } }); } catch (Exception ex) { Plugin.Log.LogError("[HotkeyHandler] 传送异常: " + ex.Message); } } private static void ToggleRecentItemsUI() { RecentItemsUI.Toggle(); Plugin.Log.LogInfo("最近获得物品UI " + (RecentItemsUI.IsVisible ? "显示" : "隐藏")); } private void DrawAnnotateWindow() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown //IL_00e2: Expected O, but got Unknown //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Expected O, but got Unknown //IL_0194: Expected O, but got Unknown //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Expected O, but got Unknown //IL_01e7: Expected O, but got Unknown //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Expected O, but got Unknown //IL_023c: Expected O, but got Unknown //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Expected O, but got Unknown //IL_0297: Expected O, but got Unknown //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Expected O, but got Unknown //IL_02ef: Expected O, but got Unknown if (_annotateIndex >= _annotateList.Count) { FinishAnnotate(); return; } string text = _annotateList[_annotateIndex]; float num = ((float)Screen.width - 900f) / 2f; float num2 = ((float)Screen.height - 300f) / 2f; GUI.Box(new Rect(num, num2, 900f, 300f), ""); Rect val = new Rect(num + 20f, num2 + 12f, 860f, 30f); string text2 = $"图标备注器 {_annotateIndex + 1}/{_annotateList.Count} 填写该图标用途"; GUIStyle obj = _titleBoldStyle; if (obj == null) { GUIStyle val2 = new GUIStyle(GUI.skin.label) { fontSize = 20, fontStyle = (FontStyle)1 }; GUIStyle val3 = val2; _titleBoldStyle = val2; obj = val3; } GUI.Label(val, text2, obj); Rect val4 = default(Rect); ((Rect)(ref val4))..ctor(num + 30f, num2 + 60f, 200f, 200f); Sprite val5 = SpriteCache.Find(text); if ((Object)(object)val5 != (Object)null && (Object)(object)val5.texture != (Object)null) { GUI.Dra
BepInEx/plugins/StartingAbilityPicker.dll
Decompiled a week ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GlobalEnums; using GlobalSettings; using HKSilksong_Randomizer; using HarmonyLib; using HutongGames.PlayMaker; using HutongGames.PlayMaker.Actions; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using SilksongItemRandomizer; using TMPro; using TeamCherry.Localization; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("StartingAbilityPicker")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("StartingAbilityPicker")] [assembly: AssemblyTitle("StartingAbilityPicker")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/YourGitHubUsername/StartingAbilityPicker")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 StartingAbilityPicker { [BepInPlugin("HardItemRandomizer.StartingAbilityPicker", "Starting Ability Picker", "1.0.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { internal static ModLog Log = ModLog.For("SAP"); public static bool AllowLeftAttack = false; public static bool AllowRightAttack = false; public static bool AllowUpwardAttack = false; public static bool DirectionEnabled = true; public static bool AllowDashLeft = false; public static bool AllowDashRight = false; public static bool AllowHarpoonLeft = false; public static bool AllowHarpoonRight = false; public static bool AllowFloatLeft = false; public static bool AllowFloatRight = false; public static bool AllowWallJumpLeft = false; public static bool AllowWallJumpRight = false; public static bool AllowHeal = false; public static bool skillMode = false; public static int skillTotal = 0; public static int skillV = 0; public static int skillH = 0; public static int skillS = 0; public static int skillA = 0; public const int MaxVertical = 5; public const int MaxHorizontal = 4; public const int MaxSpecial = 4; public const int MaxAttack = 5; private bool _lastSceneWasMenu = true; private bool showUI; public static bool allowUpward = false; public static bool allowLeft = false; public static bool allowRight = false; public static int itemCount = 0; public static bool resetPickups = false; public static string seedInput = ""; internal static HashSet<int> chosenProfileSet = new HashSet<int>(); private static string _notificationMessage = null; private static float _notificationEndTime = 0f; private static GUIStyle _notificationStyle; private static Sprite _backgroundSprite; private static Sprite _beginnerIcon; private static Sprite _focusedIcon; private static Sprite _overflowIcon; private static bool _bgLoaded = false; private static Rect _windowRect; private static float _lastScreenHeight; public static bool crestCurseEnabled = false; public static ConfigEntry<bool> CfgAllowDashLeft; public static ConfigEntry<bool> CfgAllowDashRight; public static ConfigEntry<bool> CfgAllowHarpoonLeft; public static ConfigEntry<bool> CfgAllowHarpoonRight; public static ConfigEntry<bool> CfgAllowFloatLeft; public static ConfigEntry<bool> CfgAllowFloatRight; public static ConfigEntry<bool> CfgAllowWallJumpLeft; public static ConfigEntry<bool> CfgAllowWallJumpRight; public static ConfigEntry<bool> CfgAllowHeal; private static readonly WaitForSeconds HalfSecondWait = new WaitForSeconds(0.5f); public bool _pendingApply; public int _pendingSkillTotal; public int _pendingSkillV; public int _pendingSkillH; public int _pendingSkillS; public int _pendingSkillA; public bool _pendingSkillMode; public int _pendingItemCount; private bool _sceneRandomAvailable; private Type _sceneLoaderType; private Type _roomRandoType; private Type _seedManagerType; private object _sceneLoader; private object _roomRando; private object _seedManager; private FieldInfo _cfgShowSceneLabelField; private FieldInfo _currentSceneNameField; private MethodInfo _getSeedMethod; private string sceneSeedInput = ""; private string sceneTeleportInput = ""; private bool _pendingTeleport; private string _pendingTeleportScene = ""; private bool _apiInitialized; private static bool _hasLoadedFromSaveData = false; private bool _giveArmed; private Coroutine _giveWatchdog; private GameManager _boundGameManager; private static FieldInfo _currentSeedField; private static FieldInfo _enableRandomizationField; private static PropertyInfo _publicItemRandomProp; public static Plugin Instance { get; private set; } public static ConfigEntry<bool> UseNativeSkillGiving { get; private set; } public static ConfigEntry<string> ChosenProfiles { get; private set; } public static ConfigEntry<int> StartingSkillCount { get; private set; } public static ConfigEntry<int> StartingItemCount { get; private set; } public static ConfigEntry<int> RandomSeed { get; private set; } public static ConfigEntry<bool> CfgCrestCurseEnabled { get; private set; } public static ConfigEntry<bool> EnemyRandoAdjustEnabled { get; private set; } public static ConfigEntry<bool> PanelBackgroundEnabled { get; private set; } public static ConfigEntry<bool> CfgDirectionEnabled { get; private set; } public static ConfigEntry<bool> CfgFullRandomMode { get; private set; } public bool ShowUI { get { return showUI; } set { showUI = value; } } public string SceneSeedInput { get { return sceneSeedInput; } set { sceneSeedInput = value; } } public string SceneTeleportInput { get { return sceneTeleportInput; } set { sceneTeleportInput = value; } } public bool PendingTeleport { get { return _pendingTeleport; } set { _pendingTeleport = value; } } public string PendingTeleportScene { get { return _pendingTeleportScene; } set { _pendingTeleportScene = value; } } public object SeedManager => _seedManager; public bool SceneRandomAvailable => _sceneRandomAvailable; public static int MaxVerticalDynamic => 5; public static int MaxHorizontalDynamic => 4; public static int MaxSpecialDynamic => 4; public static int MaxAttackDynamic => 5; public static Sprite BeginnerIcon => _beginnerIcon; public static Sprite FocusedIcon => _focusedIcon; public static Sprite OverflowIcon => _overflowIcon; public static bool FullRandomModeEnabled { get { return DirectionPatch.FullRandomMode; } set { DirectionPatch.FullRandomMode = value; } } private int currentProfileID => PlayerData.instance?.profileID ?? (-1); public void SetPendingOpeningSettings(bool skillMode, int skillTotal, int skillV, int skillH, int skillS, int skillA, int itemCount) { _pendingSkillMode = skillMode; _pendingSkillTotal = skillTotal; _pendingSkillV = skillV; _pendingSkillH = skillH; _pendingSkillS = skillS; _pendingSkillA = skillA; _pendingItemCount = itemCount; _pendingApply = true; } public static void ShowNotification(string message, float duration = 3f) { _notificationMessage = message; _notificationEndTime = Time.time + duration; } private Texture2D MakeTexture(int width, int height, Color col) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown Color[] array = (Color[])(object)new Color[width * height]; for (int i = 0; i < array.Length; i++) { array[i] = col; } Texture2D val = new Texture2D(width, height); val.SetPixels(array); val.Apply(); return val; } public static bool GetCrestCurseEnabled() { return crestCurseEnabled; } public static void SetCrestCurseEnabled(bool value) { if (crestCurseEnabled != value) { crestCurseEnabled = value; CfgCrestCurseEnabled.Value = value; try { Type.GetType("SilksongItemRandomizer.ToolEffectRandomizer, SilksongItemRandomizer")?.GetMethod("SetEnabled", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, new object[1] { value }); } catch { } Log.LogInfo("纹章诅咒开关: " + (value ? "启用" : "禁用")); } } public static void SetFullRandomMode(bool enabled) { DirectionPatch.FullRandomMode = enabled; } public void SetForceCompletionDisplay(bool value) { int num = currentProfileID; if (num == -1 || GetForceCompletionDisplay() == value) { return; } Plugin.SaveData.ProfileCompletionDisplay[num] = value; Plugin.SaveGlobalData(); Log.LogInfo(string.Format("强制完成度显示开关 (存档 {0}): {1}", num, value ? "启用(显示)" : "禁用(隐藏)")); PlayerData instance = PlayerData.instance; if (instance != null) { if (value) { instance.ConstructedFarsight = true; RefreshCompletionUI(forceShow: true); } else { ClearFsmCompletionVariables(); } } GlobalConfig.Save(); } private void Awake() { Instance = this; ModLog.SetFallback(((BaseUnityPlugin)this).Logger); Log.LogInfo("StartingAbilityPicker loaded! Press F7 to open starting options."); ChosenProfiles = GlobalConfig.ChosenProfiles; StartingSkillCount = GlobalConfig.StartingSkillCount; StartingItemCount = GlobalConfig.StartingItemCount; RandomSeed = GlobalConfig.RandomSeed; CfgCrestCurseEnabled = GlobalConfig.CrestCurseEnabled; crestCurseEnabled = CfgCrestCurseEnabled.Value; AllowUpwardAttack = GlobalConfig.AttackUp.Value; AllowLeftAttack = GlobalConfig.AttackLeft.Value; AllowRightAttack = GlobalConfig.AttackRight.Value; SharedRuntimeSettings.AttackUp = AllowUpwardAttack; SharedRuntimeSettings.AttackLeft = AllowLeftAttack; SharedRuntimeSettings.AttackRight = AllowRightAttack; _hasLoadedFromSaveData = true; Log.LogInfo($"从 cfg 加载攻击方向: Up={AllowUpwardAttack}, Left={AllowLeftAttack}, Right={AllowRightAttack}"); try { Type.GetType("SilksongItemRandomizer.ToolEffectRandomizer, SilksongItemRandomizer")?.GetMethod("SetEnabled", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, new object[1] { crestCurseEnabled }); } catch { } EnemyRandoAdjustEnabled = GlobalConfig.EnemyRandoAdjustEnabled; try { Type type = Type.GetType("SilksongItemRandomizer.EnemyRandoAdjuster, SilksongItemRandomizer"); if (type != null) { PropertyInfo property = type.GetProperty("Enabled", BindingFlags.Static | BindingFlags.Public); if (property != null) { property.SetValue(null, EnemyRandoAdjustEnabled.Value); } } } catch (Exception arg) { Log.LogError($"同步怪物调整开关失败: {arg}"); } PanelBackgroundEnabled = GlobalConfig.PanelBackgroundEnabled; UseNativeSkillGiving = GlobalConfig.UseNativeSkillGiving; SkillRandomizer.UseNativeItemGiving = UseNativeSkillGiving.Value; CfgDirectionEnabled = GlobalConfig.DirectionEnabled; DirectionEnabled = CfgDirectionEnabled.Value; CfgAllowDashLeft = GlobalConfig.DashLeft; CfgAllowDashRight = GlobalConfig.DashRight; CfgAllowHarpoonLeft = GlobalConfig.HarpoonLeft; CfgAllowHarpoonRight = GlobalConfig.HarpoonRight; CfgAllowFloatLeft = GlobalConfig.FloatLeft; CfgAllowFloatRight = GlobalConfig.FloatRight; CfgAllowWallJumpLeft = GlobalConfig.WallJumpLeft; CfgAllowWallJumpRight = GlobalConfig.WallJumpRight; CfgAllowHeal = GlobalConfig.Heal; AllowDashLeft = CfgAllowDashLeft.Value; AllowDashRight = CfgAllowDashRight.Value; AllowHarpoonLeft = CfgAllowHarpoonLeft.Value; AllowHarpoonRight = CfgAllowHarpoonRight.Value; AllowFloatLeft = CfgAllowFloatLeft.Value; AllowFloatRight = CfgAllowFloatRight.Value; AllowWallJumpLeft = CfgAllowWallJumpLeft.Value; AllowWallJumpRight = CfgAllowWallJumpRight.Value; AllowHeal = CfgAllowHeal.Value; CfgFullRandomMode = GlobalConfig.FullRandomMode; DirectionPatch.FullRandomMode = CfgFullRandomMode.Value; SharedRuntimeSettings.UseTypeMode = GlobalConfig.UseTypeMode.Value; SharedRuntimeSettings.SkillTotal = GlobalConfig.StartingSkillCount.Value; SharedRuntimeSettings.SkillVertical = GlobalConfig.SkillVertical.Value; SharedRuntimeSettings.SkillHorizontal = GlobalConfig.SkillHorizontal.Value; SharedRuntimeSettings.SkillSpecial = GlobalConfig.SkillSpecial.Value; SharedRuntimeSettings.SkillAttack = GlobalConfig.SkillAttack.Value; SharedRuntimeSettings.ItemCount = GlobalConfig.StartingItemCount.Value; SharedRuntimeSettings.ForceCompletionDisplay = GlobalConfig.ForceCompletionDisplay.Value; SharedRuntimeSettings.ResetSeedWorld = GlobalConfig.ResetSeedWorld.Value; LoadChosenProfiles(); EnsureRandomSeed(); SceneManager.sceneLoaded += OnSceneLoaded; Harmony.CreateAndPatchAll(typeof(DirectionPatch), (string)null); Harmony.CreateAndPatchAll(typeof(AbilityGatePatch), (string)null); Harmony.CreateAndPatchAll(typeof(DirectionPopupHelper), (string)null); Harmony.CreateAndPatchAll(typeof(SaveStats_GetCompletionPercentage_Patch), (string)null); Harmony.CreateAndPatchAll(typeof(SaveStats_UnlockedCompletionRate_Patch), (string)null); Harmony.CreateAndPatchAll(typeof(PlayerData_CountGameCompletion_Patch), (string)null); Harmony.CreateAndPatchAll(typeof(ConvertFloatToString_Patch), (string)null); Harmony.CreateAndPatchAll(typeof(BuildString_Patch), (string)null); Harmony.CreateAndPatchAll(typeof(SkillRandomizer.SkillGetMsg_Setup_Finalizer), (string)null); ((MonoBehaviour)this).StartCoroutine(LoadAllImages()); InitSceneRandomRefs(); StartingAbilityPickerAPI.Initialize(new StartingAbilityPickerConfig { Seed = RandomSeed.Value, FullRandomMode = CfgFullRandomMode.Value, MovementPermissions = new DirectionPermissions { DashLeft = AllowDashLeft, DashRight = AllowDashRight, HarpoonLeft = AllowHarpoonLeft, HarpoonRight = AllowHarpoonRight, FloatLeft = AllowFloatLeft, FloatRight = AllowFloatRight, WallJumpLeft = AllowWallJumpLeft, WallJumpRight = AllowWallJumpRight, AllowHeal = AllowHeal }, CrestCurseEnabled = crestCurseEnabled, ForceCompletionDisplay = GetForceCompletionDisplay(), UseNativeSkillGiving = UseNativeSkillGiving.Value, PanelBackgroundEnabled = PanelBackgroundEnabled.Value, DefaultStartingItemCount = StartingItemCount.Value, DefaultSkillTotal = StartingSkillCount.Value, DefaultSkillV = 0, DefaultSkillH = 0, DefaultSkillS = 0, DefaultSkillA = 0, DefaultSkillTypeMode = false, DefaultResetPickups = false, DefaultAttackPermissions = (up: AllowUpwardAttack, left: AllowLeftAttack, right: AllowRightAttack), DisableBuiltinShortcut = false }); _apiInitialized = true; } private IEnumerator LoadAllImages() { string folder = Path.Combine(Paths.PluginPath, "elesanren-Hard_Item_Randomizer", "nandu"); string text = Path.Combine(folder, "4.png"); if (File.Exists(text)) { WWW www = new WWW("file://" + text); try { yield return www; if (string.IsNullOrEmpty(www.error) && (Object)(object)www.texture != (Object)null) { _backgroundSprite = Sprite.Create(www.texture, new Rect(0f, 0f, (float)((Texture)www.texture).width, (float)((Texture)www.texture).height), new Vector2(0.5f, 0.5f)); } } finally { ((IDisposable)www)?.Dispose(); } } string[] iconFiles = new string[3] { "1.png", "2.png", "3.png" }; for (int i = 0; i < 3; i++) { string text2 = Path.Combine(folder, iconFiles[i]); if (!File.Exists(text2)) { continue; } WWW www = new WWW("file://" + text2); try { yield return www; if (string.IsNullOrEmpty(www.error) && (Object)(object)www.texture != (Object)null) { Sprite val = Sprite.Create(www.texture, new Rect(0f, 0f, (float)((Texture)www.texture).width, (float)((Texture)www.texture).height), new Vector2(0.5f, 0.5f)); switch (i) { case 0: _beginnerIcon = val; break; case 1: _focusedIcon = val; break; case 2: _overflowIcon = val; break; } } } finally { ((IDisposable)www)?.Dispose(); } } _bgLoaded = true; } private void EnsureRandomSeed() { if (RandomSeed.Value == 0) { int num = (int)DateTime.UtcNow.Ticks ^ Environment.TickCount; if (num <= 0) { num = -num; } if (num <= 0) { num = 1; } RandomSeed.Value = num; GlobalConfig.Save(); } } private void OnDestroy() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown SceneManager.sceneLoaded -= OnSceneLoaded; if ((Object)(object)_boundGameManager != (Object)null) { _boundGameManager.OnFinishedEnteringScene -= new EnterSceneEvent(OnEntrySceneFinished); _boundGameManager = null; } ModLog.Shutdown(); } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (((Scene)(ref scene)).name != "Menu_Title" && ((Scene)(ref scene)).name != "Menu" && ((Scene)(ref scene)).name != "Loading" && (Object)(object)HeroController.instance != (Object)null) { AllowUpwardAttack = GlobalConfig.AttackUp.Value; AllowLeftAttack = GlobalConfig.AttackLeft.Value; AllowRightAttack = GlobalConfig.AttackRight.Value; SharedRuntimeSettings.AttackUp = AllowUpwardAttack; SharedRuntimeSettings.AttackLeft = AllowLeftAttack; SharedRuntimeSettings.AttackRight = AllowRightAttack; _hasLoadedFromSaveData = true; LoadPlayerDataSettings(); SharedRuntimeSettings.UseTypeMode = skillMode; SharedRuntimeSettings.SkillTotal = skillTotal; SharedRuntimeSettings.SkillVertical = skillV; SharedRuntimeSettings.SkillHorizontal = skillH; SharedRuntimeSettings.SkillSpecial = skillS; SharedRuntimeSettings.SkillAttack = skillA; SharedRuntimeSettings.ItemCount = StartingItemCount.Value; InitSceneRandomInstances(); if (GetForceCompletionDisplay()) { PlayerData instance = PlayerData.instance; if (instance != null && !instance.ConstructedFarsight) { instance.ConstructedFarsight = true; Log.LogInfo($"已强制解锁完成度显示 (ConstructedFarsight) for profile {currentProfileID}"); } RefreshCompletionUI(forceShow: true); } Log.LogInfo($"[OnSceneLoaded] 场景 '{((Scene)(ref scene)).name}' 加载完成, _pendingApply={_pendingApply}, " + $"total={_pendingSkillTotal}, V={_pendingSkillV}, H={_pendingSkillH}, S={_pendingSkillS}, A={_pendingSkillA}, items={_pendingItemCount}"); if (_pendingApply) { Log.LogInfo("[OnSceneLoaded] _pendingApply=true, 登记开局发放,等入场流程结束事件"); ArmOpeningGive(); } else { Log.LogInfo("[OnSceneLoaded] _pendingApply=false, 跳过给予流程"); } if (_apiInitialized) { StartingAbilityPickerAPI.MarkGameReady(); } } else if (((Scene)(ref scene)).name == "Menu_Title" || ((Scene)(ref scene)).name == "Menu") { _lastSceneWasMenu = true; } if (!GetForceCompletionDisplay()) { ClearFsmCompletionVariables(); } } internal void ArmOpeningGive() { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) BindEntryEvent(); _giveArmed = true; if (_giveWatchdog != null) { ((MonoBehaviour)this).StopCoroutine(_giveWatchdog); } _giveWatchdog = ((MonoBehaviour)this).StartCoroutine(GiveWatchdogCoroutine()); ModLog log = Log; Scene activeScene = SceneManager.GetActiveScene(); log.LogInfo("[OpeningGive] 已登记,等入场完成事件后再发放(" + ((Scene)(ref activeScene)).name + ")"); } private void BindEntryEvent() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown GameManager instance = GameManager.instance; if ((Object)(object)instance == (Object)null) { Log.LogWarning("[OpeningGive] GameManager 尚未就绪,本次只能靠超时兜底"); } else if (!((Object)(object)_boundGameManager == (Object)(object)instance)) { if ((Object)(object)_boundGameManager != (Object)null) { _boundGameManager.OnFinishedEnteringScene -= new EnterSceneEvent(OnEntrySceneFinished); } instance.OnFinishedEnteringScene += new EnterSceneEvent(OnEntrySceneFinished); _boundGameManager = instance; } } private void OnEntrySceneFinished() { if (!_giveArmed) { return; } HeroController instance = HeroController.instance; if (!((Object)(object)instance == (Object)null)) { if (!instance.isHeroInPosition || instance.controlReqlinquished || instance.cState == null || instance.cState.transitioning || instance.cState.hazardDeath || instance.cState.hazardRespawning) { Log.LogWarning("[OpeningGive] 收到入场完成事件但英雄未就绪,继续等下一次事件"); } else { FireGive("入场完成事件"); } } } private void FireGive(string source) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) _giveArmed = false; if (_giveWatchdog != null) { ((MonoBehaviour)this).StopCoroutine(_giveWatchdog); _giveWatchdog = null; } ModLog log = Log; string[] obj = new string[5] { "[OpeningGive] ", source, "到达(", null, null }; Scene activeScene = SceneManager.GetActiveScene(); obj[3] = ((Scene)(ref activeScene)).name; obj[4] = "),开始发放"; log.LogInfo(string.Concat(obj)); ((MonoBehaviour)this).StartCoroutine(GiveSettledCoroutine()); } private IEnumerator GiveWatchdogCoroutine() { yield return (object)new WaitForSecondsRealtime(12f); _giveWatchdog = null; if (_giveArmed) { if ((Object)(object)HeroController.instance == (Object)null || PlayerData.instance == null) { Log.LogWarning("[OpeningGive] 12 秒内英雄仍未就绪,放弃本次发放"); _giveArmed = false; _pendingApply = false; } else { Log.LogWarning("[OpeningGive] 12 秒内没等到入场完成事件,按当前状态兜底发放"); FireGive("超时兜底"); } } } private IEnumerator GiveSettledCoroutine() { yield return (object)new WaitForSeconds(0.2f); ApplyOpeningSettingsNow(); } private void ApplyOpeningSettingsNow() { skillMode = _pendingSkillMode; skillTotal = _pendingSkillTotal; skillV = _pendingSkillV; skillH = _pendingSkillH; skillS = _pendingSkillS; skillA = _pendingSkillA; itemCount = _pendingItemCount; resetPickups = false; ApplySettings(); _pendingApply = false; } private void GivePendingSkillsAndItems() { Log.LogInfo($"[GivePendingSkillsAndItems] 开始给予 — mode={_pendingSkillMode}, " + $"total={_pendingSkillTotal}, V={_pendingSkillV}, H={_pendingSkillH}, S={_pendingSkillS}, A={_pendingSkillA}, items={_pendingItemCount}"); if (DirectionPatch.FullRandomMode) { int count = (_pendingSkillMode ? (_pendingSkillV + _pendingSkillH + _pendingSkillS + _pendingSkillA) : _pendingSkillTotal); SkillRandomizer.GiveFullRandomStarters(StartingAbilityPickerAPI.GetSeed(), count); } else if (!_pendingSkillMode) { for (int i = 0; i < _pendingSkillTotal; i++) { SkillRandomizer.GiveRandomSkill(); } } else { for (int j = 0; j < _pendingSkillV; j++) { SkillRandomizer.GiveRandomSkillFromCategory(SkillRandomizer.VerticalSkills); } for (int k = 0; k < _pendingSkillH; k++) { SkillRandomizer.GiveRandomSkillFromCategory(SkillRandomizer.HorizontalSkills); } for (int l = 0; l < _pendingSkillS; l++) { SkillRandomizer.GiveRandomSkillFromCategory(SkillRandomizer.SpecialSkills); } for (int m = 0; m < _pendingSkillA; m++) { SkillRandomizer.GiveRandomSkillFromCategory(SkillRandomizer.AttackSkills); } } for (int n = 0; n < _pendingItemCount; n++) { SavedItem randomItem = ItemRandomizer.GetRandomItem(); if ((Object)(object)randomItem != (Object)null) { randomItem.TryGet(false, true); } } RoomRandomMode.TryApply(); _pendingApply = false; showUI = false; Log.LogInfo("技能和物品给予完成"); } private void LoadPlayerDataSettings() { try { PlayerData instance = PlayerData.instance; if (instance != null) { skillMode = instance.GetBool("SkillRandomMode"); skillTotal = instance.GetInt("SkillTotalCount"); skillV = instance.GetInt("SkillVerticalCount"); skillH = instance.GetInt("SkillHorizontalCount"); skillS = instance.GetInt("SkillSpecialCount"); skillA = instance.GetInt("SkillAttackCount"); if (!skillMode && skillTotal == 0) { skillTotal = StartingSkillCount.Value; } } } catch (Exception arg) { Log.LogError($"加载技能随机设置失败: {arg}"); } } private void InitSceneRandomRefs() { _sceneRandomAvailable = false; try { _sceneLoaderType = Type.GetType("HKSilksong_Randomizer.RandomSceneLoader, HKSilksong_SceneRandomizer"); _roomRandoType = Type.GetType("HKSilksong_Randomizer.RoomRando, HKSilksong_SceneRandomizer"); _seedManagerType = Type.GetType("HKSilksong_Randomizer.SeedManager, HKSilksong_SceneRandomizer"); if (_sceneLoaderType == null || _roomRandoType == null || _seedManagerType == null) { Log.LogWarning("场景随机模块类型未找到,右侧面板将不可用"); return; } _cfgShowSceneLabelField = _sceneLoaderType.GetField("cfgShowSceneLabel", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field = _sceneLoaderType.GetField("currentSceneName", BindingFlags.Instance | BindingFlags.NonPublic); _currentSceneNameField = field; MethodInfo method = _roomRandoType.GetMethod("GetGenerationSeed"); _getSeedMethod = method; _sceneRandomAvailable = true; Log.LogInfo("场景随机模块可用(静态接口)"); } catch (Exception ex) { Log.LogWarning("场景随机模块初始化失败: " + ex.Message); } } private void InitSceneRandomInstances() { try { GameObject val = GameObject.Find("__RoomRando"); GameObject val2 = GameObject.Find("__SeedManager"); if ((Object)(object)val != (Object)null) { _roomRando = val.GetComponent(_roomRandoType); } if ((Object)(object)val2 != (Object)null) { _seedManager = val2.GetComponent(_seedManagerType); } if (_seedManager != null) { _sceneLoader = _seedManager.GetType().GetField("sceneLoader", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(_seedManager); } } catch (Exception ex) { Log.LogWarning("获取场景随机实例失败: " + ex.Message); } } private void LoadChosenProfiles() { chosenProfileSet.Clear(); string[] array = ChosenProfiles.Value.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { if (int.TryParse(array[i].Trim(), out var result)) { chosenProfileSet.Add(result); } } } internal void SaveChosenProfiles() { ChosenProfiles.Value = string.Join(",", chosenProfileSet); GlobalConfig.Save(); } private void Update() { if (Input.GetKeyDown((KeyCode)288) && currentProfileID != -1) { showUI = !showUI; if (showUI) { allowUpward = AllowUpwardAttack; allowLeft = AllowLeftAttack; allowRight = AllowRightAttack; itemCount = StartingItemCount.Value; resetPickups = false; seedInput = RandomSeed.Value.ToString(); } } if (Input.GetKeyDown((KeyCode)9) && !GetForceCompletionDisplay()) { ClearFsmCompletionVariables(); } if (_pendingTeleport) { _pendingTeleport = false; ((MonoBehaviour)this).StartCoroutine(DelayedTeleport(_pendingTeleportScene)); } } private IEnumerator DelayedTeleport(string sceneName) { yield return HalfSecondWait; try { if (_sceneLoader != null) { object obj = _sceneLoader.GetType().GetField("cfgTeleportScene", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(_sceneLoader); object obj2 = _sceneLoader.GetType().GetField("cfgTeleportConfirm", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(_sceneLoader); obj?.GetType().GetProperty("Value")?.SetValue(obj, sceneName, null); obj2?.GetType().GetProperty("Value")?.SetValue(obj2, true, null); ShowNotification(Locale.Get("正在传送到 ") + sceneName + " ..."); } } catch (Exception arg) { Log.LogError($"传送失败: {arg}"); } } private void OnGUI() { //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Expected O, but got Unknown //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) if (_notificationMessage != null && Time.time <= _notificationEndTime) { if (_notificationStyle == null) { _notificationStyle = new GUIStyle(GUI.skin.box) { fontSize = 40, alignment = (TextAnchor)4 }; _notificationStyle.normal.textColor = Color.white; _notificationStyle.normal.background = MakeTexture(2, 2, new Color(0f, 0f, 0f, 0.7f)); } float num = 600f; float num2 = 120f; GUI.Box(new Rect(((float)Screen.width - num) / 2f, (float)(Screen.height / 2 - 100), num, num2), _notificationMessage, _notificationStyle); } else { _notificationMessage = null; } if (!showUI) { return; } if (((Rect)(ref _windowRect)).width == 0f || Mathf.Abs((float)Screen.height - _lastScreenHeight) > 1f) { float num3 = Screen.height; float num4 = 1080f; float num5 = 925f; float num6 = num3 / 8f; float num7 = num3 - num4 - num6; if (num7 < 0f) { num7 = 0f; } _windowRect = new Rect(20f, num7, num5, num4); _lastScreenHeight = num3; } _windowRect = GUILayout.Window(100, _windowRect, new WindowFunction(DrawUIWindow), Locale.Get("开局选项 & 场景随机"), Array.Empty<GUILayoutOption>()); } private void DrawUIWindow(int windowID) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) if (PanelBackgroundEnabled.Value && (Object)(object)_backgroundSprite != (Object)null && (Object)(object)_backgroundSprite.texture != (Object)null) { GUI.DrawTexture(new Rect(0f, 0f, ((Rect)(ref _windowRect)).width, ((Rect)(ref _windowRect)).height), (Texture)(object)_backgroundSprite.texture, (ScaleMode)0); } else { GUI.DrawTexture(new Rect(0f, 0f, ((Rect)(ref _windowRect)).width, ((Rect)(ref _windowRect)).height), (Texture)(object)Texture2D.whiteTexture, (ScaleMode)0, true, 0f, new Color(0.15f, 0.15f, 0.15f, 0.85f), 0f, 0f); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(558f) }); PanelRenderer.DrawLeftPanel(this); GUILayout.EndVertical(); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(270f) }); PanelRenderer.DrawScenePanel(this); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUI.DragWindow(); } internal void ApplySettings() { Log.LogInfo("ApplySettings 开始执行"); StartingAbilityPickerAPI.SetAttackPermissions(allowUpward, allowLeft, allowRight); StartingAbilityPickerAPI.SetSkillRandomMode(skillMode); StartingAbilityPickerAPI.SetSkillCounts(skillTotal, skillV, skillH, skillS, skillA); StartingAbilityPickerAPI.SetStartingItemCount(itemCount); if (int.TryParse(seedInput, out var result)) { StartingAbilityPickerAPI.SetSeed(result); } StartingAbilityPickerAPI.SetResetSeedWorld(resetPickups); StartingAbilityPickerAPI.SetFullRandomMode(DirectionPatch.FullRandomMode); StartingAbilityPickerAPI.SetCrestCurseEnabled(crestCurseEnabled); StartingAbilityPickerAPI.SetForceCompletionDisplay(GetForceCompletionDisplay()); StartingAbilityPickerAPI.ApplyPending(); _pendingSkillMode = skillMode; _pendingSkillTotal = skillTotal; _pendingSkillV = skillV; _pendingSkillH = skillH; _pendingSkillS = skillS; _pendingSkillA = skillA; _pendingItemCount = itemCount; if (resetPickups) { _pendingApply = true; Log.LogInfo("重置种子世界,将在场景加载完成后给予技能和物品"); ResetSeedWorld(); } else { GivePendingSkillsAndItems(); RoomRandomMode.TryApply(); showUI = false; } Log.LogInfo("ApplySettings 执行完成"); StartingAbilityPickerAPI.SaveAllSettingsToConfig(); } private void ResetSeedWorld() { if (!int.TryParse(seedInput, out var result) || result == RandomSeed.Value) { result = new Random().Next(1, int.MaxValue); } seedInput = result.ToString(); RandomSeed.Value = result; GlobalConfig.Save(); TrySyncOtherMods(result); try { PlayerData instance = PlayerData.instance; if (instance == null) { return; } FieldInfo[] fields = typeof(PlayerData).GetFields(BindingFlags.Instance | BindingFlags.Public); int num = 0; FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { if (fieldInfo.Name.StartsWith("SkillTriggered_")) { fieldInfo.SetValue(instance, false); num++; } } Log.LogInfo($"已重置 {num} 个技能触发器记录"); } catch (Exception arg) { Log.LogError($"重置技能触发器失败: {arg}"); } } public static void ResetSeedWorldExternal(int newSeed) { seedInput = newSeed.ToString(); RandomSeed.Value = newSeed; GlobalConfig.Save(); Instance.TrySyncOtherMods(newSeed); try { PlayerData instance = PlayerData.instance; if (instance == null) { return; } FieldInfo[] fields = typeof(PlayerData).GetFields(BindingFlags.Instance | BindingFlags.Public); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.Name.StartsWith("SkillTriggered_")) { fieldInfo.SetValue(instance, false); } } } catch { } } private void TrySyncOtherMods(int newSeed) { try { Type type = Type.GetType("SilksongItemRandomizer.Plugin, SilksongItemRandomizer"); if (type != null) { PropertyInfo property = type.GetProperty("RandomSeed", BindingFlags.Static | BindingFlags.Public); if (property != null && property.GetValue(null) is ConfigEntry<int> val) { val.Value = newSeed; } type.GetMethod("ResetAllStaticData", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, null); } } catch { } try { Type type2 = Type.GetType("SkillTriggerMod.Plugin, SkillTriggerMod"); if (type2 != null) { PropertyInfo property2 = type2.GetProperty("RandomSeed", BindingFlags.Static | BindingFlags.Public); if (property2 != null && property2.GetValue(null) is ConfigEntry<int> val2) { val2.Value = newSeed; } Type.GetType("SkillTriggerMod.SkillRandomizer, SkillTriggerMod")?.GetMethod("SetSeed", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, new object[1] { newSeed }); type2.GetMethod("ResetAllRecords", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, null); } Plugin.SaveData.SkillTriggerRecords.Clear(); Plugin.SaveGlobalData(); } catch { } try { Type? type3 = Type.GetType("SilksongItemRandomizer.CrestRandomizer, SilksongItemRandomizer"); type3?.GetMethod("ResetMappings", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, null); type3?.GetMethod("Initialize", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, null); Type.GetType("SilksongItemRandomizer.CrestRandomizePatch, SilksongItemRandomizer")?.GetMethod("ResetProcessedIds", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, null); Type.GetType("SilksongItemRandomizer.BenchRespawnPatch, SilksongItemRandomizer")?.GetMethod("ResetCooldown", BindingFlags.Static | BindingFlags.Public)?.Invoke(null, null); } catch { } } public int GetCurrentSeed() { if (_sceneLoaderType == null) { return 0; } try { if (_currentSeedField == null) { _currentSeedField = _sceneLoaderType.GetField("CurrentSeed", BindingFlags.Static | BindingFlags.Public); } FieldInfo currentSeedField = _currentSeedField; if (currentSeedField != null) { return (int)currentSeedField.GetValue(null); } } catch (Exception ex) { Log.LogWarning("获取当前种子失败: " + ex.Message); } return 0; } public string GetCurrentSceneName() { if (_sceneLoader == null) { return ""; } try { return (string)_currentSceneNameField?.GetValue(_sceneLoader); } catch { return ""; } } public bool GetSceneRandomEnabled() { if (_sceneLoaderType == null) { return false; } try { if (_enableRandomizationField == null) { _enableRandomizationField = _sceneLoaderType.GetField("EnableRandomization", BindingFlags.Static | BindingFlags.Public); } FieldInfo enableRandomizationField = _enableRandomizationField; if (enableRandomizationField != null) { return (bool)enableRandomizationField.GetValue(null); } } catch { } return false; } public void SetSceneRandomEnabled(bool enabled) { if (_sceneLoaderType == null) { return; } try { if (_enableRandomizationField == null) { _enableRandomizationField = _sceneLoaderType.GetField("EnableRandomization", BindingFlags.Static | BindingFlags.Public); } _enableRandomizationField?.SetValue(null, enabled); if (_sceneLoader != null) { FieldInfo field = _sceneLoaderType.GetField("cfgEnableRandomization", BindingFlags.Instance | BindingFlags.NonPublic); if (field != null) { object value = field.GetValue(_sceneLoader); value?.GetType().GetProperty("Value")?.SetValue(value, enabled, null); } } } catch { } } public bool GetShowSceneLabel() { if (_cfgShowSceneLabelField != null && _sceneLoader != null) { try { object value = _cfgShowSceneLabelField.GetValue(_sceneLoader); object obj = value?.GetType().GetProperty("Value")?.GetValue(value); if (obj is bool) { return (bool)obj; } } catch { } } return true; } public void SetShowSceneLabel(bool value, bool isSeed = false) { try { if (!isSeed) { if (_cfgShowSceneLabelField != null && _sceneLoader != null) { object value2 = _cfgShowSceneLabelField.GetValue(_sceneLoader); value2?.GetType().GetProperty("Value")?.SetValue(value2, value, null); } } else if (_seedManager != null) { object obj = _seedManager.GetType().GetField("cfgShowSeedOnScreen", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(_seedManager); obj?.GetType().GetProperty("Value")?.SetValue(obj, value, null); } } catch { } } public bool GetShowSeedLabel() { try { if (_seedManager != null) { object obj = _seedManager.GetType().GetField("cfgShowSeedOnScreen", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(_seedManager); return (bool)(obj?.GetType().GetProperty("Value")?.GetValue(obj) ?? ((object)true)); } } catch { } return true; } public bool GetForceCompletionDisplay() { int num = currentProfileID; if (num == -1) { return true; } if (Plugin.SaveData.ProfileCompletionDisplay.TryGetValue(num, out var value)) { return value; } return true; } private void RefreshCompletionUI(bool forceShow = false) { if (!GetForceCompletionDisplay() && !forceShow) { ClearFsmCompletionVariables(); return; } PlayerData instance = PlayerData.instance; if (instance == null) { return; } string value = Mathf.RoundToInt(instance.completionPercentage) + "%"; string[] array = new string[4] { "Inv", "Tools", "Journal", "Quests" }; for (int i = 0; i < array.Length; i++) { GameObject val = GameObject.Find(array[i]); if ((Object)(object)val == (Object)null) { continue; } PlayMakerFSM component = val.GetComponent<PlayMakerFSM>(); if (!((Object)(object)component == (Object)null)) { FsmString val2 = component.FsmVariables.FindFsmString("Completion Percentage Str"); if (val2 != null) { val2.Value = value; } } } } private void ClearFsmCompletionVariables() { try { string[] array = new string[4] { "Inv", "Tools", "Journal", "Quests" }; for (int i = 0; i < array.Length; i++) { GameObject val = GameObject.Find(array[i]); if ((Object)(object)val == (Object)null) { continue; } PlayMakerFSM component = val.GetComponent<PlayMakerFSM>(); if ((Object)(object)component == (Object)null) { continue; } FsmString[] stringVariables = component.FsmVariables.StringVariables; foreach (FsmString val2 in stringVariables) { if (((NamedVariable)val2).Name.IndexOf("Completion", StringComparison.OrdinalIgnoreCase) >= 0) { val2.Value = ""; } } } } catch (Exception arg) { Log.LogWarning($"清空完成度变量失败: {arg}"); } } public bool GetItemRandomEnabled() { try { if (_publicItemRandomProp == null) { _publicItemRandomProp = Type.GetType("SilksongItemRandomizer.Plugin, SilksongItemRandomizer")?.GetProperty("PublicItemRandomEnabled", BindingFlags.Static | BindingFlags.Public); } return _publicItemRandomProp != null && (bool)_publicItemRandomProp.GetValue(null); } catch { } return false; } public void ApplyStartingSettings() { GivePendingSkillsAndItems(); } public void SetItemRandomEnabled(bool value) { try { if (_publicItemRandomProp == null) { _publicItemRandomProp = Type.GetType("SilksongItemRandomizer.Plugin, SilksongItemRandomizer")?.GetProperty("PublicItemRandomEnabled", BindingFlags.Static | BindingFlags.Public); } _publicItemRandomProp?.SetValue(null, value); } catch { } } public void SetEnemyRandoAdjustEnabled(bool value) { EnemyRandoAdjustEnabled.Value = value; GlobalConfig.Save(); try { Type type = Type.GetType("SilksongItemRandomizer.EnemyRandoAdjuster, SilksongItemRandomizer"); if (type != null) { PropertyInfo property = type.GetProperty("Enabled", BindingFlags.Static | BindingFlags.Public); if (property != null) { property.SetValue(null, value); } } } catch (Exception arg) { Log.LogError($"设置怪物调整开关失败: {arg}"); } } public void SetPanelBackgroundEnabled(bool value) { PanelBackgroundEnabled.Value = value; } } [HarmonyPatch(typeof(SaveStats), "GetCompletionPercentage")] public static class SaveStats_GetCompletionPercentage_Patch { [HarmonyPostfix] private static void Postfix(ref string __result) { if ((Object)(object)Plugin.Instance != (Object)null && !Plugin.Instance.GetForceCompletionDisplay()) { __result = ""; } } } [HarmonyPatch(typeof(SaveStats), "get_UnlockedCompletionRate")] public static class SaveStats_UnlockedCompletionRate_Patch { [HarmonyPostfix] private static void Postfix(ref bool __result) { if ((Object)(object)Plugin.Instance != (Object)null && !Plugin.Instance.GetForceCompletionDisplay()) { __result = false; } } } [HarmonyPatch(typeof(PlayerData), "CountGameCompletion")] public static class PlayerData_CountGameCompletion_Patch { [HarmonyPrefix] private static bool Prefix() { if ((Object)(object)Plugin.Instance != (Object)null) { return Plugin.Instance.GetForceCompletionDisplay(); } return true; } } [HarmonyPatch(typeof(ConvertFloatToString), "OnEnter")] public static class ConvertFloatToString_Patch { private static void Postfix(ConvertFloatToString __instance) { if ((Object)(object)Plugin.Instance != (Object)null && !Plugin.Instance.GetForceCompletionDisplay() && __instance.stringVariable != null && ((NamedVariable)__instance.stringVariable).Name == "Completion Percentage Str") { __instance.stringVariable.Value = ""; } } } [HarmonyPatch(typeof(BuildString), "OnEnter")] public static class BuildString_Patch { private static void Postfix(BuildString __instance) { if ((Object)(object)Plugin.Instance != (Object)null && !Plugin.Instance.GetForceCompletionDisplay() && __instance.storeResult != null && ((NamedVariable)__instance.storeResult).Name == "Completion Percentage Str") { __instance.storeResult.Value = ""; } } } public sealed class ModLog { private const int FlushThreshold = 4096; private static readonly Dictionary<string, ModLog> _byTag; private static readonly object _registryGate; private static ManualLogSource _fallback; private static bool _closed; private readonly string _tag; private readonly object _gate = new object(); private readonly StringBuilder _buffer = new StringBuilder(5120); private StreamWriter _writer; private bool _broken; private static ModLog _default; private static ModLog DefaultInstance { get { ModLog modLog = _default; if (modLog != null) { return modLog; } return _default = For(typeof(ModLog).Assembly.GetName().Name); } } private ModLog(string tag) { _tag = tag; } public static ModLog For(string tag) { lock (_registryGate) { if (_byTag.TryGetValue(tag, out var value)) { return value; } value = new ModLog(tag); _byTag[tag] = value; return value; } } public static void SetFallback(ManualLogSource source) { _fallback = source; } public static void Shutdown() { lock (_registryGate) { _closed = true; foreach (KeyValuePair<string, ModLog> item in _byTag) { item.Value.Close(); } _byTag.Clear(); } } static ModLog() { _byTag = new Dictionary<string, ModLog>(4); _registryGate = new object(); try { AppDomain.CurrentDomain.ProcessExit += delegate { Shutdown(); }; AppDomain.CurrentDomain.DomainUnload += delegate { Shutdown(); }; } catch { } } public void LogInfo(object message) { Write("INFO ", message); } public void LogWarning(object message) { Write("WARN ", message); } public void LogError(object message) { Write("ERROR", message); } public void LogDebug(object message) { Write("DEBUG", message); } public void LogMessage(object message) { Write("INFO ", message); } public static void Info(object message) { DefaultInstance.LogInfo(message); } public static void Warning(object message) { DefaultInstance.LogWarning(message); } public static void Error(object message) { DefaultInstance.LogError(message); } public static void Debug(object message) { DefaultInstance.LogDebug(message); } private void Write(string level, object message) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (message == null) { return; } string text = message as string; if (text == null) { text = message.ToString(); } if (string.IsNullOrEmpty(text)) { return; } lock (_gate) { if (_closed) { return; } if (_broken) { if (_fallback != null) { _fallback.Log(LevelOf(level), (object)text); } return; } _buffer.Append(DateTime.Now.ToString("HH:mm:ss.fff")); _buffer.Append(" [").Append(level).Append("] "); _buffer.Append(text); _buffer.Append('\n'); if (_buffer.Length >= 4096 || level == "ERROR") { FlushLocked(); } } } private void FlushLocked() { if (_buffer.Length == 0) { return; } try { if (_writer == null) { OpenLocked(); } _writer.Write(_buffer.ToString()); _writer.Flush(); _buffer.Length = 0; } catch (Exception ex) { _broken = true; _buffer.Length = 0; if (_fallback != null) { _fallback.LogWarning((object)("[ModLog] 写入日志文件失败,后续日志回退到 BepInEx 日志: " + ex.Message)); } } } private void OpenLocked() { string text = Path.Combine(Paths.ConfigPath, "SilksongItemRandomizer", "logs"); Directory.CreateDirectory(text); string path = _tag + ".log"; FileStream stream = new FileStream(Path.Combine(text, path), FileMode.Create, FileAccess.Write, FileShare.ReadWrite); _writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); _writer.AutoFlush = false; } private void Close() { lock (_gate) { if (_buffer.Length > 0 && !_broken) { FlushLocked(); } if (_writer != null) { try { _writer.Flush(); _writer.Dispose(); } catch { } _writer = null; } _buffer.Length = 0; } } private static LogLevel LevelOf(string level) { return (LogLevel)(level switch { "ERROR" => 2, "WARN " => 4, "DEBUG" => 32, _ => 16, }); } } public class DirectionPermissions { public bool DashLeft; public bool DashRight; public bool HarpoonLeft; public bool HarpoonRight; public bool FloatLeft; public bool FloatRight; public bool WallJumpLeft; public bool WallJumpRight; public bool AllowHeal = true; } public class StartingSettings { public bool AllowUpward; public bool AllowLeft; public bool AllowRight; public bool UseTypeMode; public int SkillTotal; public int SkillVertical; public int SkillHorizontal; public int SkillSpecial; public int SkillAttack; public int StartingItemCount; public int Seed; public bool ResetSeedWorld; public bool FullRandomMode; public bool CrestCurseEnabled; public bool ForceCompletionDisplay = true; public DirectionPermissions MovementPermissions; } public class StartingAbilityPickerConfig { public int Seed; public bool FullRandomMode; public DirectionPermissions MovementPermissions; public bool CrestCurseEnabled; public bool ForceCompletionDisplay = true; public bool UseNativeSkillGiving = true; public bool PanelBackgroundEnabled = true; public int DefaultStartingItemCount; public int DefaultSkillTotal; public int DefaultSkillV; public int DefaultSkillH; public int DefaultSkillS; public int DefaultSkillA; public bool DefaultSkillTypeMode; public bool DefaultResetPickups; public (bool up, bool left, bool right) DefaultAttackPermissions = (up: false, left: false, right: false); public bool DisableBuiltinShortcut; } public static class StartingAbilityPickerAPI { private static bool _initialized = false; private static StartingAbilityPickerConfig _config; private static DirectionPermissions _currentMovement = new DirectionPermissions(); private static bool _fullRandomMode = false; private static bool _crestCurseEnabled = false; private static bool _forceCompletionDisplay = true; private static bool _useTypeMode = false; private static int _skillTotal = 0; private static int _skillV = 0; private static int _skillH = 0; private static int _skillS = 0; private static int _skillA = 0; private static int _itemCount = 0; private static int _seed = 0; private static bool _resetSeedWorld = false; private static bool _allowUpward = false; private static bool _allowLeft = false; private static bool _allowRight = false; private static bool _pendingChanges = false; private static bool _applied = false; private static bool _isGameReady = false; public static void Initialize(StartingAbilityPickerConfig config) { if (!_initialized) { _config = config ?? new StartingAbilityPickerConfig(); if (SharedRuntimeSettings.Seed == 0 && _config.Seed != 0) { _seed = _config.Seed; } else { _seed = SharedRuntimeSettings.Seed; } _fullRandomMode = SharedRuntimeSettings.FullRandomMode; _crestCurseEnabled = SharedRuntimeSettings.CrestCurseEnabled; _forceCompletionDisplay = SharedRuntimeSettings.ForceCompletionDisplay; _useTypeMode = SharedRuntimeSettings.UseTypeMode; _skillTotal = SharedRuntimeSettings.SkillTotal; _skillV = SharedRuntimeSettings.SkillVertical; _skillH = SharedRuntimeSettings.SkillHorizontal; _skillS = SharedRuntimeSettings.SkillSpecial; _skillA = SharedRuntimeSettings.SkillAttack; _itemCount = SharedRuntimeSettings.ItemCount; _resetSeedWorld = SharedRuntimeSettings.ResetSeedWorld; _allowUpward = SharedRuntimeSettings.AttackUp; _allowLeft = SharedRuntimeSettings.AttackLeft; _allowRight = SharedRuntimeSettings.AttackRight; _currentMovement.DashLeft = SharedRuntimeSettings.DashLeft; _currentMovement.DashRight = SharedRuntimeSettings.DashRight; _currentMovement.HarpoonLeft = SharedRuntimeSettings.HarpoonLeft; _currentMovement.HarpoonRight = SharedRuntimeSettings.HarpoonRight; _currentMovement.FloatLeft = SharedRuntimeSettings.FloatLeft; _currentMovement.FloatRight = SharedRuntimeSettings.FloatRight; _currentMovement.WallJumpLeft = SharedRuntimeSettings.WallJumpLeft; _currentMovement.WallJumpRight = SharedRuntimeSettings.WallJumpRight; _currentMovement.AllowHeal = SharedRuntimeSettings.AllowHeal; SyncToPlugin(); _initialized = true; _pendingChanges = true; } } private static void SyncToPlugin() { Plugin.SetFullRandomMode(_fullRandomMode); Plugin.SetCrestCurseEnabled(_crestCurseEnabled); Plugin.Instance?.SetForceCompletionDisplay(_forceCompletionDisplay); SkillRandomizer.UseNativeItemGiving = _config?.UseNativeSkillGiving ?? true; if (_config != null) { Plugin.PanelBackgroundEnabled.Value = _config.PanelBackgroundEnabled; } Plugin.skillMode = _useTypeMode; Plugin.skillTotal = _skillTotal; Plugin.skillV = _skillV; Plugin.skillH = _skillH; Plugin.skillS = _skillS; Plugin.skillA = _skillA; Plugin.itemCount = _itemCount; Plugin.seedInput = _seed.ToString(); Plugin.resetPickups = _resetSeedWorld; Plugin.allowUpward = _allowUpward; Plugin.allowLeft = _allowLeft; Plugin.allowRight = _allowRight; Plugin.AllowDashLeft = _currentMovement.DashLeft; Plugin.AllowDashRight = _currentMovement.DashRight; Plugin.AllowHarpoonLeft = _currentMovement.HarpoonLeft; Plugin.AllowHarpoonRight = _currentMovement.HarpoonRight; Plugin.AllowFloatLeft = _currentMovement.FloatLeft; Plugin.AllowFloatRight = _currentMovement.FloatRight; Plugin.AllowWallJumpLeft = _currentMovement.WallJumpLeft; Plugin.AllowWallJumpRight = _currentMovement.WallJumpRight; Plugin.AllowHeal = _currentMovement.AllowHeal; Plugin.AllowUpwardAttack = _allowUpward; Plugin.AllowLeftAttack = _allowLeft; Plugin.AllowRightAttack = _allowRight; } public static void MarkGameReady() { _isGameReady = true; if (_pendingChanges) { ApplyPending(); } } public static void ApplyPending() { if (_pendingChanges) { DirectionPatch.FullRandomMode = _fullRandomMode; DirectionPatch.SetAllowAttackDirection(_allowUpward, _allowLeft, _allowRight); if (_currentMovement != null) { DirectionPatch.SetAllowDashDirection(_currentMovement.DashLeft, _currentMovement.DashRight); DirectionPatch.SetAllowHarpoonDirection(_currentMovement.HarpoonLeft, _currentMovement.HarpoonRight); DirectionPatch.SetAllowFloatDirection(_currentMovement.FloatLeft, _currentMovement.FloatRight); DirectionPatch.SetAllowWallJumpDirection(_currentMovement.WallJumpLeft, _currentMovement.WallJumpRight); DirectionPatch.SetAllowHeal(_currentMovement.AllowHeal); } Plugin.SetCrestCurseEnabled(_crestCurseEnabled); Plugin.Instance?.SetForceCompletionDisplay(_forceCompletionDisplay); PlayerData val = (PlayerData.HasInstance ? PlayerData.instance : null); if (val != null) { val.SetBool("SkillRandomMode", _useTypeMode); val.SetInt("SkillTotalCount", _skillTotal); val.SetInt("SkillVerticalCount", _skillV); val.SetInt("SkillHorizontalCount", _skillH); val.SetInt("SkillSpecialCount", _skillS); val.SetInt("SkillAttackCount", _skillA); } if (_resetSeedWorld) { Plugin.ResetSeedWorldExternal(_seed); } _pendingChanges = false; _applied = true; } } public static void SetFullRandomMode(bool enabled) { _fullRandomMode = enabled; Plugin.SetFullRandomMode(enabled); SharedRuntimeSettings.FullRandomMode = enabled; _pendingChanges = true; ApplyPending(); } public static bool GetFullRandomMode() { return _fullRandomMode; } public static void SaveAllSettingsToConfig() { GlobalConfig.FullRandomMode.Value = SharedRuntimeSettings.FullRandomMode; GlobalConfig.AttackUp.Value = SharedRuntimeSettings.AttackUp; GlobalConfig.AttackLeft.Value = SharedRuntimeSettings.AttackLeft; GlobalConfig.AttackRight.Value = SharedRuntimeSettings.AttackRight; GlobalConfig.DashLeft.Value = SharedRuntimeSettings.DashLeft; GlobalConfig.DashRight.Value = SharedRuntimeSettings.DashRight; GlobalConfig.HarpoonLeft.Value = SharedRuntimeSettings.HarpoonLeft; GlobalConfig.HarpoonRight.Value = SharedRuntimeSettings.HarpoonRight; GlobalConfig.FloatLeft.Value = SharedRuntimeSettings.FloatLeft; GlobalConfig.FloatRight.Value = SharedRuntimeSettings.FloatRight; GlobalConfig.WallJumpLeft.Value = SharedRuntimeSettings.WallJumpLeft; GlobalConfig.WallJumpRight.Value = SharedRuntimeSettings.WallJumpRight; GlobalConfig.Heal.Value = SharedRuntimeSettings.AllowHeal; GlobalConfig.TrapEnabled.Value = SharedRuntimeSettings.TrapEnabled; GlobalConfig.TrapMovementEnabled.Value = SharedRuntimeSettings.TrapMovementEnabled; GlobalConfig.TrapDifficulty.Value = SharedRuntimeSettings.TrapDifficulty; GlobalConfig.EnemyRandoAdjustEnabled.Value = SharedRuntimeSettings.EnemyRandomEnabled; GlobalConfig.EnemyScaleRandom.Value = EnemyRandoAdjuster.ScaleRandomEnabled; GlobalConfig.EnemyScaleMin.Value = EnemyRandoAdjuster.ScaleMin; GlobalConfig.EnemyScaleMax.Value = EnemyRandoAdjuster.ScaleMax; GlobalConfig.ItemRandomEnabled.Value = SharedRuntimeSettings.ItemRandomEnabled; GlobalConfig.CrestRandomEnabled.Value = SharedRuntimeSettings.CrestRandomEnabled; GlobalConfig.SilkRandomizerEnabled.Value = SharedRuntimeSettings.SilkRandomEnabled; GlobalConfig.CrestCurseEnabled.Value = SharedRuntimeSettings.CrestCurseEnabled; GlobalConfig.ForceCompletionDisplay.Value = SharedRuntimeSettings.ForceCompletionDisplay; GlobalConfig.UseTypeMode.Value = SharedRuntimeSettings.UseTypeMode; GlobalConfig.StartingSkillCount.Value = SharedRuntimeSettings.SkillTotal; GlobalConfig.SkillVertical.Value = SharedRuntimeSettings.SkillVertical; GlobalConfig.SkillHorizontal.Value = SharedRuntimeSettings.SkillHorizontal; GlobalConfig.SkillSpecial.Value = SharedRuntimeSettings.SkillSpecial; GlobalConfig.SkillAttack.Value = SharedRuntimeSettings.SkillAttack; GlobalConfig.StartingItemCount.Value = SharedRuntimeSettings.ItemCount; GlobalConfig.RandomSeed.Value = SharedRuntimeSettings.Seed; GlobalConfig.ResetSeedWorld.Value = SharedRuntimeSettings.ResetSeedWorld; GlobalConfig.ColdResist.Value = SharedRuntimeSettings.ColdResistOwned; GlobalConfig.Swim.Value = SharedRuntimeSettings.SwimOwned; GlobalConfig.SaveNow(); } public static void SetCrestCurseEnabled(bool enabled) { _crestCurseEnabled = enabled; Plugin.SetCrestCurseEnabled(enabled); SharedRuntimeSettings.CrestCurseEnabled = enabled; _pendingChanges = true; ApplyPending(); } public static bool GetCrestCurseEnabled() { return _crestCurseEnabled; } public static void SetForceCompletionDisplay(bool enabled) { _forceCompletionDisplay = enabled; Plugin.Instance?.SetForceCompletionDisplay(enabled); SharedRuntimeSettings.ForceCompletionDisplay = enabled; _pendingChanges = true; ApplyPending(); } public static bool GetForceCompletionDisplay() { return _forceCompletionDisplay; } public static void SetAttackPermissions(bool up, bool left, bool right) { _allowUpward = up; _allowLeft = left; _allowRight = right; Plugin.allowUpward = up; Plugin.allowLeft = left; Plugin.allowRight = right; Plugin.AllowUpwardAttack = up; Plugin.AllowLeftAttack = left; Plugin.AllowRightAttack = right; SharedRuntimeSettings.AttackUp = up; SharedRuntimeSettings.AttackLeft = left; SharedRuntimeSettings.AttackRight = right; _pendingChanges = true; ApplyPending(); } public static (bool up, bool left, bool right) GetAttackPermissions() { return (up: _allowUpward, left: _allowLeft, right: _allowRight); } public static void SetMovementPermissions(DirectionPermissions perms) { if (perms != null) { _currentMovement.DashLeft = perms.DashLeft; _currentMovement.DashRight = perms.DashRight; _currentMovement.HarpoonLeft = perms.HarpoonLeft; _currentMovement.HarpoonRight = perms.HarpoonRight; _currentMovement.FloatLeft = perms.FloatLeft; _currentMovement.FloatRight = perms.FloatRight; _currentMovement.WallJumpLeft = perms.WallJumpLeft; _currentMovement.WallJumpRight = perms.WallJumpRight; _currentMovement.AllowHeal = perms.AllowHeal; Plugin.AllowDashLeft = perms.DashLeft; Plugin.AllowDashRight = perms.DashRight; Plugin.AllowHarpoonLeft = perms.HarpoonLeft; Plugin.AllowHarpoonRight = perms.HarpoonRight; Plugin.AllowFloatLeft = perms.FloatLeft; Plugin.AllowFloatRight = perms.FloatRight; Plugin.AllowWallJumpLeft = perms.WallJumpLeft; Plugin.AllowWallJumpRight = perms.WallJumpRight; Plugin.AllowHeal = perms.AllowHeal; SharedRuntimeSettings.DashLeft = perms.DashLeft; SharedRuntimeSettings.DashRight = perms.DashRight; SharedRuntimeSettings.HarpoonLeft = perms.HarpoonLeft; SharedRuntimeSettings.HarpoonRight = perms.HarpoonRight; SharedRuntimeSettings.FloatLeft = perms.FloatLeft; SharedRuntimeSettings.FloatRight = perms.FloatRight; SharedRuntimeSettings.WallJumpLeft = perms.WallJumpLeft; SharedRuntimeSettings.WallJumpRight = perms.WallJumpRight; SharedRuntimeSettings.AllowHeal = perms.AllowHeal; _pendingChanges = true; ApplyPending(); } } public static DirectionPermissions GetMovementPermissions() { return _currentMovement; } public static void SetSkillRandomMode(bool useTypeMode) { _useTypeMode = useTypeMode; Plugin.skillMode = useTypeMode; SharedRuntimeSettings.UseTypeMode = useTypeMode; _pendingChanges = true; ApplyPending(); } public static bool GetSkillRandomMode() { return _useTypeMode; } public static void SetSkillCounts(int total, int v, int h, int s, int a) { _skillTotal = total; _skillV = v; _skillH = h; _skillS = s; _skillA = a; Plugin.skillTotal = total; Plugin.skillV = v; Plugin.skillH = h; Plugin.skillS = s; Plugin.skillA = a; SharedRuntimeSettings.SkillTotal = total; SharedRuntimeSettings.SkillVertical = v; SharedRuntimeSettings.SkillHorizontal = h; SharedRuntimeSettings.SkillSpecial = s; SharedRuntimeSettings.SkillAttack = a; _pendingChanges = true; ApplyPending(); } public static (int total, int v, int h, int s, int a) GetSkillCounts() { return (total: _skillTotal, v: _skillV, h: _skillH, s: _skillS, a: _skillA); } public static void SetStartingItemCount(int count) { _itemCount = count; Plugin.itemCount = count; SharedRuntimeSettings.ItemCount = count; _pendingChanges = true; ApplyPending(); } public static int GetStartingItemCount() { return _itemCount; } public static void SetSeed(int seed) { _seed = seed; Plugin.seedInput = seed.ToString(); Plugin.RandomSeed.Value = seed; SharedRuntimeSettings.Seed = seed; _pendingChanges = true; ApplyPending(); } public static int GetSeed() { return _seed; } public static void SetResetSeedWorld(bool reset) { _resetSeedWorld = reset; Plugin.resetPickups = reset; SharedRuntimeSettings.ResetSeedWorld = reset; _pendingChanges = true; ApplyPending(); } public static bool GetResetSeedWorld() { return _resetSeedWorld; } public static List<string> PreviewStartingSkills() { return SkillRandomizer.PreviewStartingSkills(_seed, _useTypeMode, _skillTotal, _skillV, _skillH, _skillS, _skillA); } public static bool HasPendingChanges() { return _pendingChanges; } public static void ApplySettingsNow(StartingSettings settings) { if (settings != null) { _allowUpward = settings.AllowUpward; _allowLeft = settings.AllowLeft; _allowRight = settings.AllowRight; _useTypeMode = settings.UseTypeMode; _skillTotal = settings.SkillTotal; _skillV = settings.SkillVertical; _skillH = settings.SkillHorizontal; _skillS = settings.SkillSpecial; _skillA = settings.SkillAttack; _itemCount = settings.StartingItemCount; _seed = settings.Seed; _resetSeedWorld = settings.ResetSeedWorld; _fullRandomMode = settings.FullRandomMode; _crestCurseEnabled = settings.CrestCurseEnabled; _forceCompletionDisplay = settings.ForceCompletionDisplay; if (settings.MovementPermissions != null) { _currentMovement = settings.MovementPermissions; } SyncToPlugin(); SharedRuntimeSettings.AttackUp = _allowUpward; SharedRuntimeSettings.AttackLeft = _allowLeft; SharedRuntimeSettings.AttackRight = _allowRight; SharedRuntimeSettings.UseTypeMode = _useTypeMode; SharedRuntimeSettings.SkillTotal = _skillTotal; SharedRuntimeSettings.SkillVertical = _skillV; SharedRuntimeSettings.SkillHorizontal = _skillH; SharedRuntimeSettings.SkillSpecial = _skillS; SharedRuntimeSettings.SkillAttack = _skillA; SharedRuntimeSettings.ItemCount = _itemCount; SharedRuntimeSettings.Seed = _seed; SharedRuntimeSettings.ResetSeedWorld = _resetSeedWorld; SharedRuntimeSettings.FullRandomMode = _fullRandomMode; SharedRuntimeSettings.CrestCurseEnabled = _crestCurseEnabled; SharedRuntimeSettings.ForceCompletionDisplay = _forceCompletionDisplay; SharedRuntimeSettings.DashLeft = _currentMovement.DashLeft; SharedRuntimeSettings.DashRight = _currentMovement.DashRight; SharedRuntimeSettings.HarpoonLeft = _currentMovement.HarpoonLeft; SharedRuntimeSettings.HarpoonRight = _currentMovement.HarpoonRight; SharedRuntimeSettings.FloatLeft = _currentMovement.FloatLeft; SharedRuntimeSettings.FloatRight = _currentMovement.FloatRight; SharedRuntimeSettings.WallJumpLeft = _currentMovement.WallJumpLeft; SharedRuntimeSettings.WallJumpRight = _currentMovement.WallJumpRight; SharedRuntimeSettings.AllowHeal = _currentMovement.AllowHeal; ApplyPending(); if ((Object)(object)Plugin.Instance != (Object)null) { Plugin.Instance.ApplyStartingSettings(); } } } public static void RefreshUI() { SyncToPlugin(); } public static void SetItemRandomEnabled(bool enabled) { SilksongItemRandomizerAPI.SetEnabled(enabled); } public static void SetSceneRandomEnabled(bool enabled) { HKSilksong_RandomizerAPI.SetEnabled(enabled); } public static void SetTrapRandomEnabled(bool enabled) { SilksongItemRandomizerAPI.SetTrapEnabled(enabled); } public static void SetEnemyRandomEnabled(bool enabled) { (Type.GetType("SilksongItemRandomizer.EnemyRandoAdjuster, SilksongItemRandomizer")?.GetProperty("Enabled", BindingFlags.Static | BindingFlags.Public))?.SetValue(null, enabled); } public static void GiveSkill(string skillField, bool nativePopup = true) { SkillRandomizer.GiveSkill(skillField, nativePopup); } public static void GiveSilkHeart(Sprite icon = null) { SkillRandomizer.GiveSilkHeart(icon); } public static void GiveRandomSkill() { SkillRandomizer.GiveRandomSkill(); } public static void GiveRandomSkillFromCategory(string[] categoryFields) { SkillRandomizer.GiveRandomSkillFromCategory(new List<string>(categoryFields)); } public static void SetAbilityGates(bool healGate, bool jumpGate, bool coldGate, bool swimGate) { bool flag = jumpGate; bool num = SharedRuntimeSettings.HealGateEnabled == healGate && SharedRuntimeSettings.JumpGateEnabled == jumpGate && SharedRuntimeSettings.ColdResistGateEnabled == coldGate && SharedRuntimeSettings.SwimGateEnabled == swimGate && SharedRuntimeSettings.FloatGateEnabled == flag; SharedRuntimeSettings.HealGateEnabled = healGate; SharedRuntimeSettings.JumpGateEnabled = jumpGate; SharedRuntimeSettings.ColdResistGateEnabled = coldGate; SharedRuntimeSettings.SwimGateEnabled = swimGate; SharedRuntimeSettings.FloatGateEnabled = flag; if (!num) { Plugin.Log.LogInfo($"[SAP-API] 能力门控 heal={healGate} jump={jumpGate} float={flag} cold={coldGate} swim={swimGate}"); } } public static void SetColdResist(bool owned) { SharedRuntimeSettings.ColdResistOwned = owned; } public static void SetDoubleJumpOwned(bool owned) { SharedRuntimeSettings.DoubleJumpOwned = owned; } public static void SetFloatOwned(bool owned) { SharedRuntimeSettings.FloatOwned = owned; } public static void SetSwimOwned(bool owned) { SharedRuntimeSettings.SwimOwned = owned; } public static int GetCurrentRoomSeed() { try { return HKSilksong_RandomizerAPI.GetCurrentRoomSeed(); } catch { return 0; } } public static string GetCurrentRoomScene() { try { return HKSilksong_RandomizerAPI.GetCurrentSceneName(); } catch { return ""; } } public static void SetRoomRandomizationEnabled(bool enabled) { try { HKSilksong_RandomizerAPI.SetEnabled(enabled); } catch { } } public static bool IsRoomRandomizationEnabled() { try { return HKSilksong_RandomizerAPI.IsSceneRandomEnabled(); } catch { return false; } } public static void TeleportToRoom(string sceneName, string entryGate = null) { try { HKSilksong_RandomizerAPI.TeleportToScene(sceneName, entryGate); } catch { } } public static string GetDisplayName(string skillField) { try { return SkillRandomizer.GetDisplayName(skillField); } catch { return skillField; } } public static Sprite GetIcon(string skillField) { try { return SkillRandomizer.GetIcon(skillField); } catch { return null; } } public static void ShowSettingsUI(bool show) { Plugin.Instance.ShowUI = show; } public static bool IsSettingsUIVisible() { return Plugin.Instance.ShowUI; } } public static class SkillRandomizer { private sealed class BannerMsgItem : ICollectableUIMsgItem, IUIMsgPopupItem { private readonly string _name; private readonly Sprite _icon; public BannerMsgItem(string name, Sprite icon) { _name = name; _icon = icon; } public Object GetRepresentingObject() { return null; } public Sprite GetUIMsgSprite() { return _icon; } public string GetUIMsgName() { return _name; } public float GetUIMsgIconScale() { return 1f; } public bool HasUpgradeIcon() { return false; } } [HarmonyPatch(typeof(SkillGetMsg), "Setup")] internal static class SkillGetMsg_Setup_Finalizer { private static Exception Finalizer(Exception __exception, ToolItemSkill skill) { if (__exception == null) { return null; } try { string text = null; try { text = PlayerData.instance?.CurrentCrestID; } catch { } Plugin.Log.LogError("[技能弹窗] SkillGetMsg.Setup 异常已兜底(skill=" + ((skill != null) ? ((ToolItem)skill).name : null) + ", crest=" + text + "): " + __exception.Message); } catch { } return null; } } public sealed class StarterPermission { public string Id; public string DisplayName; public string SkillField; public bool AllowRight; public bool AllowLeft; public bool IsAttack; public bool IsHeal; } private static readonly Dictionary<string, string> SkillChineseNames = new Dictionary<string, string> { { "hasNeedleThrow", "丝之矛" }, { "hasThreadSphere", "灵丝风暴" }, { "hasHarpoonDash", "飞针" }, { "hasSilkCharge", "丝刃标" }, { "hasSilkBomb", "符文之怒" }, { "hasSilkBossNeedle", "苍白之爪" }, { "hasNeedolin", "丝忆弦针" }, { "hasDash", "疾风步" }, { "hasBrolly", "流浪者披风" }, { "hasDoubleJump", "雪绒披风" }, { "hasChargeSlash", "蓄力斩" }, { "hasSuperJump", "灵丝升腾" }, { "hasWalljump", "蛛攀术" }, { "HasSeenEvaHeal", "风铃摇" }, { "hasParry", "格挡" }, { "hasNeedolinMemoryPowerup", "深邃挽歌" }, { "hasFastTravelTeleport", "幻兽歌" }, { "CollectedHeartCoral", "珊瑚之心" }, { "CollectedHeartFlower", "繁花之心" }, { "CollectedHeartHunter", "猎人之心" }, { "CollectedHeartClover", "三叶草之心" }, { "HasMelodyConductor", "指挥家旋律" }, { "HasMelodyLibrarian", "图书管理员旋律" }, { "HasMelodyArchitect", "建筑师旋律" } }; private static readonly Dictionary<string, string> BestPickNames = new Dictionary<string, string> { { "hasNeedleThrow", "Silk Spear" }, { "hasThreadSphere", "Thread Sphere" }, { "hasHarpoonDash", "prompt_hornet_silk_dash" }, { "hasSilkCharge", "Silk Charge" }, { "hasSilkBomb", "Silk Bomb" }, { "hasSilkBossNeedle", "Silk Boss Needle" }, { "hasNeedolin", "Needolin_Prompt" }, { "hasDash", "prompt_swiftstep" }, { "hasBrolly", "prompt_hornet_umbrella" }, { "hasDoubleJump", "Hornet_Double_Jump_Prompt" }, { "hasChargeSlash", "prompt_nail_art" }, { "hasSuperJump", "prompt_super_jump" }, { "hasWalljump", "Wall_Jump_Prompt" }, { "HasSeenEvaHeal", "EvaHeal_Prompt" }, { "hasParry", "prompt_hornet_parry" }, { "hasNeedolinMemoryPowerup", "deep_melody_prompts" }, { "hasFastTravelTeleport", "bellbeast_melody_prompts" }, { "HasSeenSilkHearts", "prompt_silkheart" }, { "hasJournal", "Journal_Prompt" }, { "ConstructedFarsight", "world_sense_prompt" }, { "WhiteFlower", "melody_prompts_0000_flower" }, { "HasMelodyConductor", "melody_prompts_0001_conductor" }, { "HasMelodyLibrarian", "melody_prompts_0002_librarian" }, { "HasMelodyArchitect", "melody_prompts_0000_architect" } }; private static readonly Dictionary<string, string[]> FallbackKeywords = new Dictionary<string, string[]> { { "hasNeedleThrow", new string[5] { "Silk Spear", "SilkSpear", "NeedleThrow", "needle", "spear" } }, { "hasThreadSphere", new string[6] { "Thread Storm", "ThreadStorm", "ThreadSphere", "thread", "storm", "sphere" } }, { "hasHarpoonDash", new string[5] { "Clawline", "Harpoon Dash", "HarpoonDash", "harpoon", "dash" } }, { "hasSilkCharge", new string[5] { "Sharpdart", "Silk Charge", "SilkCharge", "sharpdart", "silk charge" } }, { "hasSilkBomb", new string[7] { "Rune Rage", "RuneRage", "Silk Bomb", "SilkBomb", "rune", "rage", "silk bomb" } }, { "hasSilkBossNeedle", new string[8] { "Pale Nails", "PaleNails", "Silk Boss Needle", "SilkBossNeedle", "pale", "nail", "needle", "boss" } }, { "hasNeedolin", new string[2] { "Needolin", "needolin" } }, { "hasDash", new string[6] { "Swift Step", "SwiftStep", "Dash", "dash", "swift", "step" } }, { "hasBrolly", new string[8] { "Drifter's Cloak", "DriftersCloak", "Drifter", "Brolly", "Umbrella", "brolly", "drifter", "cloak" } }, { "hasDoubleJump", new string[7] { "Faydown Cloak", "FaydownCloak", "Double Jump", "DoubleJump", "faydown", "double", "jump" } }, { "hasChargeSlash", new string[7] { "Needle Strike", "NeedleStrike", "Charge Slash", "ChargeSlash", "needle strike", "charge", "slash" } }, { "hasSuperJump", new string[7] { "Silk Soar", "SilkSoar", "Super Jump", "SuperJump", "silk soar", "super", "jump" } }, { "hasWalljump", new string[8] { "Cling Grip", "ClingGrip", "Wall Jump", "WallJump", "cling", "grip", "wall", "jump" } }, { "HasSeenEvaHeal", new string[5] { "EvaHeal", "Eva", "Heal", "Windchime", "风铃" } }, { "hasParry", new string[4] { "Cross Stitch", "Parry", "Block", "格挡" } }, { "hasNeedolinMemoryPowerup", new string[4] { "Needolin", "Memory", "Powerup", "挽歌" } }, { "hasFastTravelTeleport", new string[5] { "FastTravel", "Teleport", "Fast", "Travel", "传送" } } }; public static readonly List<string> VerticalSkills = new List<string> { "hasSuperJump", "hasDoubleJump", "hasWalljump", "hasBrolly", "hasHarpoonDash" }; public static readonly List<string> HorizontalSkills = new List<string> { "hasDash", "hasBrolly", "hasHarpoonDash", "hasSilkCharge" }; public static readonly List<string> SpecialSkills = new List<string> { "hasNeedolin", "hasChargeSlash", "hasBrolly", "hasHarpoonDash", "HasSeenEvaHeal", "hasNeedolinMemoryPowerup", "hasFastTravelTeleport" }; public static readonly List<string> AttackSkills = new List<string> { "hasSilkBomb", "hasSilkBossNeedle", "hasThreadSphere", "hasSilkSpear", "hasSilkCharge", "hasParry", "hasNeedleThrow" }; private static readonly List<string> AllFields = SkillChineseNames.Keys.ToList(); private static readonly string[] SpecialPopupFields = new string[2] { "ConstructedFarsight", "WhiteFlower" }; private static Random _rng; private static Dictionary<string, Sprite> _icons = new Dictionary<string, Sprite>(); private static Sprite _fallback; private static bool _cacheBuilt; private static SavedItem[] _cachedAllItems; private static readonly Dictionary<string, string> SkillToItemMap = new Dictionary<string, string> { { "hasNeedleThrow", "Silk Spear" }, { "hasThreadSphere", "Thread Sphere" }, { "hasHarpoonDash", "Harpoon Dash" }, { "hasSilkCharge", "Silk Charge" }, { "hasSilkBomb", "Silk Bomb" }, { "hasSilkBossNeedle", "Silk Boss Needle" }, { "hasNeedolin", "Needolin" }, { "hasDash", "Swift Step" }, { "hasBrolly", "Drifter's Cloak" }, { "hasDoubleJump", "Faydown Cloak" }, { "hasChargeSlash", "Charge Slash" }, { "hasSuperJump", "Silk Soar" }, { "hasWalljump", "Cling Grip" }, { "hasParry", "Parry" } }; private static readonly HashSet<string> BannerSkillFields = new HashSet<string> { "hasBrolly", "hasDoubleJump", "hasChargeSlash", "hasNeedolinMemoryPowerup", "hasFastTravelTeleport" }; private static SkillGetMsg _cachedSkillMsgPrefab; private static PowerUpGetMsg _cachedPowerUpMsgPrefab; private static readonly string SKILL_MSG_BUNDLE_NAME = "c3ef29e95eda5580682bb076589a723c.bundle"; private static readonly string SKILL_MSG_ASSET_PATH = "Assets/Prefabs/UI/Hornet UI/Silk_Skill_Get_Prompt.prefab"; private static AssetBundle _cachedBundle; private static bool _bundleLoadAttempted = false; private static bool _popupErrorLogged = false; private static bool _itemDescriptionErrorLogged = false; private static readonly Dictionary<string, FieldInfo> PlayerDataFieldCache = new Dictionary<string, FieldInfo>(); private static FieldInfo[] _toolItemSkillFields; private static FieldInfo _lsFallbackField; private static FieldInfo _lsKeyField; private static FieldInfo _promptDescField; private static PropertyInfo _relicDescriptionProp; private static MethodInfo _atlasGetSpriteMethod; private static readonly HashSet<string> _iconMissSet = new HashSet<string>(); private static ToolCrest _cachedCrest; private static string _cachedCrestId; private static bool _powerUpMsgAttempted; private static bool _skillMsgFallbackAttempted; private static readonly Random DirectionRng = new Random(); private static readonly Dictionary<string, string> HeartFieldToEvent = new Dictionary<string, string> { { "CollectedHeartCoral", "CORAL" }, { "CollectedHeartFlower", "FLOWER" }, { "CollectedHeartHunter", "HUNTER" }, { "CollectedHeartClover", "CLOVER" } }; private static readonly Dictionary<string, string> MelodyFieldToEvent = new Dictionary<string, string> { { "HasMelodyConductor", "CONDUCTOR" }, { "HasMelodyLibrarian", "LIBRARIAN" }, { "HasMelodyArchitect", "ARCHITECT" } }; private static readonly StarterPermission[] FullRandomStarterPool = new StarterPermission[12] { new StarterPermission { Id = "perm:hasDash_L", DisplayName = "冲刺左", SkillField = "hasDash", AllowLeft = true }, new StarterPermission { Id = "perm:hasDash_R", DisplayName = "冲刺右", SkillField = "hasDash", AllowRight = true }, new StarterPermission { Id = "perm:hasHarpoonDash_L", DisplayName = "飞针左", SkillField = "hasHarpoonDash", AllowLeft = true }, new StarterPermission { Id = "perm:hasHarpoonDash_R", DisplayName = "飞针右", SkillField = "hasHarpoonDash", AllowRight = true }, new StarterPermission { Id = "perm:hasBrolly_L", DisplayName = "漂浮左", SkillField = "hasBrolly", AllowLeft = true }, new StarterPermission { Id = "perm:hasBrolly_R", DisplayName = "漂浮右", SkillField = "hasBrolly", AllowRight = true }, new StarterPermission { Id = "perm:hasWalljump_L", DisplayName = "壁跳左", SkillField = "hasWalljump", AllowLeft = true }, new StarterPermission { Id = "perm:hasWalljump_R", DisplayName = "壁跳右", SkillField = "hasWalljump", AllowRight = true }, new StarterPermission { Id = "perm:upward", DisplayName = "上劈权限", SkillField = "upward", IsAttack = true }, new StarterPermission { Id = "perm:left", DisplayName = "左劈权限", SkillField = "left", IsAttack = true }, new StarterPermission { Id = "perm:right", DisplayName = "右劈权限", SkillField = "right", IsAttack = true }, new StarterPermission { Id = "perm:heal", DisplayName = "回血权限", SkillField = "heal", IsHeal = true } }; public static bool UseNativeItemGiving { get; set; } = true; private static FieldInfo GetPlayerDataField(string field) { if (!PlayerDataFieldCache.TryGetValue(field, out var value)) { value = typeof(PlayerData).GetField(field, BindingFlags.Instance | BindingFlags.Public); PlayerDataFieldCache[field] = value; } return value; } public static void SetSeed(int seed) { _rng = ((seed == 0) ? new Random() : new Random(seed)); _cacheBuilt = false; } private static Random GetRng() { return _rng ?? (_rng = new Random()); } private static void BuildIconCache() { if (_cacheBuilt) { return; } _cacheBuilt = true; _icons.Clear(); SavedItem[] array = null; Sprite[] array2 = null; try { _cachedAllItems = Resources.FindObjectsOfTypeAll<SavedItem>(); array = _cachedAllItems; array2 = Resources.FindObjectsOfTypeAll<Sprite>(); } catch (Exception ex) { Plugin.Log.LogWarning("构建图标缓存时资源获取失败: " + ex.Message); return; } Object[] objs = (Object[])(object)array; string[] lower = BuildLowerSnapshot(objs); objs = (Object[])(object)array2; string[] lower2 = BuildLowerSnapshot(objs); Dictionary<string, string[]> dictionary = new Dictionary<string, string[]>(StringComparer.Ordinal); foreach (string item in AllFields.Concat(SpecialPopupFields)) { bool flag = false; if (BestPickNames.TryGetValue(item, out var bestName)) { SavedItem val = ((IEnumerable<SavedItem>)array).FirstOrDefault((Func<SavedItem, bool>)((SavedItem i) => Object.op_Implicit((Object)(object)i) && string.Equals(((Object)i).name, bestName, StringComparison.OrdinalIgnoreCase))); if ((Object)(object)val != (Object)null) { try { Sprite popupIcon = val.GetPopupIcon(); if (Object.op_Implicit((Object)(object)popupIcon)) { _icons[item] = popupIcon; flag = true; } } catch { } } if (!flag) { Sprite val2 = ((IEnumerable<Sprite>)array2).FirstOrDefault((Func<Sprite, bool>)((Sprite s) => Object.op_Implicit((Object)(object)s) && string.Equals(((Object)s).name, bestName, StringComparison.OrdinalIgnoreCase))); if ((Object)(object)val2 != (Object)null) { _icons[item] = val2; flag = true; } } } if (!flag && FallbackKeywords.TryGetValue(item, out var value)) { if (!dictionary.TryGetValue(item, out var value2)) { value2 = new string[value.Length]; for (int num = 0; num < value.Length; num++) { value2[num] = ((value[num] == null) ? null : value[num].ToLower()); } dictionary[item] = value2; } SavedItem val3 = FindSavedItemByKeywords(array, lower, value2); if ((Object)(object)val3 != (Object)null) { try { Sprite popupIcon2 = val3.GetPopupIcon(); if (Object.op_Implicit((Object)(object)popupIcon2)) { _icons[item] = popupIcon2; flag = true; } } catch { } } if (!flag) { Sprite val4 = FindSpriteByKeywords(array2, lower2, value2); if ((Object)(object)val4 != (Object)null) { _icons[item] = val4; flag = true; } } } if (!flag && !_popupErrorLogged) { Plugin.Log.LogWarning("✗ " + item + " 未找到图标"); _popupErrorLogged = true; } } if (!((Object)(object)_fallback == (Object)null)) { return; } SavedItem val5 = ((IEnumerable<SavedItem>)array).FirstOrDefault((Func<SavedItem, bool>)((SavedItem i) => Object.op_Implicit((Object)(object)i) && ((Object)i).name.Contains("Rosary"))); if (Object.op_Implicit((Object)(object)val5)) { try { _fallback = val5.GetPopupIcon(); } catch { } } if ((Object)(object)_fallback == (Object)null) { _fallback = ((IEnumerable<Sprite>)array2).FirstOrDefault((Func<Sprite, bool>)((Sprite s) => Object.op_Implicit((Object)(object)s) && ((Object)s).name.Contains("Rosary"))); } } private static string[] BuildLowerSnapshot(Object[] objs) { string[] array = new string[objs.Length]; for (int i = 0; i < objs.Length; i++) { Object val = objs[i]; if (!(val == (Object)null)) { string name = val.name; if (!string.IsNullOrEmpty(name)) { array[i] = name.ToLower(); } } } return array; } private static SavedItem FindSavedItemByKeywords(SavedItem[] items, string[] lower, string[] lowerKw) { for (int i = 0; i < items.Length; i++) { SavedItem val = items[i]; if ((Object)(object)val == (Object)null) { continue; } string text = lower[i]; if (text == null) { continue; } foreach (string text2 in lowerKw) { if (text2 != null && text.Contains(text2)) { return val; } } } return null; } private static Sprite FindSpriteByKeywords(Sprite[] sprites, string[] lower, string[] lowerKw) { for (int i = 0; i < sprites.Length; i++) { Sprite val = sprites[i]; if ((Object)(object)val == (Object)null) { continue; } string text = lower[i]; if (text == null) { continue; } foreach (string text2 in lowerKw) { if (text2 != null && text.Contains(text2)) { return val; } } } return null; } public static Sprite GetIcon(string field) { BuildIconCache(); if (_icons.TryGetValue(field, out var value) && (Object)(object)value != (Object)null) { return value; } if (_iconMissSet.Contains(field)) { return _fallback; } try { if (BestPickNames.TryGetValue(field, out var value2)) { foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if ((Object)(object)allLoadedAssetBundle == (Object)null) { continue; } string[] allAssetNames; try { allAssetNames = allLoadedAssetBundle.GetAllAssetNames(); } catch { continue; } if (allAssetNames == null) { continue; } string text = null; string[] array = allAssetNames; foreach (string text2 in array) { string fileName = Path.GetFileName(text2); if (string.Equals(fileName, value2, StringComparison.OrdinalIgnoreCase) || fileName.IndexOf(value2, StringComparison.OrdinalIgnoreCase) >= 0) { text = text2; break; } } if (text == null) { array = allAssetNames; foreach (string text3 in array) { if (Path.GetFileName(text3).IndexOf(value2.Replace("_", ""), StringComparison.OrdinalIgnoreCase) >= 0) { text = text3; break; } } } if (text != null) { Sprite val = allLoadedAssetBundle.LoadAsset<Sprite>(text); if ((Object)(object)val != (Object)null) { _icons[field] = val; return val; } } } foreach (AssetBundle allLoadedAssetBundle2 in AssetBundle.GetAllLoadedAssetBundles()) { if ((Object)(object)allLoadedAssetBundle2 == (Object)null) { continue; } string[] allAssetNames2; try { allAssetNames2 = allLoadedAssetBundle2.GetAllAssetNames(); } catch { continue; } if (allAssetNames2 == null) { continue; } string[] array = allAssetNames2; foreach (string text4 in array) { if (text4.IndexOf("Prompts.spriteatlas", StringComparison.OrdinalIgnoreCase) < 0) { continue; } Object val2 = allLoadedAssetBundle2.LoadAsset(text4); if (val2 == (Object)null) { continue; } if (_atlasGetSpriteMethod == null) { _atlasGetSpriteMethod = ((object)val2).GetType().GetMethod("GetSprite", new Type[1] { typeof(string) }); } MethodInfo atlasGetSpriteMethod = _atlasGetSpriteMethod; if (!(atlasGetSpriteMethod == null)) { object? obj3 = atlasGetSpriteMethod.Invoke(val2, new object[1] { value2 }); Sprite val3 = (Sprite)((obj3 is Sprite) ? obj3 : null); if ((Object)(object)val3 == (Object)null) { object? obj4 = atlasGetSpriteMethod.Invoke(val2, new object[1] { value2.TrimStart(new char[1] { '_' }) }); val3 = (Sprite)((obj4 is Sprite) ? obj4 : null); } if ((Object)(object)val3 != (Object)null) { _icons[field] = val3; return val3; } } } } } } catch { } _iconMissSet.Add(field); return _fallback; } public static string GetDisplayName(string skillField) { if (SkillChineseNames.TryGetValue(skillField, out var value)) { return Locale.Get(value); } return skillField; } public static PowerUps? GetPowerUpEnum(string skillField) { return skillField switch { "hasDash" => (PowerUps)0, "hasWalljump" => (PowerUps)1, "hasHarpoonDash" => (PowerUps)2, "hasNeedolin" => (PowerUps)3, "hasSuperJump" => (PowerUps)4, "HasSeenEvaHeal" => (PowerUps)5, _ => null, }; } public static bool TryGetSkillFieldFromItem(SavedItem item, out string skillField) { skillField = null; if ((Object)(object)item == (Object)null) { return false; } string name = ((Object)item).name; foreach (KeyValuePair<string, string> item2 in SkillToItemMap) { if (string.Equals(item2.Value, name, StringComparison.OrdinalIgnoreCase)) { skillField = item2.Key; return true; } } return false; } private static PowerUpGetMsg GetPowerUpMsgPrefab() { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_cachedPowerUpMsgPrefab != (Object)null) { return _cachedPowerUpMsgPrefab; } if (_powerUpMsgAttempted) { return null; } _powerUpMsgAttempted = true; try { PowerUpGetMsg[] array = Resources.FindObjectsOfTypeAll<PowerUpGetMsg>(); PowerUpGetMsg[] array2 = array; foreach (PowerUpGetMsg val in array2) { if ((Object)(object)val != (Object)null && (Object)(object)((Component)val).gameObject != (Object)null) { Scene scene = ((Component)val).gameObject.scene; if (((Scene)(ref scene)).name == null) { _cachedPowerUpMsgPrefab = val; return _cachedPowerUpMsgPrefab; } } } array2 = array; foreach (PowerUpGetMsg val2 in array2) { if ((Object)(object)val2 != (Object)null && (Object)(object)((Component)val2).gameObject != (Object)null) { _cachedPowerUpMsgPrefab = val2; return _cachedPowerUpMsgPrefab; } } } catch (Exception ex) { if (!_popupErrorLogged) { Plugin.Log.LogWarning("PowerUpGetMsg 预制体加载失败: " + ex.Message); } } return null; } private static SkillGetMsg GetSkillMsgPrefab() { //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_cachedSkillMsgPrefab != (Object)null) { return _cachedSkillMsgPrefab; } if (!_bundleLoadAttempted) { _bundleLoadAttempted = true; try { AssetBundle val = null; foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if ((Object)(object)allLoadedAssetBundle != (Object)null && ((Object)allLoadedAssetBundle).name == SKILL_MSG_BUNDLE_NAME) { val = allLoadedAssetBundle; break; } } if ((Object)(object)val == (Object)null) { string text = Path.Combine(Application.streamingAssetsPath, "aa", "StandaloneWindows64", SKILL_MSG_BUNDLE_NAME); if (File.Exists(text)) { val = AssetBundle.LoadFromFile(text); if ((Object)(object)val != (Object)null) { _cachedBundle = val; } } } if ((Object)(object)val != (Object)null) { GameObject val2 = val.LoadAsset<GameObject>(SKILL_MSG_ASSET_PATH); if ((Object)(object)val2 != (Object)null) { _cachedSkillMsgPrefab = val2.GetComponent<SkillGetMsg>(); if ((Object)(object)_cachedSkillMsgPrefab != (Object)null) { return _cachedSkillMsgPrefab; } } } } catch (Exception ex) { if (!_popupErrorLogged) { Plugin.Log.LogWarning("SkillGetMsg 预制体加载失败: " + ex.Message); } } } if (!_skillMsgFallbackAttempted) { _skillMsgFallbackAttempted = true; try { SkillGetMsg[] array = Resources.FindObjectsOfTypeAll<SkillGetMsg>(); foreach (SkillGetMsg val3 in array) { Scene scene = ((Component)val3).gameObject.scene; if (((Scene)(ref scene)).name == null && ((Object)val3).name.Contains("SkillGetMsg")) { _cachedSkillMsgPrefab = val3; return _cachedSkillMsgPrefab; } } } catch { } } return null; } private static bool CanShowSkillGetMsg() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) try { PlayerData instance = PlayerData.instance; if (instance == null) { return false; } string currentCrestID = instance.CurrentCrestID; if (string.IsNullOrEmpty(currentCrestID)) { return false; } ToolCrest crestByName = ToolItemManager.GetCrestByName(currentCrestID); if ((Object)(object)crestByName == (Object)null) { return false; } if (crestByName.SaveData.Slots == null) { return false; } return true; } catch { return false; } } private static ToolItemSkill GetSafeToolItemSkill(string skillField, string displayName, Sprite icon) { //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) if (SkillToItemMap.TryGetValue(skillField, out var itemName)) { try { ToolItem toolByName = ToolItemManager.GetToolByName(itemName); ToolItemSkill val = (ToolItemSkill)(object)((toolByName is ToolItemSkill) ? toolByName : null); if ((Object)(object)val != (Object)null && (Object)(object)val.PromptSprite != (Object)null) { return val; } } catch { } } SavedItem val2 = null; if (SkillToItemMap.TryGetValue(skillField, out itemName)) { try { BuildIconCache(); val2 = _cachedAllItems?.FirstOrDefault((Func<SavedItem, bool>)((SavedItem i) => Object.op_Implicit((Object)(object)i) && string.Equals(((Object)i).name, itemName, StringComparison.OrdinalIgnoreCase))); ToolItemSkill val3 = (ToolItemSkill)(object)((val2 is ToolItemSkill) ? val2 : null); if (val3 != null && (Object)(object)val3 != (Object)null && (Object)(object)val3.PromptSprite != (Object)null) { return val3; } } catch { } } try { ToolItemSkill val4 = ScriptableObject.CreateInstance<ToolItemSkill>(); if ((Object)(object)val4 == (Object)null) { return null; } if (_toolItemSkillFields == null) { _toolItemSkillFields = typeof(ToolItemSkill).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } FieldInfo[] toolItemSkillFields = _toolItemSkillFields; foreach (FieldInfo fieldInfo in toolItemSkillFields) { if (fieldInfo.FieldType == typeof(Sprite) && fieldInfo.GetValue(val4) == null) { fieldInfo.SetValue